CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/ext/libpng17/pngrutil.c
Views: 1401
#ifdef _MSC_VER1#pragma warning (disable:4018)2#pragma warning (disable:4146)3#endif45/* pngrutil.c - utilities to read a PNG file6*7* Last changed in libpng 1.7.0 [(PENDING RELEASE)]8* Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson9* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)10* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)11*12* This code is released under the libpng license.13* For conditions of distribution and use, see the disclaimer14* and license in png.h15*16* This file contains routines that are only called from within17* libpng itself during the course of reading an image.18*/1920#include "pngpriv.h"21#define PNG_SRC_FILE PNG_SRC_FILE_pngrutil2223#ifdef PNG_READ_SUPPORTED2425#if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)26/* The following is a variation on the above for use with the fixed27* point values used for gAMA and cHRM. Instead of png_error it28* issues a warning and returns (-1) - an invalid value because both29* gAMA and cHRM use *unsigned* integers for fixed point values.30*/31#define PNG_FIXED_ERROR (-1)3233static png_fixed_point /* PRIVATE */34png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)35{36png_uint_32 uval = png_get_uint_32(buf);3738if (uval <= PNG_UINT_31_MAX)39return (png_fixed_point)uval; /* known to be in range */4041/* The caller can turn off the warning by passing NULL. */42if (png_ptr != NULL)43png_warning(png_ptr, "PNG fixed point integer out of range");4445return PNG_FIXED_ERROR;46}47#endif /* READ_gAMA or READ_cHRM */4849#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED50/* NOTE: the read macros will obscure these definitions, so that if51* PNG_USE_READ_MACROS is set the library will not use them internally,52* but the APIs will still be available externally.53*54* The parentheses around "PNGAPI function_name" in the following three55* functions are necessary because they allow the macros to co-exist with56* these (unused but exported) functions.57*/5859/* Grab an unsigned 32-bit integer from a buffer in big-endian format. */60png_uint_32 (PNGAPI61png_get_uint_32)(png_const_bytep buf)62{63return PNG_U32(buf[0], buf[1], buf[2], buf[3]);64}6566/* Grab a signed 32-bit integer from a buffer in big-endian format. The67* data is stored in the PNG file in two's complement format and there68* is no guarantee that a 'png_int_32' is exactly 32 bits, therefore69* the following code does a two's complement to native conversion.70*/71png_int_32 (PNGAPI72png_get_int_32)(png_const_bytep buf)73{74return PNG_S32(buf[0], buf[1], buf[2], buf[3]);75}7677/* Grab an unsigned 16-bit integer from a buffer in big-endian format. */78png_uint_16 (PNGAPI79png_get_uint_16)(png_const_bytep buf)80{81return PNG_U16(buf[0], buf[1]);82}83#endif /* READ_INT_FUNCTIONS */8485/* This is an exported function however its error handling is too harsh for most86* internal use. For example if it were used for reading the chunk parameters87* it would error out even on ancillary chunks that can be ignored.88*/89png_uint_32 PNGAPI90png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)91{92png_uint_32 uval = png_get_uint_32(buf);9394if (uval > PNG_UINT_31_MAX)95png_error(png_ptr, "PNG unsigned integer out of range");9697return uval;98}99100/* Read and check the PNG file signature */101void /* PRIVATE */102png_read_sig(png_structrp png_ptr, png_inforp info_ptr)103{104png_size_t num_checked, num_to_check;105106/* Exit if the user application does not expect a signature. */107if (png_ptr->sig_bytes >= 8)108return;109110num_checked = png_ptr->sig_bytes;111num_to_check = 8 - num_checked;112113#ifdef PNG_IO_STATE_SUPPORTED114png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;115#endif116117/* The signature must be serialized in a single I/O call. */118png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);119png_ptr->sig_bytes = 8;120121if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))122{123if (num_checked < 4 &&124png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))125png_error(png_ptr, "Not a PNG file");126else127png_error(png_ptr, "PNG file corrupted by ASCII conversion");128}129if (num_checked < 3)130png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;131}132133/* Read data, and (optionally) run it through the CRC. */134void /* PRIVATE */135png_crc_read(png_structrp png_ptr, png_voidp buf, png_uint_32 length)136{137if (png_ptr == NULL)138return;139140png_read_data(png_ptr, buf, length);141png_calculate_crc(png_ptr, buf, length);142}143144/* Optionally skip data and then check the CRC. Depending on whether we are145* reading an ancillary or critical chunk, and how the program has set things146* up, we may calculate the CRC on the data and print a message. Returns true147* if the chunk should be discarded, otherwise false.148*/149int /* PRIVATE */150png_crc_finish(png_structrp png_ptr, png_uint_32 skip)151{152/* The size of the local buffer for inflate is a good guess as to a153* reasonable size to use for buffering reads from the application.154*/155while (skip > 0)156{157png_uint_32 len;158png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];159160len = (sizeof tmpbuf);161if (len > skip)162len = skip;163skip -= len;164165png_crc_read(png_ptr, tmpbuf, len);166}167168/* Compare the CRC stored in the PNG file with that calculated by libpng from169* the data it has read thus far. Do any required error handling. The170* second parameter is to allow a critical chunk (specifically PLTE) to be171* treated as ancillary.172*/173{174png_byte crc_bytes[4];175176# ifdef PNG_IO_STATE_SUPPORTED177png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;178# endif179180png_read_data(png_ptr, crc_bytes, 4);181182if (png_ptr->current_crc != crc_quiet_use &&183png_get_uint_32(crc_bytes) != png_ptr->crc)184{185if (png_ptr->current_crc == crc_error_quit)186png_chunk_error(png_ptr, "CRC");187188else189png_chunk_warning(png_ptr, "CRC");190191/* The only way to discard a chunk at present is to issue a warning.192* TODO: quiet_discard.193*/194return png_ptr->current_crc == crc_warn_discard;195}196}197198return 0;199}200201#if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\202defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\203defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\204defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)205/* Manage the read buffer; this simply reallocates the buffer if it is not small206* enough (or if it is not allocated). The routine returns a pointer to the207* buffer; if an error occurs and 'warn' is set the routine returns NULL, else208* it will call png_error (via png_malloc) on failure. (warn == 2 means209* 'silent').210*/211png_bytep /* PRIVATE */212png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)213{214png_bytep buffer = png_ptr->read_buffer;215216if (buffer != NULL && new_size > png_ptr->read_buffer_size)217{218png_ptr->read_buffer = NULL;219png_ptr->read_buffer_size = 0;220png_free(png_ptr, buffer);221buffer = NULL;222}223224if (buffer == NULL)225{226buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));227228if (buffer != NULL)229{230png_ptr->read_buffer = buffer;231png_ptr->read_buffer_size = new_size;232}233234else if (warn < 2) /* else silent */235{236if (warn != 0)237png_chunk_warning(png_ptr, "insufficient memory to read chunk");238239else240png_chunk_error(png_ptr, "insufficient memory to read chunk");241}242}243244return buffer;245}246#endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */247248/* png_inflate_claim: claim the zstream for some nefarious purpose that involves249* decompression. Returns Z_OK on success, else a zlib error code. It checks250* the owner but, in final release builds, just issues a warning if some other251* chunk apparently owns the stream. Prior to release it does a png_error.252*/253static int254png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)255{256if (png_ptr->zowner != 0)257{258char msg[64];259260PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);261/* So the message that results is "<chunk> using zstream"; this is an262* internal error, but is very useful for debugging. i18n requirements263* are minimal.264*/265(void)png_safecat(msg, (sizeof msg), 4, " using zstream");266#if PNG_RELEASE_BUILD267png_chunk_warning(png_ptr, msg);268png_ptr->zowner = 0;269#else270png_chunk_error(png_ptr, msg);271#endif272}273274/* Implementation note: unlike 'png_deflate_claim' this internal function275* does not take the size of the data as an argument. Some efficiency could276* be gained by using this when it is known *if* the zlib stream itself does277* not record the number; however, this is an illusion: the original writer278* of the PNG may have selected a lower window size, and we really must279* follow that because, for systems with with limited capabilities, we280* would otherwise reject the application's attempts to use a smaller window281* size (zlib doesn't have an interface to say "this or lower"!).282*283* inflateReset2 was added to zlib 1.2.4; before this the window could not be284* reset, therefore it is necessary to always allocate the maximum window285* size with earlier zlibs just in case later compressed chunks need it.286*/287{288int ret; /* zlib return code */289#if ZLIB_VERNUM >= 0x1240290int window_bits = 0;291292# if defined(PNG_SET_OPTION_SUPPORTED) && \293defined(PNG_MAXIMUM_INFLATE_WINDOW)294295if (png_ptr->maximum_inflate_window)296window_bits = 15;297298# endif299#endif /* ZLIB_VERNUM >= 0x1240 */300301/* Initialize the alloc/free callbacks every time: */302png_ptr->zstream.zalloc = png_zalloc;303png_ptr->zstream.zfree = png_zfree;304png_ptr->zstream.opaque = png_ptr;305306/* Set this for safety, just in case the previous owner left pointers to307* memory allocations.308*/309png_ptr->zstream.next_in = NULL;310png_ptr->zstream.avail_in = 0;311png_ptr->zstream.next_out = NULL;312png_ptr->zstream.avail_out = 0;313314/* If png_struct::zstream has been used before for decompression it does315* not need to be re-initialized, just reset.316*/317if (png_ptr->zstream.state != NULL)318{319#if ZLIB_VERNUM >= 0x1240320ret = inflateReset2(&png_ptr->zstream, window_bits);321#else322ret = inflateReset(&png_ptr->zstream);323#endif324}325326else327{328#if ZLIB_VERNUM >= 0x1240329ret = inflateInit2(&png_ptr->zstream, window_bits);330#else331ret = inflateInit(&png_ptr->zstream);332#endif333}334335#if ZLIB_VERNUM >= 0x1240336/* Turn off validation of the ADLER32 checksum */337if (png_ptr->current_crc == crc_quiet_use)338ret = inflateReset2(&png_ptr->zstream, -window_bits);339#endif340341if (ret == Z_OK && png_ptr->zstream.state != NULL)342{343png_ptr->zowner = owner;344png_ptr->zstream_ended = 0;345}346347else348{349png_zstream_error(&png_ptr->zstream, ret);350png_ptr->zstream_ended = 1;351}352353return ret;354}355356# ifdef window_bits357# undef window_bits358# endif359}360361/* This is a wrapper for the zlib deflate call which will handle larger buffer362* sizes than uInt. The input is limited to png_uint_32, because invariably363* the input comes from a chunk which has a 31-bit length, the output can be364* anything that fits in a png_alloc_size_t.365*366* This internal function sets png_struct::zstream_ended when the end of the367* decoded data has been encountered; this includes both a normal end and368* error conditions.369*/370static int371png_zlib_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,372/* INPUT: */ png_const_bytep *next_in_ptr, png_uint_32p avail_in_ptr,373/* OUTPUT: */ png_bytep *next_out_ptr, png_alloc_size_t *avail_out_ptr)374{375if (png_ptr->zowner == owner) /* Else not claimed */376{377int ret;378png_alloc_size_t avail_out = *avail_out_ptr;379png_uint_32 avail_in = *avail_in_ptr;380png_bytep output = *next_out_ptr;381png_const_bytep input = *next_in_ptr;382383/* zlib can't necessarily handle more than 65535 bytes at once (i.e. it384* can't even necessarily handle 65536 bytes) because the type uInt is385* "16 bits or more". Consequently it is necessary to chunk the input to386* zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the387* maximum value that can be stored in a uInt.) It is possible to set388* ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have389* a performance advantage, because it reduces the amount of data accessed390* at each step and that may give the OS more time to page it in.391*/392png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);393/* avail_in and avail_out are set below from 'size' */394png_ptr->zstream.avail_in = 0;395png_ptr->zstream.avail_out = 0;396397/* Read directly into the output if it is available (this is set to398* a local buffer below if output is NULL).399*/400if (output != NULL)401png_ptr->zstream.next_out = output;402403do404{405uInt avail;406Byte local_buffer[PNG_INFLATE_BUF_SIZE];407408/* zlib INPUT BUFFER */409/* The setting of 'avail_in' used to be outside the loop; by setting it410* inside it is possible to chunk the input to zlib and simply rely on411* zlib to advance the 'next_in' pointer. This allows arbitrary412* amounts of data to be passed through zlib at the unavoidable cost of413* requiring a window save (memcpy of up to 32768 output bytes)414* every ZLIB_IO_MAX input bytes.415*/416avail_in += png_ptr->zstream.avail_in; /* not consumed last time */417avail = ZLIB_IO_MAX;418419if (avail_in < avail)420avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */421422avail_in -= avail;423png_ptr->zstream.avail_in = avail;424425/* zlib OUTPUT BUFFER */426avail_out += png_ptr->zstream.avail_out; /* not written last time */427avail = ZLIB_IO_MAX; /* maximum zlib can process */428429if (output == NULL)430{431/* Reset the output buffer each time round if output is NULL and432* make available the full buffer, up to 'remaining_space'433*/434png_ptr->zstream.next_out = local_buffer;435if ((sizeof local_buffer) < avail)436avail = (sizeof local_buffer);437}438439if (avail_out < avail)440avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */441442png_ptr->zstream.avail_out = avail;443avail_out -= avail;444445/* zlib inflate call */446/* In fact 'avail_out' may be 0 at this point, that happens at the end447* of the read when the final LZ end code was not passed at the end of448* the previous chunk of input data. Tell zlib if we have reached the449* end of the output buffer.450*/451ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH :452(finish ? Z_FINISH : Z_SYNC_FLUSH));453} while (ret == Z_OK);454455/* For safety kill the local buffer pointer now */456if (output == NULL)457png_ptr->zstream.next_out = NULL;458459/* Claw back the 'size' and 'remaining_space' byte counts. */460avail_in += png_ptr->zstream.avail_in;461avail_out += png_ptr->zstream.avail_out;462463/* Update the input and output sizes; the updated values are the amount464* consumed or written, effectively the inverse of what zlib uses.465*/466*avail_out_ptr = avail_out;467if (output != NULL)468*next_out_ptr = png_ptr->zstream.next_out;469470*avail_in_ptr = avail_in;471*next_in_ptr = png_ptr->zstream.next_in;472473/* Ensure png_ptr->zstream.msg is set, ret can't be Z_OK at this point.474*/475debug(ret != Z_OK);476477if (ret != Z_BUF_ERROR)478png_ptr->zstream_ended = 1;479480png_zstream_error(&png_ptr->zstream, ret);481return ret;482}483484else485{486/* This is a bad internal error. The recovery assigns to the zstream msg487* pointer, which is not owned by the caller, but this is safe; it's only488* used on errors! (The {next,avail}_{in,out} values are not changed.)489*/490png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");491return Z_STREAM_ERROR;492}493}494495#ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED496/* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to497* allow the caller to do multiple calls if required. If the 'finish' flag is498* set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must499* be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and500* Z_OK or Z_STREAM_END will be returned on success.501*502* The input and output sizes are updated to the actual amounts of data consumed503* or written, not the amount available (as in a z_stream). The data pointers504* are not changed, so the next input is (data+input_size) and the next505* available output is (output+output_size).506*/507static int508png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,509/* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,510/* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)511{512png_uint_32 avail_in = *input_size_ptr;513png_alloc_size_t avail_out = *output_size_ptr;514int ret = png_zlib_inflate(png_ptr, owner, finish,515&input, &avail_in, &output, &avail_out);516517/* And implement the non-zlib semantics (the size values are updated to the518* amounts consumed and written, not the amount remaining.)519*/520*input_size_ptr -= avail_in;521*output_size_ptr -= avail_out;522return ret;523}524525/* Decompress trailing data in a chunk. The assumption is that read_buffer526* points at an allocated area holding the contents of a chunk with a527* trailing compressed part. What we get back is an allocated area528* holding the original prefix part and an uncompressed version of the529* trailing part (the malloc area passed in is freed).530*/531static int532png_decompress_chunk(png_structrp png_ptr,533png_uint_32 chunklength, png_uint_32 prefix_size,534png_alloc_size_t *newlength /* must be initialized to the maximum! */,535int terminate /*add a '\0' to the end of the uncompressed data*/)536{537/* TODO: implement different limits for different types of chunk.538*539* The caller supplies *newlength set to the maximum length of the540* uncompressed data, but this routine allocates space for the prefix and541* maybe a '\0' terminator too. We have to assume that 'prefix_size' is542* limited only by the maximum chunk size.543*/544png_alloc_size_t limit = PNG_SIZE_MAX;545546#ifdef PNG_SET_USER_LIMITS_SUPPORTED547if (png_ptr->user_chunk_malloc_max > 0 &&548png_ptr->user_chunk_malloc_max < limit)549limit = png_ptr->user_chunk_malloc_max;550#elif PNG_USER_CHUNK_MALLOC_MAX > 0551if (PNG_USER_CHUNK_MALLOC_MAX < limit)552limit = PNG_USER_CHUNK_MALLOC_MAX;553#endif554555if (limit >= prefix_size + (terminate != 0))556{557int ret;558559limit -= prefix_size + (terminate != 0);560561if (limit < *newlength)562*newlength = limit;563564/* Now try to claim the stream. */565ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);566567if (ret == Z_OK)568{569png_uint_32 lzsize = chunklength - prefix_size;570571ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,572/* input: */ png_ptr->read_buffer + prefix_size, &lzsize,573/* output: */ NULL, newlength);574575if (ret == Z_STREAM_END)576{577/* Use 'inflateReset' here, not 'inflateReset2' because this578* preserves the previously decided window size (otherwise it would579* be necessary to store the previous window size.) In practice580* this doesn't matter anyway, because png_inflate will call inflate581* with Z_FINISH in almost all cases, so the window will not be582* maintained.583*/584if (inflateReset(&png_ptr->zstream) == Z_OK)585{586/* Because of the limit checks above we know that the new,587* expanded, size will fit in a size_t (let alone an588* png_alloc_size_t). Use png_malloc_base here to avoid an589* extra OOM message.590*/591png_alloc_size_t new_size = *newlength;592png_alloc_size_t buffer_size = prefix_size + new_size +593(terminate != 0);594png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,595buffer_size));596597if (text != NULL)598{599ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,600png_ptr->read_buffer + prefix_size, &lzsize,601text + prefix_size, newlength);602603if (ret == Z_STREAM_END)604{605if (new_size == *newlength)606{607if (terminate != 0)608text[prefix_size + *newlength] = 0;609610if (prefix_size > 0)611memcpy(text, png_ptr->read_buffer, prefix_size);612613{614png_bytep old_ptr = png_ptr->read_buffer;615616png_ptr->read_buffer = text;617png_ptr->read_buffer_size = buffer_size;618text = old_ptr; /* freed below */619}620}621622else623{624/* The size changed on the second read, there can be no625* guarantee that anything is correct at this point.626* The 'msg' pointer has been set to "unexpected end of627* LZ stream", which is fine, but return an error code628* that the caller won't accept.629*/630ret = PNG_UNEXPECTED_ZLIB_RETURN;631}632}633634else if (ret == Z_OK)635ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */636637/* Free the text pointer (this is the old read_buffer on638* success)639*/640png_free(png_ptr, text);641642/* This really is very benign, but it's still an error because643* the extra space may otherwise be used as a Trojan Horse.644*/645if (ret == Z_STREAM_END &&646chunklength - prefix_size != lzsize)647png_chunk_benign_error(png_ptr, "extra compressed data");648}649650else651{652/* Out of memory allocating the buffer */653ret = Z_MEM_ERROR;654png_zstream_error(&png_ptr->zstream, Z_MEM_ERROR);655}656}657658else659{660/* inflateReset failed, store the error message */661png_zstream_error(&png_ptr->zstream, ret);662663if (ret == Z_STREAM_END)664ret = PNG_UNEXPECTED_ZLIB_RETURN;665}666}667668else if (ret == Z_OK)669ret = PNG_UNEXPECTED_ZLIB_RETURN;670671/* Release the claimed stream */672png_ptr->zowner = 0;673}674675else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */676ret = PNG_UNEXPECTED_ZLIB_RETURN;677678return ret;679}680681else682{683/* Application/configuration limits exceeded */684png_zstream_error(&png_ptr->zstream, Z_MEM_ERROR);685return Z_MEM_ERROR;686}687}688#endif /* READ_COMPRESSED_TEXT */689690#ifdef PNG_READ_iCCP_SUPPORTED691/* Perform a partial read and decompress, producing 'avail_out' bytes and692* reading from the current chunk as required.693*/694static int695png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,696png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,697int finish)698{699if (png_ptr->zowner == png_ptr->chunk_name)700{701int ret;702703/* next_in and avail_in must have been initialized by the caller. */704png_ptr->zstream.next_out = next_out;705png_ptr->zstream.avail_out = 0; /* set in the loop */706707do708{709if (png_ptr->zstream.avail_in == 0)710{711if (read_size > *chunk_bytes)712read_size = (uInt)*chunk_bytes;713*chunk_bytes -= read_size;714715if (read_size > 0)716png_crc_read(png_ptr, read_buffer, read_size);717718png_ptr->zstream.next_in = read_buffer;719png_ptr->zstream.avail_in = read_size;720}721722if (png_ptr->zstream.avail_out == 0)723{724uInt avail = ZLIB_IO_MAX;725if (avail > *out_size)726avail = (uInt)*out_size;727*out_size -= avail;728729png_ptr->zstream.avail_out = avail;730}731732/* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all733* the available output is produced; this allows reading of truncated734* streams.735*/736ret = inflate(&png_ptr->zstream,737*chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH :738Z_SYNC_FLUSH));739}740while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));741742*out_size += png_ptr->zstream.avail_out;743png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */744745/* Ensure the error message pointer is always set: */746png_zstream_error(&png_ptr->zstream, ret);747return ret;748}749750else751{752png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");753return Z_STREAM_ERROR;754}755}756#endif /* READ_iCCP */757758/* Chunk handling error handlers and utilities: */759/* Utility to read the chunk data from the start without processing it;760* a skip function.761*/762static void763png_handle_skip(png_structrp png_ptr)764/* Skip the entire chunk after the name,length header has been read: */765{766png_crc_finish(png_ptr, png_ptr->chunk_length);767}768769static void770png_handle_error(png_structrp png_ptr771# ifdef PNG_ERROR_TEXT_SUPPORTED772, png_const_charp error773# else774# define png_handle_error(pp,e) png_handle_error(pp)775# endif776)777/* Handle an error detected immediately after the chunk header has been778* read; this skips the rest of the chunk data and the CRC then signals779* a *benign* chunk error.780*/781{782png_handle_skip(png_ptr);783png_chunk_benign_error(png_ptr, error);784}785786#if defined (PNG_READ_gAMA_SUPPORTED) || defined (PNG_READ_sBIT_SUPPORTED) ||\787defined (PNG_READ_cHRM_SUPPORTED) || defined (PNG_READ_sRGB_SUPPORTED) ||\788defined (PNG_READ_iCCP_SUPPORTED) || defined (PNG_READ_tRNS_SUPPORTED) ||\789defined (PNG_READ_bKGD_SUPPORTED) || defined (PNG_READ_hIST_SUPPORTED) ||\790defined (PNG_READ_pHYs_SUPPORTED) || defined (PNG_READ_oFFs_SUPPORTED) ||\791defined (PNG_READ_sCAL_SUPPORTED) || defined (PNG_READ_tIME_SUPPORTED)792static void793png_handle_bad_length(png_structrp png_ptr)794{795png_handle_error(png_ptr, "invalid length");796}797#endif /* chunks that can generate length errors */798799/* Read and check the IDHR chunk */800static void801png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr)802{803png_byte buf[13];804png_uint_32 width, height;805png_byte bit_depth, color_type, compression_type, filter_method;806png_byte interlace_type;807808png_debug(1, "in png_handle_IHDR");809810/* Check the length (this is a chunk error; not benign) */811if (png_ptr->chunk_length != 13)812png_chunk_error(png_ptr, "invalid length");813814png_crc_read(png_ptr, buf, 13);815png_crc_finish(png_ptr, 0);816817width = png_get_uint_31(png_ptr, buf);818height = png_get_uint_31(png_ptr, buf + 4);819bit_depth = buf[8];820color_type = buf[9];821compression_type = buf[10];822filter_method = buf[11];823interlace_type = buf[12];824825/* Set internal variables */826png_ptr->width = width;827png_ptr->height = height;828png_ptr->bit_depth = bit_depth;829png_ptr->interlaced = interlace_type;830png_ptr->color_type = color_type;831png_ptr->filter_method = filter_method;832833png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,834color_type, interlace_type, compression_type, filter_method);835}836837/* Read and check the palette */838static void839png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr)840{841png_color palette[PNG_MAX_PALETTE_LENGTH];842png_uint_32 length = png_ptr->chunk_length;843png_uint_32 max_palette_length, num, i;844845png_debug(1, "in png_handle_PLTE");846847if (info_ptr == NULL)848return;849850if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR))851{852png_handle_error(png_ptr, "ignored in grayscale PNG");853return;854}855856#ifndef PNG_READ_OPT_PLTE_SUPPORTED857if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)858{859/* Skip the whole chunk: */860png_handle_skip(png_ptr);861return;862}863#endif864865if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)866{867png_crc_finish(png_ptr, length);868png_chunk_report(png_ptr, "invalid length",869((png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) ? PNG_CHUNK_ERROR :870PNG_CHUNK_FATAL));871return;872}873874/* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */875num = length / 3U;876877/* If the palette has 256 or fewer entries but is too large for the bit878* depth, we don't issue an error, to preserve the behavior of previous879* libpng versions. We silently truncate the unused extra palette entries880* here.881*/882if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)883max_palette_length = (1U << png_ptr->bit_depth);884else885max_palette_length = PNG_MAX_PALETTE_LENGTH;886887if (num > max_palette_length)888num = max_palette_length;889890for (i = 0; i < num; ++i)891{892png_byte buf[3];893894png_crc_read(png_ptr, buf, 3);895palette[i].red = buf[0];896palette[i].green = buf[1];897palette[i].blue = buf[2];898}899900png_crc_finish(png_ptr, length - num * 3U);901png_set_PLTE(png_ptr, info_ptr, palette, num);902903/* Ok, make our own copy since the set succeeded: */904debug(png_ptr->palette == NULL); /* should only get set once */905png_ptr->palette = png_voidcast(png_colorp, png_malloc(png_ptr,906sizeof (png_color[PNG_MAX_PALETTE_LENGTH])));907/* This works because we know png_set_PLTE also expands the palette to the908* full size:909*/910memcpy(png_ptr->palette, info_ptr->palette,911sizeof (png_color[PNG_MAX_PALETTE_LENGTH]));912png_ptr->num_palette = info_ptr->num_palette;913914/* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before915* IDAT. Prior to 1.6.0 this was not checked; instead the code merely916* checked the apparent validity of a tRNS chunk inserted before PLTE on a917* palette PNG. 1.6.0 attempts to rigorously follow the standard and918* therefore does a benign error if the erroneous condition is detected *and*919* cancels the tRNS if the benign error returns. The alternative is to920* amend the standard since it would be rather hypocritical of the standards921* maintainers to ignore it.922*/923#ifdef PNG_READ_tRNS_SUPPORTED924if (png_ptr->num_trans > 0 ||925(info_ptr->valid & PNG_INFO_tRNS) != 0)926{927/* Cancel this because otherwise it would be used if the transforms928* require it. Don't cancel the 'valid' flag because this would prevent929* detection of duplicate chunks.930*/931png_ptr->num_trans = 0;932info_ptr->num_trans = 0;933934png_chunk_benign_error(png_ptr, "tRNS must be after");935}936#endif /* READ_tRNS */937938#ifdef PNG_READ_hIST_SUPPORTED939if ((info_ptr->valid & PNG_INFO_hIST) != 0)940png_chunk_benign_error(png_ptr, "hIST must be after");941#endif /* READ_hIST */942943#ifdef PNG_READ_bKGD_SUPPORTED944if ((info_ptr->valid & PNG_INFO_bKGD) != 0)945png_chunk_benign_error(png_ptr, "bKGD must be after");946#endif /* READ_bKGD */947}948949static void950png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr)951{952png_debug(1, "in png_handle_IEND");953954png_crc_finish(png_ptr, png_ptr->chunk_length);955956/* Treat this as benign and terminate the PNG anyway: */957if (png_ptr->chunk_length != 0)958png_chunk_benign_error(png_ptr, "invalid length");959960PNG_UNUSED(info_ptr)961}962963#ifdef PNG_READ_gAMA_SUPPORTED964static void965png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr)966{967png_fixed_point igamma;968png_byte buf[4];969970png_debug(1, "in png_handle_gAMA");971972if (png_ptr->chunk_length != 4)973{974png_handle_bad_length(png_ptr);975return;976}977978png_crc_read(png_ptr, buf, 4);979980if (png_crc_finish(png_ptr, 0))981return;982983igamma = png_get_fixed_point(NULL, buf);984985png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);986png_colorspace_sync(png_ptr, info_ptr);987}988#else989# define png_handle_gAMA NULL990#endif /* READ_gAMA */991992#ifdef PNG_READ_sBIT_SUPPORTED993static void994png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr)995{996unsigned int truelen, i;997png_byte sample_depth;998png_byte buf[4];9991000png_debug(1, "in png_handle_sBIT");10011002if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))1003{1004png_handle_error(png_ptr, "duplicate");1005return;1006}10071008if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)1009{1010truelen = 3;1011sample_depth = 8;1012}10131014else1015{1016truelen = PNG_CHANNELS(*png_ptr);1017sample_depth = png_ptr->bit_depth;1018affirm(truelen <= 4);1019}10201021if (png_ptr->chunk_length != truelen)1022{1023png_handle_bad_length(png_ptr);1024return;1025}10261027buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;1028png_crc_read(png_ptr, buf, truelen);10291030if (png_crc_finish(png_ptr, 0))1031return;10321033for (i=0; i<truelen; ++i)1034if (buf[i] == 0 || buf[i] > sample_depth)1035{1036png_chunk_benign_error(png_ptr, "invalid");1037return;1038}10391040if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)1041{1042png_ptr->sig_bit.red = buf[0];1043png_ptr->sig_bit.green = buf[1];1044png_ptr->sig_bit.blue = buf[2];1045png_ptr->sig_bit.alpha = buf[3];1046}10471048else1049{1050png_ptr->sig_bit.gray = buf[0];1051png_ptr->sig_bit.red = buf[0];1052png_ptr->sig_bit.green = buf[0];1053png_ptr->sig_bit.blue = buf[0];1054png_ptr->sig_bit.alpha = buf[1];1055}10561057png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));1058}1059#else1060# define png_handle_sBIT NULL1061#endif /* READ_sBIT */10621063#ifdef PNG_READ_cHRM_SUPPORTED1064static void1065png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr)1066{1067png_byte buf[32];1068png_xy xy;10691070png_debug(1, "in png_handle_cHRM");10711072if (png_ptr->chunk_length != 32)1073{1074png_handle_bad_length(png_ptr);1075return;1076}10771078png_crc_read(png_ptr, buf, 32);10791080if (png_crc_finish(png_ptr, 0))1081return;10821083xy.whitex = png_get_fixed_point(NULL, buf);1084xy.whitey = png_get_fixed_point(NULL, buf + 4);1085xy.redx = png_get_fixed_point(NULL, buf + 8);1086xy.redy = png_get_fixed_point(NULL, buf + 12);1087xy.greenx = png_get_fixed_point(NULL, buf + 16);1088xy.greeny = png_get_fixed_point(NULL, buf + 20);1089xy.bluex = png_get_fixed_point(NULL, buf + 24);1090xy.bluey = png_get_fixed_point(NULL, buf + 28);10911092if (xy.whitex == PNG_FIXED_ERROR ||1093xy.whitey == PNG_FIXED_ERROR ||1094xy.redx == PNG_FIXED_ERROR ||1095xy.redy == PNG_FIXED_ERROR ||1096xy.greenx == PNG_FIXED_ERROR ||1097xy.greeny == PNG_FIXED_ERROR ||1098xy.bluex == PNG_FIXED_ERROR ||1099xy.bluey == PNG_FIXED_ERROR)1100{1101png_chunk_benign_error(png_ptr, "invalid");1102return;1103}11041105/* If a colorspace error has already been output skip this chunk */1106if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)1107return;11081109if (png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM)1110{1111png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;1112png_colorspace_sync(png_ptr, info_ptr);1113png_chunk_benign_error(png_ptr, "duplicate");1114return;1115}11161117png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;1118(void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,11191/*prefer cHRM values*/);1120png_colorspace_sync(png_ptr, info_ptr);1121}1122#else1123# define png_handle_cHRM NULL1124#endif /* READ_cHRM */11251126#ifdef PNG_READ_sRGB_SUPPORTED1127static void1128png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr)1129{1130png_byte intent;11311132png_debug(1, "in png_handle_sRGB");11331134if (png_ptr->chunk_length != 1)1135{1136png_handle_bad_length(png_ptr);1137return;1138}11391140png_crc_read(png_ptr, &intent, 1);11411142if (png_crc_finish(png_ptr, 0))1143return;11441145/* If a colorspace error has already been output skip this chunk */1146if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)1147return;11481149/* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect1150* this.1151*/1152if (png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT)1153{1154png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;1155png_colorspace_sync(png_ptr, info_ptr);1156png_chunk_benign_error(png_ptr, "too many profiles");1157return;1158}11591160(void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);1161png_colorspace_sync(png_ptr, info_ptr);1162}1163#else1164# define png_handle_sRGB NULL1165#endif /* READ_sRGB */11661167#ifdef PNG_READ_iCCP_SUPPORTED1168static void1169png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr)1170/* Note: this does not properly handle profiles that are > 64K under DOS */1171{1172png_const_charp errmsg = NULL; /* error message output, or no error */1173png_uint_32 length = png_ptr->chunk_length;1174int finished = 0; /* crc checked */11751176png_debug(1, "in png_handle_iCCP");11771178/* Consistent with all the above colorspace handling an obviously *invalid*1179* chunk is just ignored, so does not invalidate the color space. An1180* alternative is to set the 'invalid' flags at the start of this routine1181* and only clear them in they were not set before and all the tests pass.1182* The minimum 'deflate' stream is assumed to be just the 2 byte header and1183* 4 byte checksum. The keyword must be at least one character and there is1184* a terminator (0) byte and the compression method.1185*/1186if (length < 9)1187{1188png_handle_bad_length(png_ptr);1189return;1190}11911192/* If a colorspace error has already been output skip this chunk */1193if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)1194{1195png_crc_finish(png_ptr, length);1196return;1197}11981199/* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect1200* this.1201*/1202if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)1203{1204uInt read_length, keyword_length;1205char keyword[81];12061207/* Find the keyword; the keyword plus separator and compression method1208* bytes can be at most 81 characters long.1209*/1210read_length = 81; /* maximum */1211if (read_length > length)1212read_length = (uInt)/*SAFE*/length;12131214png_crc_read(png_ptr, (png_bytep)keyword, read_length);1215length -= read_length;12161217keyword_length = 0;1218while (keyword_length < 80 && keyword_length < read_length &&1219keyword[keyword_length] != 0)1220++keyword_length;12211222/* TODO: make the keyword checking common */1223if (keyword_length >= 1 && keyword_length <= 79)1224{1225/* We only understand '0' compression - deflate - so if we get a1226* different value we can't safely decode the chunk.1227*/1228if (keyword_length+1 < read_length &&1229keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)1230{1231read_length -= keyword_length+2;12321233if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)1234{1235Byte profile_header[132];1236Byte local_buffer[PNG_INFLATE_BUF_SIZE];1237png_alloc_size_t size = (sizeof profile_header);12381239png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);1240png_ptr->zstream.avail_in = read_length;1241(void)png_inflate_read(png_ptr, local_buffer,1242(sizeof local_buffer), &length, profile_header, &size,12430/*finish: don't, because the output is too small*/);12441245if (size == 0)1246{1247/* We have the ICC profile header; do the basic header checks.1248*/1249const png_uint_32 profile_length =1250png_get_uint_32(profile_header);12511252if (png_icc_check_length(png_ptr, &png_ptr->colorspace,1253keyword, profile_length))1254{1255/* The length is apparently ok, so we can check the 1321256* byte header.1257*/1258if (png_icc_check_header(png_ptr, &png_ptr->colorspace,1259keyword, profile_length, profile_header,1260(png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0))1261{1262/* Now read the tag table; a variable size buffer is1263* needed at this point, allocate one for the whole1264* profile. The header check has already validated1265* that none of these stuff will overflow.1266*/1267const png_uint_32 tag_count = png_get_uint_32(1268profile_header+128);1269png_bytep profile = png_read_buffer(png_ptr,1270profile_length, 2/*silent*/);12711272if (profile != NULL)1273{1274memcpy(profile, profile_header,1275(sizeof profile_header));12761277size = 12 * tag_count;12781279(void)png_inflate_read(png_ptr, local_buffer,1280(sizeof local_buffer), &length,1281profile + (sizeof profile_header), &size, 0);12821283/* Still expect a buffer error because we expect1284* there to be some tag data!1285*/1286if (size == 0)1287{1288if (png_icc_check_tag_table(png_ptr,1289&png_ptr->colorspace, keyword, profile_length,1290profile))1291{1292/* The profile has been validated for basic1293* security issues, so read the whole thing in.1294*/1295size = profile_length - (sizeof profile_header)1296- 12 * tag_count;12971298(void)png_inflate_read(png_ptr, local_buffer,1299(sizeof local_buffer), &length,1300profile + (sizeof profile_header) +130112 * tag_count, &size, 1/*finish*/);13021303if (length > 01304# ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED1305&& png_ptr->benign_error_action ==1306PNG_ERROR1307# endif /* BENIGN_READ_ERRORS */1308)1309errmsg = "extra compressed data";13101311/* But otherwise allow extra data: */1312else if (size == 0)1313{1314if (length > 0)1315{1316/* This can be handled completely, so1317* keep going.1318*/1319png_chunk_warning(png_ptr,1320"extra compressed data");1321}13221323png_crc_finish(png_ptr, length);1324finished = 1;13251326# if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 01327/* Check for a match against sRGB */1328png_icc_set_sRGB(png_ptr,1329&png_ptr->colorspace, profile,1330png_ptr->zstream.adler);1331# endif13321333/* Steal the profile for info_ptr. */1334if (info_ptr != NULL)1335{1336png_free_data(png_ptr, info_ptr,1337PNG_FREE_ICCP, 0);13381339info_ptr->iccp_name = png_voidcast(char*,1340png_malloc_base(png_ptr,1341keyword_length+1));1342if (info_ptr->iccp_name != NULL)1343{1344memcpy(info_ptr->iccp_name, keyword,1345keyword_length+1);1346info_ptr->iccp_profile = profile;1347png_ptr->read_buffer = NULL; /*steal*/1348info_ptr->free_me |= PNG_FREE_ICCP;1349info_ptr->valid |= PNG_INFO_iCCP;1350}13511352else1353{1354png_ptr->colorspace.flags |=1355PNG_COLORSPACE_INVALID;1356errmsg = "out of memory";1357}1358}13591360/* else the profile remains in the read1361* buffer which gets reused for subsequent1362* chunks.1363*/13641365if (info_ptr != NULL)1366png_colorspace_sync(png_ptr, info_ptr);13671368if (errmsg == NULL)1369{1370png_ptr->zowner = 0;1371return;1372}1373}13741375else if (size > 0)1376errmsg = "truncated";1377}13781379/* else png_icc_check_tag_table output an error */1380}13811382else /* profile truncated */1383errmsg = png_ptr->zstream.msg;1384}13851386else1387errmsg = "out of memory";1388}13891390/* else png_icc_check_header output an error */1391}13921393/* else png_icc_check_length output an error */1394}13951396else /* profile truncated */1397errmsg = png_ptr->zstream.msg;13981399/* Release the stream */1400png_ptr->zowner = 0;1401}14021403else /* png_inflate_claim failed */1404errmsg = png_ptr->zstream.msg;1405}14061407else1408errmsg = "bad compression method"; /* or missing */1409}14101411else1412errmsg = "bad keyword";1413}14141415else1416errmsg = "too many profiles";14171418/* Failure: the reason is in 'errmsg' */1419if (finished == 0)1420png_crc_finish(png_ptr, length);14211422png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;1423png_colorspace_sync(png_ptr, info_ptr);1424if (errmsg != NULL) /* else already output */1425png_chunk_benign_error(png_ptr, errmsg);1426}1427#else1428# define png_handle_iCCP NULL1429#endif /* READ_iCCP */14301431#ifdef PNG_READ_sPLT_SUPPORTED1432static void1433png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr)1434/* Note: this does not properly handle chunks that are > 64K under DOS */1435{1436png_uint_32 length = png_ptr->chunk_length;1437png_bytep entry_start, buffer;1438png_sPLT_t new_palette;1439png_sPLT_entryp pp;1440png_uint_32 data_length;1441int entry_size, i;1442png_uint_32 skip = 0;1443png_uint_32 dl;1444png_size_t max_dl;14451446png_debug(1, "in png_handle_sPLT");14471448#ifdef PNG_USER_LIMITS_SUPPORTED1449if (png_ptr->user_chunk_cache_max != 0)1450{1451if (png_ptr->user_chunk_cache_max == 1)1452{1453png_crc_finish(png_ptr, length);1454return;1455}14561457if (--png_ptr->user_chunk_cache_max == 1)1458{1459/* Warn the first time */1460png_chunk_benign_error(png_ptr, "no space in chunk cache");1461png_crc_finish(png_ptr, length);1462return;1463}1464}1465#endif /* USER_LIMITS */14661467buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);1468if (buffer == NULL)1469{1470png_crc_finish(png_ptr, length);1471png_chunk_benign_error(png_ptr, "out of memory");1472return;1473}14741475/* WARNING: this may break if size_t is less than 32 bits; it is assumed1476* that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a1477* potential breakage point if the types in pngconf.h aren't exactly right.1478*/1479png_crc_read(png_ptr, buffer, length);14801481if (png_crc_finish(png_ptr, skip))1482return;14831484buffer[length] = 0;14851486for (entry_start = buffer; *entry_start; entry_start++)1487/* Empty loop to find end of name */ ;14881489++entry_start;14901491/* A sample depth should follow the separator, and we should be on it */1492if (length < 2U || entry_start > buffer + (length - 2U))1493{1494png_chunk_benign_error(png_ptr, "malformed");1495return;1496}14971498new_palette.depth = *entry_start++;1499entry_size = (new_palette.depth == 8 ? 6 : 10);1500/* This must fit in a png_uint_32 because it is derived from the original1501* chunk data length.1502*/1503data_length = length - (png_uint_32)(entry_start - buffer);15041505/* Integrity-check the data length */1506if (data_length % entry_size)1507{1508png_chunk_benign_error(png_ptr, "invalid length");1509return;1510}15111512dl = (png_int_32)(data_length / entry_size);1513max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));15141515if (dl > max_dl)1516{1517png_chunk_benign_error(png_ptr, "exceeds system limits");1518return;1519}15201521new_palette.nentries = (png_int_32)(data_length / entry_size);15221523new_palette.entries = png_voidcast(png_sPLT_entryp, png_malloc_base(1524png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry))));15251526if (new_palette.entries == NULL)1527{1528png_chunk_benign_error(png_ptr, "out of memory");1529return;1530}15311532for (i = 0; i < new_palette.nentries; i++)1533{1534pp = new_palette.entries + i;15351536if (new_palette.depth == 8)1537{1538pp->red = *entry_start++;1539pp->green = *entry_start++;1540pp->blue = *entry_start++;1541pp->alpha = *entry_start++;1542}15431544else1545{1546pp->red = png_get_uint_16(entry_start); entry_start += 2;1547pp->green = png_get_uint_16(entry_start); entry_start += 2;1548pp->blue = png_get_uint_16(entry_start); entry_start += 2;1549pp->alpha = png_get_uint_16(entry_start); entry_start += 2;1550}15511552pp->frequency = png_get_uint_16(entry_start); entry_start += 2;1553}15541555/* Discard all chunk data except the name and stash that */1556new_palette.name = (png_charp)buffer;15571558png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);15591560png_free(png_ptr, new_palette.entries);1561}1562#else1563# define png_handle_sPLT NULL1564#endif /* READ_sPLT */15651566#ifdef PNG_READ_tRNS_SUPPORTED1567static void1568png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr)1569{1570png_uint_32 num_trans;1571png_byte readbuf[PNG_MAX_PALETTE_LENGTH];15721573png_debug(1, "in png_handle_tRNS");15741575png_ptr->num_trans = 0U; /* safety */15761577if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))1578{1579/* libpng 1.7.0: this used to be a benign error, but it doesn't look very1580* benign because it has security implications; libpng ignores the second1581* tRNS, so if you can find something that ignores the first instead you1582* can choose which image the user sees depending on the PNG decoder.1583*/1584png_crc_finish(png_ptr, png_ptr->chunk_length);1585png_chunk_error(png_ptr, "duplicate");1586return;1587}15881589if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)1590{1591png_byte buf[2];15921593if (png_ptr->chunk_length != 2)1594{1595png_handle_bad_length(png_ptr);1596return;1597}15981599png_crc_read(png_ptr, buf, 2);1600num_trans = 1U;1601png_ptr->trans_color.gray = png_get_uint_16(buf);1602}16031604else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)1605{1606png_byte buf[6];16071608if (png_ptr->chunk_length != 6)1609{1610png_handle_bad_length(png_ptr);1611return;1612}16131614png_crc_read(png_ptr, buf, 6);1615num_trans = 1U;1616png_ptr->trans_color.red = png_get_uint_16(buf);1617png_ptr->trans_color.green = png_get_uint_16(buf + 2);1618png_ptr->trans_color.blue = png_get_uint_16(buf + 4);1619}16201621else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)1622{1623/* png_find_chunk_op checks this: */1624debug(png_ptr->mode & PNG_HAVE_PLTE);16251626num_trans = png_ptr->chunk_length;16271628if (num_trans > png_ptr->num_palette || num_trans == 0)1629{1630png_handle_bad_length(png_ptr);1631return;1632}16331634png_crc_read(png_ptr, readbuf, num_trans);1635}16361637else1638{1639png_handle_error(png_ptr, "invalid");1640return;1641}16421643if (png_crc_finish(png_ptr, 0))1644return;16451646/* Set it into the info_struct: */1647png_set_tRNS(png_ptr, info_ptr, readbuf, num_trans, &png_ptr->trans_color);16481649/* Now make a copy of the buffer if one is required (palette images). */1650debug(png_ptr->trans_alpha == NULL);1651if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)1652{1653png_ptr->trans_alpha = png_voidcast(png_bytep,1654png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH));1655memset(png_ptr->trans_alpha, 0xFFU, PNG_MAX_PALETTE_LENGTH);1656memcpy(png_ptr->trans_alpha, info_ptr->trans_alpha, num_trans);1657}16581659png_ptr->num_trans = png_check_bits(png_ptr, num_trans, 9);1660}1661#else1662# define png_handle_tRNS NULL1663#endif /* READ_tRNS */16641665#ifdef PNG_READ_bKGD_SUPPORTED1666static void1667png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr)1668{1669unsigned int truelen;1670png_byte buf[6];1671png_color_16 background;16721673png_debug(1, "in png_handle_bKGD");16741675if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))1676{1677png_handle_error(png_ptr, "duplicate");1678return;1679}16801681if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)1682truelen = 1;16831684else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)1685truelen = 6;16861687else1688truelen = 2;16891690if (png_ptr->chunk_length != truelen)1691{1692png_handle_bad_length(png_ptr);1693return;1694}16951696png_crc_read(png_ptr, buf, truelen);16971698if (png_crc_finish(png_ptr, 0))1699return;17001701/* We convert the index value into RGB components so that we can allow1702* arbitrary RGB values for background when we have transparency, and1703* so it is easy to determine the RGB values of the background color1704* from the info_ptr struct.1705*/1706if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)1707{1708background.index = buf[0];17091710if (info_ptr && info_ptr->num_palette)1711{1712if (buf[0] >= info_ptr->num_palette)1713{1714png_chunk_benign_error(png_ptr, "invalid index");1715return;1716}17171718background.red = png_check_u16(png_ptr, png_ptr->palette[buf[0]].red);1719background.green =1720png_check_u16(png_ptr, png_ptr->palette[buf[0]].green);1721background.blue =1722png_check_u16(png_ptr, png_ptr->palette[buf[0]].blue);1723}17241725else1726background.red = background.green = background.blue = 0;17271728background.gray = 0;1729}17301731else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */1732{1733background.index = 0;1734background.red =1735background.green =1736background.blue =1737background.gray = png_get_uint_16(buf);1738}17391740else1741{1742background.index = 0;1743background.red = png_get_uint_16(buf);1744background.green = png_get_uint_16(buf + 2);1745background.blue = png_get_uint_16(buf + 4);1746background.gray = 0;1747}17481749png_set_bKGD(png_ptr, info_ptr, &background);1750}1751#else1752# define png_handle_bKGD NULL1753#endif /* READ_bKGD */17541755#ifdef PNG_READ_hIST_SUPPORTED1756static void1757png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr)1758{1759unsigned int num, i;1760png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];17611762png_debug(1, "in png_handle_hIST");17631764if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))1765{1766png_handle_error(png_ptr, "duplicate");1767return;1768}17691770num = png_ptr->chunk_length / 2;17711772if (num != png_ptr->num_palette || 2*num != png_ptr->chunk_length)1773{1774png_handle_bad_length(png_ptr);1775return;1776}17771778for (i = 0; i < num; i++)1779{1780png_byte buf[2];17811782png_crc_read(png_ptr, buf, 2);1783readbuf[i] = png_get_uint_16(buf);1784}17851786if (png_crc_finish(png_ptr, 0))1787return;17881789png_set_hIST(png_ptr, info_ptr, readbuf);1790}1791#else1792# define png_handle_hIST NULL1793#endif /* READ_hIST */17941795#ifdef PNG_READ_pHYs_SUPPORTED1796static void1797png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr)1798{1799png_byte buf[9];1800png_uint_32 res_x, res_y;1801int unit_type;18021803png_debug(1, "in png_handle_pHYs");18041805if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))1806{1807png_handle_error(png_ptr, "duplicate");1808return;1809}18101811if (png_ptr->chunk_length != 9)1812{1813png_handle_bad_length(png_ptr);1814return;1815}18161817png_crc_read(png_ptr, buf, 9);18181819if (png_crc_finish(png_ptr, 0))1820return;18211822res_x = png_get_uint_32(buf);1823res_y = png_get_uint_32(buf + 4);1824unit_type = buf[8];1825png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);1826}1827#else1828# define png_handle_pHYs NULL1829#endif /* READ_pHYs */18301831#ifdef PNG_READ_oFFs_SUPPORTED /* EXTENSION, before IDAT, no duplicates */1832static void1833png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr)1834{1835png_byte buf[9];1836png_int_32 offset_x, offset_y;1837int unit_type;18381839png_debug(1, "in png_handle_oFFs");18401841if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))1842{1843png_handle_error(png_ptr, "duplicate");1844return;1845}18461847if (png_ptr->chunk_length != 9)1848{1849png_handle_bad_length(png_ptr);1850return;1851}18521853png_crc_read(png_ptr, buf, 9);18541855if (png_crc_finish(png_ptr, 0))1856return;18571858offset_x = png_get_int_32(buf);1859offset_y = png_get_int_32(buf + 4);1860unit_type = buf[8];1861png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);1862}1863#else1864# define png_handle_oFFs NULL1865#endif /* READ_oFFs */18661867#ifdef PNG_READ_pCAL_SUPPORTED /* EXTENSION: before IDAT, no duplicates */1868static void1869png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr)1870{1871png_int_32 X0, X1;1872png_byte type, nparams;1873png_bytep buffer, buf, units, endptr;1874png_charpp params;1875int i;18761877png_debug(1, "in png_handle_pCAL");18781879if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))1880{1881png_handle_error(png_ptr, "duplicate");1882return;1883}18841885png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",1886png_ptr->chunk_length + 1);18871888buffer = png_read_buffer(png_ptr, png_ptr->chunk_length+1, 2/*silent*/);18891890if (buffer == NULL)1891{1892png_handle_error(png_ptr, "out of memory");1893return;1894}18951896png_crc_read(png_ptr, buffer, png_ptr->chunk_length);18971898if (png_crc_finish(png_ptr, 0))1899return;19001901buffer[png_ptr->chunk_length] = 0; /* Null terminate the last string */19021903png_debug(3, "Finding end of pCAL purpose string");1904for (buf = buffer; *buf; buf++)1905/* Empty loop */ ;19061907endptr = buffer + png_ptr->chunk_length;19081909/* We need to have at least 12 bytes after the purpose string1910* in order to get the parameter information.1911*/1912if (endptr - buf <= 12)1913{1914png_chunk_benign_error(png_ptr, "invalid");1915return;1916}19171918png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");1919X0 = png_get_int_32((png_bytep)buf+1);1920X1 = png_get_int_32((png_bytep)buf+5);1921type = buf[9];1922nparams = buf[10];1923units = buf + 11;19241925png_debug(3, "Checking pCAL equation type and number of parameters");1926/* Check that we have the right number of parameters for known1927* equation types.1928*/1929if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||1930(type == PNG_EQUATION_BASE_E && nparams != 3) ||1931(type == PNG_EQUATION_ARBITRARY && nparams != 3) ||1932(type == PNG_EQUATION_HYPERBOLIC && nparams != 4))1933{1934png_chunk_benign_error(png_ptr, "invalid parameter count");1935return;1936}19371938else if (type >= PNG_EQUATION_LAST)1939{1940png_chunk_benign_error(png_ptr, "unrecognized equation type");1941return;1942}19431944for (buf = units; *buf; buf++)1945/* Empty loop to move past the units string. */ ;19461947png_debug(3, "Allocating pCAL parameters array");19481949params = png_voidcast(png_charpp, png_malloc_base(png_ptr,1950nparams * (sizeof (png_charp))));19511952if (params == NULL)1953{1954png_chunk_benign_error(png_ptr, "out of memory");1955return;1956}19571958/* Get pointers to the start of each parameter string. */1959for (i = 0; i < nparams; i++)1960{1961buf++; /* Skip the null string terminator from previous parameter. */19621963png_debug1(3, "Reading pCAL parameter %d", i);19641965for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)1966/* Empty loop to move past each parameter string */ ;19671968/* Make sure we haven't run out of data yet */1969if (buf > endptr)1970{1971png_free(png_ptr, params);1972png_chunk_benign_error(png_ptr, "invalid data");1973return;1974}1975}19761977png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,1978(png_charp)units, params);19791980png_free(png_ptr, params);1981}1982#else1983# define png_handle_pCAL NULL1984#endif /* READ_pCAL */19851986#ifdef PNG_READ_sCAL_SUPPORTED1987/* Read the sCAL chunk */1988static void1989png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr)1990{1991png_uint_32 length = png_ptr->chunk_length;1992png_bytep buffer;1993png_size_t i;1994int state;19951996png_debug(1, "in png_handle_sCAL");19971998if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))1999{2000png_handle_error(png_ptr, "duplicate");2001return;2002}20032004/* Need unit type, width, \0, height: minimum 4 bytes */2005if (length < 4)2006{2007png_handle_bad_length(png_ptr);2008return;2009}20102011png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",2012length + 1);20132014buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);20152016if (buffer == NULL)2017{2018png_handle_error(png_ptr, "out of memory");2019return;2020}20212022png_crc_read(png_ptr, buffer, length);2023buffer[length] = 0; /* Null terminate the last string */20242025if (png_crc_finish(png_ptr, 0))2026return;20272028/* Validate the unit. */2029if (buffer[0] != 1 && buffer[0] != 2)2030{2031png_chunk_benign_error(png_ptr, "invalid unit");2032return;2033}20342035/* Validate the ASCII numbers, need two ASCII numbers separated by2036* a '\0' and they need to fit exactly in the chunk data.2037*/2038i = 1;2039state = 0;20402041if (!png_check_fp_number((png_const_charp)buffer, length, &state, &i) ||2042i >= length || buffer[i++] != 0)2043png_chunk_benign_error(png_ptr, "bad width format");20442045else if (!PNG_FP_IS_POSITIVE(state))2046png_chunk_benign_error(png_ptr, "non-positive width");20472048else2049{2050png_size_t heighti = i;20512052state = 0;2053if (!png_check_fp_number((png_const_charp)buffer, length, &state, &i) ||2054i != length)2055png_chunk_benign_error(png_ptr, "bad height format");20562057else if (!PNG_FP_IS_POSITIVE(state))2058png_chunk_benign_error(png_ptr, "non-positive height");20592060else2061/* This is the (only) success case. */2062png_set_sCAL_s(png_ptr, info_ptr, buffer[0],2063(png_charp)buffer+1, (png_charp)buffer+heighti);2064}2065}2066#else2067# define png_handle_sCAL NULL2068#endif /* READ_sCAL */20692070#ifdef PNG_READ_tIME_SUPPORTED2071static void2072png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr)2073{2074png_byte buf[7];2075png_time mod_time;20762077png_debug(1, "in png_handle_tIME");20782079if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))2080{2081png_handle_error(png_ptr, "duplicate");2082return;2083}20842085if (png_ptr->chunk_length != 7)2086{2087png_handle_bad_length(png_ptr);2088return;2089}20902091png_crc_read(png_ptr, buf, 7);20922093if (png_crc_finish(png_ptr, 0))2094return;20952096mod_time.second = buf[6];2097mod_time.minute = buf[5];2098mod_time.hour = buf[4];2099mod_time.day = buf[3];2100mod_time.month = buf[2];2101mod_time.year = png_get_uint_16(buf);21022103png_set_tIME(png_ptr, info_ptr, &mod_time);2104}2105#else2106# define png_handle_tIME NULL2107#endif /* READ_tIME */21082109#ifdef PNG_READ_tEXt_SUPPORTED2110static void2111png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr)2112{2113png_uint_32 length = png_ptr->chunk_length;2114png_text text_info;2115png_bytep buffer;2116png_charp key;2117png_charp text;2118png_uint_32 skip = 0;21192120png_debug(1, "in png_handle_tEXt");21212122#ifdef PNG_USER_LIMITS_SUPPORTED2123if (png_ptr->user_chunk_cache_max != 0)2124{2125if (png_ptr->user_chunk_cache_max == 1)2126{2127png_crc_finish(png_ptr, length);2128return;2129}21302131if (--png_ptr->user_chunk_cache_max == 1)2132{2133png_handle_error(png_ptr, "no space in chunk cache");2134return;2135}2136}2137#endif /* USER_LIMITS */21382139buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);21402141if (buffer == NULL)2142{2143png_handle_error(png_ptr, "out of memory");2144return;2145}21462147png_crc_read(png_ptr, buffer, length);21482149if (png_crc_finish(png_ptr, skip))2150return;21512152key = (png_charp)buffer;2153key[length] = 0;21542155for (text = key; *text; text++)2156/* Empty loop to find end of key */ ;21572158if (text != key + length)2159text++;21602161text_info.compression = PNG_TEXT_COMPRESSION_NONE;2162text_info.key = key;2163text_info.lang = NULL;2164text_info.lang_key = NULL;2165text_info.itxt_length = 0;2166text_info.text = text;2167text_info.text_length = strlen(text);21682169if (png_set_text_2(png_ptr, info_ptr, &text_info, 1))2170png_warning(png_ptr, "Insufficient memory to process text chunk");2171}2172#else2173# define png_handle_tEXt NULL2174#endif /* READ_tEXt */21752176#ifdef PNG_READ_zTXt_SUPPORTED2177static void2178png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr)2179{2180png_uint_32 length = png_ptr->chunk_length;2181png_const_charp errmsg = NULL;2182png_bytep buffer;2183png_uint_32 keyword_length;21842185png_debug(1, "in png_handle_zTXt");21862187#ifdef PNG_USER_LIMITS_SUPPORTED2188if (png_ptr->user_chunk_cache_max != 0)2189{2190if (png_ptr->user_chunk_cache_max == 1)2191{2192png_crc_finish(png_ptr, length);2193return;2194}21952196if (--png_ptr->user_chunk_cache_max == 1)2197{2198png_handle_error(png_ptr, "no space in chunk cache");2199return;2200}2201}2202#endif /* USER_LIMITS */22032204/* Note, "length" is sufficient here; we won't be adding2205* a null terminator later.2206*/2207buffer = png_read_buffer(png_ptr, length, 2/*silent*/);22082209if (buffer == NULL)2210{2211png_handle_error(png_ptr, "out of memory");2212return;2213}22142215png_crc_read(png_ptr, buffer, length);22162217if (png_crc_finish(png_ptr, 0))2218return;22192220/* TODO: also check that the keyword contents match the spec! */2221for (keyword_length = 0;2222keyword_length < length && buffer[keyword_length] != 0;2223++keyword_length)2224/* Empty loop to find end of name */ ;22252226if (keyword_length > 79 || keyword_length < 1)2227errmsg = "bad keyword";22282229/* zTXt must have some LZ data after the keyword, although it may expand to2230* zero bytes; we need a '\0' at the end of the keyword, the compression type2231* then the LZ data:2232*/2233else if (keyword_length + 3 > length)2234errmsg = "truncated";22352236else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)2237errmsg = "unknown compression type";22382239else2240{2241png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;22422243/* TODO: at present png_decompress_chunk imposes a single application2244* level memory limit, this should be split to different values for iCCP2245* and text chunks.2246*/2247if (png_decompress_chunk(png_ptr, length, keyword_length+2,2248&uncompressed_length, 1/*terminate*/) == Z_STREAM_END)2249{2250png_text text;22512252/* It worked; png_ptr->read_buffer now looks like a tEXt chunk except2253* for the extra compression type byte and the fact that it isn't2254* necessarily '\0' terminated.2255*/2256buffer = png_ptr->read_buffer;2257buffer[uncompressed_length+(keyword_length+2)] = 0;22582259text.compression = PNG_TEXT_COMPRESSION_zTXt;2260text.key = (png_charp)buffer;2261text.text = (png_charp)(buffer + keyword_length+2);2262text.text_length = uncompressed_length;2263text.itxt_length = 0;2264text.lang = NULL;2265text.lang_key = NULL;22662267if (png_set_text_2(png_ptr, info_ptr, &text, 1))2268errmsg = "insufficient memory";2269}22702271else2272errmsg = png_ptr->zstream.msg;2273}22742275if (errmsg != NULL)2276png_chunk_benign_error(png_ptr, errmsg);2277}2278#else2279# define png_handle_zTXt NULL2280#endif /* READ_zTXt */22812282#ifdef PNG_READ_iTXt_SUPPORTED2283static void2284png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr)2285{2286png_uint_32 length = png_ptr->chunk_length;2287png_const_charp errmsg = NULL;2288png_bytep buffer;2289png_uint_32 prefix_length;22902291png_debug(1, "in png_handle_iTXt");22922293#ifdef PNG_USER_LIMITS_SUPPORTED2294if (png_ptr->user_chunk_cache_max != 0)2295{2296if (png_ptr->user_chunk_cache_max == 1)2297{2298png_crc_finish(png_ptr, length);2299return;2300}23012302if (--png_ptr->user_chunk_cache_max == 1)2303{2304png_handle_error(png_ptr, "no space in chunk cache");2305return;2306}2307}2308#endif /* USER_LIMITS */23092310buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);23112312if (buffer == NULL)2313{2314png_handle_error(png_ptr, "out of memory");2315return;2316}23172318png_crc_read(png_ptr, buffer, length);23192320if (png_crc_finish(png_ptr, 0))2321return;23222323/* First the keyword. */2324for (prefix_length=0;2325prefix_length < length && buffer[prefix_length] != 0;2326++prefix_length)2327/* Empty loop */ ;23282329/* Perform a basic check on the keyword length here. */2330if (prefix_length > 79 || prefix_length < 1)2331errmsg = "bad keyword";23322333/* Expect keyword, compression flag, compression type, language, translated2334* keyword (both may be empty but are 0 terminated) then the text, which may2335* be empty.2336*/2337else if (prefix_length + 5 > length)2338errmsg = "truncated";23392340else if (buffer[prefix_length+1] == 0 ||2341(buffer[prefix_length+1] == 1 &&2342buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))2343{2344int compressed = buffer[prefix_length+1] != 0;2345png_uint_32 language_offset, translated_keyword_offset;2346png_alloc_size_t uncompressed_length = 0;23472348/* Now the language tag */2349prefix_length += 3;2350language_offset = prefix_length;23512352for (; prefix_length < length && buffer[prefix_length] != 0;2353++prefix_length)2354/* Empty loop */ ;23552356/* WARNING: the length may be invalid here, this is checked below. */2357translated_keyword_offset = ++prefix_length;23582359for (; prefix_length < length && buffer[prefix_length] != 0;2360++prefix_length)2361/* Empty loop */ ;23622363/* prefix_length should now be at the trailing '\0' of the translated2364* keyword, but it may already be over the end. None of this arithmetic2365* can overflow because chunks are at most 2^31 bytes long, but on 16-bit2366* systems the available allocation may overflow.2367*/2368++prefix_length;23692370if (!compressed && prefix_length <= length)2371uncompressed_length = length - prefix_length;23722373else if (compressed && prefix_length < length)2374{2375uncompressed_length = PNG_SIZE_MAX;23762377/* TODO: at present png_decompress_chunk imposes a single application2378* level memory limit, this should be split to different values for2379* iCCP and text chunks.2380*/2381if (png_decompress_chunk(png_ptr, length, prefix_length,2382&uncompressed_length, 1/*terminate*/) == Z_STREAM_END)2383buffer = png_ptr->read_buffer;23842385else2386errmsg = png_ptr->zstream.msg;2387}23882389else2390errmsg = "truncated";23912392if (errmsg == NULL)2393{2394png_text text;23952396buffer[uncompressed_length+prefix_length] = 0;23972398if (compressed == 0)2399text.compression = PNG_ITXT_COMPRESSION_NONE;24002401else2402text.compression = PNG_ITXT_COMPRESSION_zTXt;24032404text.key = (png_charp)buffer;2405text.lang = (png_charp)buffer + language_offset;2406text.lang_key = (png_charp)buffer + translated_keyword_offset;2407text.text = (png_charp)buffer + prefix_length;2408text.text_length = 0;2409text.itxt_length = uncompressed_length;24102411if (png_set_text_2(png_ptr, info_ptr, &text, 1))2412errmsg = "insufficient memory";2413}2414}24152416else2417errmsg = "bad compression info";24182419if (errmsg != NULL)2420png_chunk_benign_error(png_ptr, errmsg);2421}2422#else2423# define png_handle_iTXt NULL2424#endif /* READ_iTXt */24252426/* UNSUPPORTED CHUNKS */2427#define png_handle_sTER NULL2428#define png_handle_fRAc NULL2429#define png_handle_gIFg NULL2430#define png_handle_gIFt NULL2431#define png_handle_gIFx NULL2432#define png_handle_dSIG NULL24332434/* IDAT has special treatment below */2435#define png_handle_IDAT NULL24362437/******************************************************************************2438* UNKNOWN HANDLING LOGIC2439*2440* There are three ways an unknown chunk may arise:2441*2442* 1) Chunks not in the spec.2443* 2) Chunks in the spec where libpng support doesn't exist or has been compiled2444* out. These are recognized, for a very small performance benefit at the2445* cost of maintaining a png_known_chunks entry for each one.2446* 3) Chunks supported by libpng which have been marked as 'unknown' by the2447* application.2448*2449* Prior to 1.7.0 all three cases are handled the same way, in 1.7.0 some2450* attempt is made to optimize (2) and (3) by storing flags in2451* png_struct::known_unknown for chunks in the spec which have been marked for2452* unknown handling.2453*2454* There are three things libpng can do with an unknown chunk, in order of2455* preference:2456*2457* 1) If PNG_READ_USER_CHUNKS_SUPPORTED call an application supplied callback2458* with all the chunk data. If this doesn't handle the chunk in prior2459* versions of libpng the chunk would be stored if safe otherwise skipped.2460* In 1.7.0 the specified chunk unknown handling is used.2461* 2) If PNG_SAVE_UNKNOWN_CHUNKS_SUPPOPRTED the chunk may be saved in the2462* info_struct (if there is one.)2463* 3) The chunk can be skipped.2464*2465* In effect libpng tries each option in turn. (2) looks at any per-chunk2466* unknown handling then, if one wasn't specified, the overall default.2467*2468* IHDR and IEND cannot be treated as unknown. PLTE and IDAT can. Prior to2469* 1.7.0 they couldn't be skipped without a png_error. 1.7.0 adds an extension2470* which allows any critical chunk to be skipped so long as IDAT is skipped; the2471* logic for failing on critical chunks only applies if the image data is being2472* processed.2473*2474* The default behavior is (3); unknown chunks are simply skipped. 1.7.0 uses2475* this to optimize the read code when possible.2476*2477* In the read code PNG_READ_UNKNOWN_CHUNKS_SUPPORTED is set only if either (1)2478* or (2) or both are supported.2479*2480*****************************************************************************/2481#ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED2482static int2483png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)2484{2485png_byte chunk_string[5];24862487PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);2488return png_handle_as_unknown(png_ptr, chunk_string);2489}2490#endif /* SAVE_UNKNOWN_CHUNKS */24912492#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED2493/* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */2494static void2495png_make_unknown_chunk(png_structrp png_ptr, png_unknown_chunkp chunk,2496png_bytep data)2497{2498chunk->data = data;2499chunk->size = png_ptr->chunk_length;2500PNG_CSTRING_FROM_CHUNK(chunk->name, png_ptr->chunk_name);2501/* 'mode' is a flag array, only three of the bottom four bits are public: */2502chunk->location =2503png_ptr->mode & (PNG_HAVE_IHDR+PNG_HAVE_PLTE+PNG_AFTER_IDAT);2504}25052506/* Handle an unknown, or known but disabled, chunk */2507void /* PRIVATE */2508png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,2509png_bytep chunk_data)2510{2511png_debug(1, "in png_handle_unknown");25122513/* NOTE: this code is based on the code in libpng-1.4.12 except for fixing2514* the bug which meant that setting a non-default behavior for a specific2515* chunk would be ignored (the default was always used unless a user2516* callback was installed).2517*2518* 'keep' is the value from the png_chunk_unknown_handling, the setting for2519* this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it2520* will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.2521* This is just an optimization to avoid multiple calls to the lookup2522* function.2523*2524* One of the following methods will read the chunk or skip it (at least one2525* of these is always defined because this is the only way to switch on2526* PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)2527*/2528# ifdef PNG_READ_USER_CHUNKS_SUPPORTED2529/* The user callback takes precedence over the chunk handling option: */2530if (png_ptr->read_user_chunk_fn != NULL)2531{2532png_unknown_chunk unknown_chunk;2533int ret;25342535/* Callback to user unknown chunk handler */2536png_make_unknown_chunk(png_ptr, &unknown_chunk, chunk_data);2537ret = png_ptr->read_user_chunk_fn(png_ptr, &unknown_chunk);25382539/* ret is:2540* negative: An error occurred; png_chunk_error will be called.2541* zero: The chunk was not handled, the chunk will be discarded2542* unless png_set_keep_unknown_chunks has been used to set2543* a 'keep' behavior for this particular chunk, in which2544* case that will be used. A critical chunk will cause an2545* error at this point unless it is to be saved.2546* positive: The chunk was handled, libpng will ignore/discard it.2547*/2548if (ret > 0)2549return;25502551else if (ret < 0)2552png_chunk_error(png_ptr, "application error");25532554/* Else: use the default handling. */2555}2556# endif /* READ_USER_CHUNKS */25572558# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED2559{2560int keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);25612562/* keep is currently just the per-chunk setting, if there was no2563* setting change it to the global default now (note that this may2564* still be AS_DEFAULT) then obtain the cache of the chunk if required,2565* if not simply skip the chunk.2566*/2567if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)2568keep = png_ptr->unknown_default;25692570if (keep == PNG_HANDLE_CHUNK_ALWAYS ||2571(keep == PNG_HANDLE_CHUNK_IF_SAFE &&2572PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))2573# ifdef PNG_USER_LIMITS_SUPPORTED2574switch (png_ptr->user_chunk_cache_max)2575{2576case 2:2577png_ptr->user_chunk_cache_max = 1;2578png_chunk_benign_error(png_ptr, "no space in chunk cache");2579/* FALL THROUGH */2580case 1:2581/* NOTE: prior to 1.6.0 this case resulted in an unknown2582* critical chunk being skipped, now there will be a hard2583* error below.2584*/2585break;25862587default: /* not at limit */2588--(png_ptr->user_chunk_cache_max);2589/* FALL THROUGH */2590case 0: /* no limit */2591# endif /* USER_LIMITS */2592/* Here when the limit isn't reached or when limits are2593* compiled out; store the chunk.2594*/2595{2596png_unknown_chunk unknown_chunk;25972598png_make_unknown_chunk(png_ptr, &unknown_chunk,2599chunk_data);2600png_set_unknown_chunks(png_ptr, info_ptr, &unknown_chunk,26011);2602return;2603}2604# ifdef PNG_USER_LIMITS_SUPPORTED2605}2606# endif /* USER_LIMITS */2607}2608# else /* !SAVE_UNKNOWN_CHUNKS */2609PNG_UNUSED(info_ptr)2610# endif /* !SAVE_UNKNOWN_CHUNKS */26112612/* This is the 'skip' case, where the read callback (if any) returned 0 and2613* the save code did not save the chunk.2614*/2615if (PNG_CHUNK_CRITICAL(png_ptr->chunk_name))2616png_chunk_error(png_ptr, "unhandled critical chunk");2617}2618#endif /* READ_UNKNOWN_CHUNKS */26192620/* This function is called to verify that a chunk name is valid.2621* This function can't have the "critical chunk check" incorporated2622* into it, since in the future we will need to be able to call user2623* functions to handle unknown critical chunks after we check that2624* the chunk name itself is valid.2625*/26262627/* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:2628*2629* ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))2630*/26312632void /* PRIVATE */2633png_check_chunk_name(png_const_structrp png_ptr, const png_uint_32 chunk_name)2634{2635int i;2636png_uint_32 cn=chunk_name;26372638png_debug(1, "in png_check_chunk_name");26392640for (i=1; i<=4; ++i)2641{2642int c = cn & 0xff;26432644if (c < 65 || c > 122 || (c > 90 && c < 97))2645png_chunk_error(png_ptr, "invalid chunk type");26462647cn >>= 8;2648}2649}2650void /* PRIVATE */2651png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length)2652{2653png_alloc_size_t limit = PNG_UINT_31_MAX;26542655# ifdef PNG_SET_USER_LIMITS_SUPPORTED2656if (png_ptr->user_chunk_malloc_max > 0 &&2657png_ptr->user_chunk_malloc_max < limit)2658limit = png_ptr->user_chunk_malloc_max;2659# elif PNG_USER_CHUNK_MALLOC_MAX > 02660if (PNG_USER_CHUNK_MALLOC_MAX < limit)2661limit = PNG_USER_CHUNK_MALLOC_MAX;2662# endif2663if (png_ptr->chunk_name == png_IDAT)2664{2665/* color_type 0 x 2 3 4 x 6 */2666int channels[]={1,0,3,1,2,0,4};2667png_alloc_size_t idat_limit = PNG_UINT_31_MAX;2668size_t row_factor =2669(png_ptr->width * channels[png_ptr->color_type] *2670(png_ptr->bit_depth > 8? 2: 1)2671+ 1 + (png_ptr->interlaced? 6: 0));2672if (png_ptr->height > PNG_UINT_32_MAX/row_factor)2673idat_limit=PNG_UINT_31_MAX;2674else2675idat_limit = png_ptr->height * row_factor;2676row_factor = row_factor > 32566? 32566 : row_factor;2677idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */2678idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;2679limit = limit < idat_limit? idat_limit : limit;2680}26812682if (length > limit)2683{2684png_debug2(0," length = %lu, limit = %lu",2685(unsigned long)length,(unsigned long)limit);2686png_chunk_error(png_ptr, "chunk data is too large");2687}2688}26892690/* This is the known chunk table; it contains an entry for each supported2691* chunk.2692*/2693static const struct2694{2695void (*handle)(png_structrp png_ptr, png_infop info_ptr);2696png_uint_32 name;2697unsigned int before :5;2698unsigned int after :5;2699}2700png_known_chunks[] =2701/* To make the code easier to write the following defines are used, note that2702* before_end should never trip - it would indicate that libpng attempted to2703* read beyond the IEND chunk.2704*2705* 'within_IDAT' is used for IDAT chunks; PNG_AFTER_IDAT must not be set, but2706* PNG_HAVE_IDAT may be set.2707*/2708#define before_end PNG_HAVE_IEND /* Should be impossible */2709#define within_IDAT (before_end+PNG_AFTER_IDAT)2710#define before_IDAT (within_IDAT+PNG_HAVE_IDAT)2711#define before_PLTE (before_IDAT+PNG_HAVE_PLTE)2712#define before_start (before_PLTE+PNG_HAVE_IHDR)2713#define at_start 02714#define after_start PNG_HAVE_IHDR2715#define after_PLTE (after_start+PNG_HAVE_PLTE) /* NOTE: PLTE optional */2716#define after_IDAT (after_PLTE+PNG_AFTER_IDAT) /* NOTE: PLTE optional */27172718/* See pngchunk.h for how this works: */2719#define PNG_CHUNK_END(n, c1, c2, c3, c4, before, after)\2720{ png_handle_ ## n, png_ ##n, before, after }2721#define PNG_CHUNK(n, c1, c2, c3, c4, before, after)\2722PNG_CHUNK_END(n, c1, c2, c3, c4, before, after),2723#define PNG_CHUNK_BEGIN(n, c1, c2, c3, c4, before, after)\2724PNG_CHUNK_END(n, c1, c2, c3, c4, before, after),2725{2726# include "pngchunk.h"2727};2728#undef PNG_CHUNK_START2729#undef PNG_CHUNK2730#undef PNG_CHUNK_END27312732#define C_KNOWN ((sizeof png_known_chunks)/(sizeof png_known_chunks[0]))27332734/* See: scripts/chunkhash.c for code to generate this. This reads the same2735* description file (pngchunk.h) as is included above. Whenever2736* that file is changed chunkhash needs to be re-run to generate the lines2737* following this comment.2738*2739* PNG_CHUNK_HASH modifes its argument and returns an index. png_chunk_index is2740* a function which does the same thing without modifying the value of the2741* argument. Both macro and function always return a valid index; to detect2742* known chunks it is necessary to check png_known_chunks[index].name against2743* the hashed name.2744*/2745static const png_byte png_chunk_lut[64] =2746{274710, 20, 7, 3, 0, 23, 8, 0, 0, 11, 24, 0, 0, 0, 0, 4,274812, 0, 0, 0, 13, 0, 0, 0, 25, 0, 0, 0, 2, 0, 0, 0,27490, 6, 17, 0, 15, 0, 5, 19, 26, 0, 0, 0, 18, 0, 0, 9,27501, 0, 21, 0, 22, 14, 0, 0, 0, 0, 0, 0, 16, 0, 0, 02751};27522753#define PNG_CHUNK_HASH(n)\2754png_chunk_lut[0x3f & (((n += n >> 2),n += n >> 8),n += n >> 16)]27552756static png_byte2757png_chunk_index(png_uint_32 name)2758{2759name += name >> 2;2760name += name >> 8;2761name += name >> 16;2762return png_chunk_lut[name & 0x3f];2763}27642765#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED2766/* Mark a known chunk to be handled as unknown. */2767void /*PRIVATE*/2768png_cache_known_unknown(png_structrp png_ptr, png_const_bytep add, int keep)2769/* Update the png_struct::known_unknown bit cache which stores whether each2770* known chunk should be treated as unknown.2771*2772* This cache exists to avoid doing the search loop on every chunk while2773* handling chunks. This code is only ever used if unknown handling is2774* invoked, and the loop is isolated code; the function is called from2775* add_one_chunk in pngset.c once for each unknown and while this is2776* happening no other code is being run in this thread.2777*/2778{2779/* The cache only stores whether or not to handle the chunk; specifically2780* whether or not keep is 0.2781*/2782png_uint_32 name = PNG_CHUNK_FROM_STRING(add);27832784debug(PNG_HANDLE_CHUNK_AS_DEFAULT == 0 && C_KNOWN <= 32);27852786/* But do not treat IHDR or IEND as unknown. This is historical; it2787* always was this way, it's not clear if PLTE can always safely be2788* treated as unknown, but it is allowed.2789*/2790if (name != png_IHDR && name != png_IEND)2791{2792png_byte i = png_chunk_index(name);27932794if (png_known_chunks[i].name == name)2795{2796{2797if (keep != PNG_HANDLE_CHUNK_AS_DEFAULT)2798{2799png_ptr->known_unknown |= 1U << i;28002801# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED2802if (keep == PNG_HANDLE_CHUNK_ALWAYS ||2803(keep == PNG_HANDLE_CHUNK_IF_SAFE &&2804PNG_CHUNK_ANCILLARY(name)))2805png_ptr->save_unknown |= 1U << i;28062807else /* PNG_HANDLE_CHUNK_NEVER || !SAFE */2808png_ptr->save_unknown &= ~(1U << i);2809# endif /* SAVE_UNKNOWN_CHUNKS */2810}28112812else2813png_ptr->known_unknown &= ~(1U << i);2814}2815}28162817/* else this is not a known chunk */2818}28192820else /* 1.7.0: inform the app writer; */2821png_app_warning(png_ptr, "IHDR, IEND cannot be treated as unknown");28222823}2824#endif /* HANDLE_AS_UNKNOWN */28252826/* Handle chunk position requirements in a consistent way. The chunk must2827* come after 'after' and before 'before', either of which may be 0. If it2828* does the function returns true, if it does not an appropriate chunk error2829* is issued; benign for non-critical chunks, fatal for critical ones.2830*/2831static int2832png_handle_position(png_const_structrp png_ptr, unsigned int chunk)2833{2834unsigned int before = png_known_chunks[chunk].before;2835unsigned int after = png_known_chunks[chunk].after;28362837# ifdef PNG_ERROR_TEXT_SUPPORTED2838png_const_charp error = NULL;2839# endif /* ERROR_TEXT */28402841/* PLTE is optional with all color types except PALETTE, so for the other2842* color types clear it from the 'after' bits.2843*2844* TODO: find some better way of recognizing the case where there is a PLTE2845* and it follows after_PLTE chunks (see the complex stuff in handle_PLTE.)2846*/2847if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)2848after &= PNG_BIC_MASK(PNG_HAVE_PLTE);28492850if ((png_ptr->mode & before) == 0 &&2851(png_ptr->mode & after) == after)2852return 1;28532854/* The error case; do before first (it is normally more important) */2855# ifdef PNG_ERROR_TEXT_SUPPORTED2856switch (before & -before) /* Lowest set bit */2857{2858case 0:2859/* Check 'after'; only one bit set. */2860switch (after)2861{2862case PNG_HAVE_IHDR:2863error = "missing IHDR";2864break;28652866case PNG_HAVE_PLTE:2867error = "must occur after PLTE";2868break;28692870case PNG_AFTER_IDAT:2871error = "must come after IDAT";2872break;28732874default:2875impossible("invalid 'after' position");2876}2877break;28782879case PNG_HAVE_IHDR:2880error = "must occur first";2881break;28822883case PNG_HAVE_PLTE:2884error = "must come before PLTE";2885break;28862887case PNG_HAVE_IDAT:2888error = "must come before IDAT";2889break;28902891default:2892impossible("invalid 'before' position");2893}2894# endif /* ERROR_TEXT */28952896png_chunk_report(png_ptr, error, PNG_CHUNK_CRITICAL(png_ptr->chunk_name) ?2897PNG_CHUNK_FATAL : PNG_CHUNK_ERROR);2898return 0;2899}29002901/* This is the shared chunk handling function, used for both the sequential and2902* progressive reader.2903*/2904png_chunk_op /* PRIVATE */2905png_find_chunk_op(png_structrp png_ptr)2906{2907/* Given a chunk in png_struct::{chunk_name,chunk_length} validate the name2908* and work out how it should be handled. This function checks the chunk2909* location using png_struct::mode and will set the PNG_AFTER_IDAT bit if2910* appropriate but otherwise makes no changes to the stream read state.2911*2912* png_chunk_skip Skip this chunk2913* png_chunk_unknown This is an unknown chunk which can't be skipped;2914* the unknown handler must be called with all the2915* chunk data.2916* png_chunk_process_all The caller must call png_chunk_handle to handle2917* the chunk, when this call is made all the chunk2918* data must be available to the handler.2919* png_chunk_process_part The handler expects data in png_struct::zstream.2920* {next,avail}_in and does not require all of the2921* data at once (as png_read_process_IDAT).2922*/2923png_uint_32 chunk_name = png_ptr->chunk_name;2924unsigned int mode = png_ptr->mode;2925unsigned int index;29262927/* This function should never be called if IEND has been set:2928*/2929debug((mode & PNG_HAVE_IEND) == 0);29302931/* IDAT logic: we are only *after* IDAT when we start reading the first2932* following (non-IDAT) chunk, this may already have been set in the IDAT2933* handling code, but if IDAT is handled as unknown this doesn't happen.2934*/2935if (chunk_name != png_IDAT && (mode & PNG_HAVE_IDAT) != 0)2936mode = png_ptr->mode |= PNG_AFTER_IDAT;29372938index = png_chunk_index(chunk_name);29392940if (png_known_chunks[index].name == chunk_name)2941{2942/* Known chunks have a position requirement; check it, badly positioned2943* chunks that do not error out in png_handle_position are simply skipped.2944*2945* API CHANGE: libpng 1.7.0: prior versions of libpng did not check2946* ordering requirements for known chunks where the support for reading2947* them had been configured out of libpng. This seems dangerous; the2948* user chunk callback could still see them and crash as a result.2949*/2950if (!png_handle_position(png_ptr, index))2951return png_chunk_skip;29522953/* Do the mode update.2954*2955* API CHANGE 1.7.0: the 'HAVE' flags are now consistently set *before*2956* the chunk is handled. Previously only IDAT was handled this way. This2957* can only affect an app that was previously handling PLTE itself in a2958* callback, however this seems to be impossible.2959*/2960switch (chunk_name)2961{2962case png_IHDR: png_ptr->mode |= PNG_HAVE_IHDR; break;2963case png_PLTE: png_ptr->mode |= PNG_HAVE_PLTE; break;2964case png_IDAT: png_ptr->mode |= PNG_HAVE_IDAT; break;2965case png_IEND: png_ptr->mode |= PNG_HAVE_IEND; break;2966default: break;2967}29682969# ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED2970/* A known chunk may still be treated as unknown. Check for that. */2971if (!((png_ptr->known_unknown >> index) & 1U))2972# endif /* HANDLE_AS_UNKNOWN */2973{2974/* This is a known chunk that is not being treated as unknown. If2975* it is IDAT then partial processing is done, otherwise (at present)2976* the whole thing is processed in one shot2977*2978* TODO: this is a feature of the legacy use of the sequential read2979* code in the handlers, fix this.2980*/2981if (chunk_name == png_IDAT)2982return png_chunk_process_part;29832984/* Check for a known chunk where support has been compiled out of2985* libpng. We know it cannot be a critical chunk; support for those2986* cannot be removed.2987*/2988if (png_known_chunks[index].handle != NULL)2989return png_chunk_process_all;29902991# ifdef PNG_READ_USER_CHUNKS_SUPPORTED2992if (png_ptr->read_user_chunk_fn != NULL)2993return png_chunk_unknown;2994# endif /* READ_USER_CHUNKS */29952996# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED2997/* There is no per-chunk special handling set for this chunk2998* (because of the test on known_unknown above) so only the2999* default unknown handling behavior matters. We skip the chunk3000* if the behavior is 'NEVER' or 'DEFAULT'. This is irrelevant3001* if SAVE_UNKNOWN_CHUNKS is not supported.3002*/3003if (png_ptr->unknown_default > PNG_HANDLE_CHUNK_NEVER)3004return png_chunk_unknown;3005# endif /* SAVE_UNKNOWN_CHUNKS */30063007return png_chunk_skip;3008}30093010# ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED3011else3012{3013/* Else this is a known chunk that is being treated as unknown. If3014* there is a user callback the whole shebang is required:3015*/3016# ifdef PNG_READ_USER_CHUNKS_SUPPORTED3017if (png_ptr->read_user_chunk_fn != NULL)3018return png_chunk_unknown;3019# endif /* READ_USER_CHUNKS */30203021/* No user callback, there is a possibility that we can skip this3022* chunk:3023*/3024# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED3025if ((png_ptr->save_unknown >> index) & 1U)3026return png_chunk_unknown;3027# endif /* SAVE_UNKNOWN_CHUNKS */30283029/* If this is a critical chunk and IDAT is not being skipped then3030* this is an error. The only possibility here is PLTE on an3031* image which is palette mapped. If the app ignores this error3032* then there will be a more definate one in png_handle_unknown.3033*/3034if (chunk_name == png_PLTE &&3035png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)3036png_app_error(png_ptr, "skipping PLTE on palette image");30373038return png_chunk_skip;3039}3040# endif /* HANDLE_AS_UNKNOWN */3041}30423043else /* unknown chunk */3044{3045/* The code above implicitly validates the chunk name, however if a chunk3046* name/type is not recognized it is necessary to validate it to ensure3047* that the PNG stream isn't hopelessly damaged:3048*/3049png_check_chunk_name(png_ptr, chunk_name);30503051# ifdef PNG_READ_USER_CHUNKS_SUPPORTED3052if (png_ptr->read_user_chunk_fn != NULL)3053return png_chunk_unknown;3054# endif /* READ_USER_CHUNKS */30553056# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED3057/* There may be per-chunk handling, otherwise the default is used, this3058* is the one place where the list needs to be searched:3059*/3060{3061int keep = png_chunk_unknown_handling(png_ptr, chunk_name);30623063if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)3064keep = png_ptr->unknown_default;30653066if (keep == PNG_HANDLE_CHUNK_ALWAYS ||3067(keep == PNG_HANDLE_CHUNK_IF_SAFE &&3068PNG_CHUNK_ANCILLARY(chunk_name)))3069return png_chunk_unknown;3070}3071# endif /* SAVE_UNKNOWN_CHUNKS */30723073/* The chunk will be skipped so it must not be a critical chunk, unless3074* IDATs are being skipped too.3075*/3076if (PNG_CHUNK_CRITICAL(chunk_name)3077# ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED3078&& !png_IDATs_skipped(png_ptr)3079# endif /* HANDLE_AS_UNKNOWN */3080)3081png_chunk_error(png_ptr, "unhandled critical chunk");30823083return png_chunk_skip;3084}3085}30863087void /* PRIVATE */3088png_handle_chunk(png_structrp png_ptr, png_inforp info_ptr)3089/* The chunk to handle is in png_struct::chunk_name,chunk_length.3090*3091* NOTE: at present it is only valid to call this after png_find_chunk_op3092* has returned png_chunk_process_all and all the data is available for3093* png_handle_chunk (via the libpng read callback.)3094*/3095{3096png_uint_32 chunk_name = png_ptr->chunk_name;3097unsigned int index = png_chunk_index(chunk_name);30983099/* So this must be true: */3100affirm(png_known_chunks[index].name == chunk_name &&3101png_known_chunks[index].handle != NULL);31023103png_known_chunks[index].handle(png_ptr, info_ptr);3104}31053106static void3107copy_row(png_const_structrp png_ptr, png_bytep dp, png_const_bytep sp,3108png_uint_32 x/*in INPUT*/, png_uint_32 width/*of INPUT*/, int clear)3109/* Copy the row in row_buffer; this is the 'simple' case of combine_row3110* where no adjustment to the pixel spacing is required.3111*/3112{3113png_copy_row(png_ptr, dp, sp, x, width,3114# ifdef PNG_TRANSFORM_MECH_SUPPORTED3115png_ptr->row_bit_depth * PNG_FORMAT_CHANNELS(png_ptr->row_format),3116# else3117PNG_PIXEL_DEPTH(*png_ptr),3118# endif3119clear/*clear partial byte at end of row*/, 1/*sp -> dp[x]*/);3120}31213122#ifdef PNG_READ_INTERLACING_SUPPORTED3123static void3124combine_row(png_const_structrp png_ptr, png_bytep dp, png_const_bytep sp,3125png_uint_32 x/*in INPUT*/, png_uint_32 width/*of INPUT*/, int display)3126/* 1.7.0: API CHANGE: prior to 1.7.0 read de-interlace was done in two steps,3127* the first would expand a narrow pass by replicating pixels according to3128* the inter-pixel spacing of the pixels from the pass in the image. It did3129* not take account of any offset from the start of the image row of the3130* first pixel. The second step happened in png_combine_row where the result3131* was merged into the output rows.3132*3133* In 1.7.0 this is no longer done. Instead all the work happens here. This3134* is only an API change for the progressive reader if the app didn't call3135* png_combine_row, but rather expected an expanded row. It's not obvious3136* why any user of the progressive reader would want this, particularly given3137* the weird non-offseting of the start in the original3138* 'png_do_read_interlace'; the behavior was completely undocumented.3139*3140* In 1.7.0 combine_row does all the work. It expects a raw uncompressed,3141* de-filtered, transformed row and it either copies it if:3142*3143* 1) It is not interlaced.3144* 2) libpng isn't handling the de-interlace.3145* 3) This is pass 7 (i.e. '6' using the libpng 0-based numbering).3146*3147* The input data comes from png_struct and sp:3148*3149* sp[width(pixels)]; the row data from input[x(pixels)...]3150* png_struct::pass; the pass3151* png_struct::row_number; the row number in the *image*3152* png_struct::row_bit_depth,3153* png_struct::row_format; the pixel format, if TRANSFORM_MECH, else:3154* png_struct::bit_depth,3155* png_struct::color_type; the pixel format otherwise3156*3157* The destination pointer (but not size) and how to handle intermediate3158* passes are arguments to the API. The destination is the pointer to the3159* entire row buffer, not just the part from output[x] on. 'display' is3160* interpreted as:3161*3162* 0: only overwrite destination pixels that will correspond to the source3163* pixel in the final image. 'sparkle' mode.3164* 1: overwrite the corresponding destination pixel and all following3165* pixels (horizontally and, eventually, vertically) that will come3166* from *later* passes. 'block' mode.3167*/3168{3169const unsigned int pass = png_ptr->pass;31703171png_debug(1, "in png_combine_row");31723173/* Factor out the copy case first, the 'display' argument is irrelevant in3174* these cases:3175*/3176if (!png_ptr->do_interlace || png_ptr->pass == 6)3177{3178copy_row(png_ptr, dp, sp, x, width, 0/*do not clear*/);3179return;3180}31813182else /* not a simple copy */3183{3184const unsigned int pixel_depth =3185# ifdef PNG_TRANSFORM_MECH_SUPPORTED3186png_ptr->row_bit_depth * PNG_IMAGE_PIXEL_CHANNELS(png_ptr->row_format);3187# else3188PNG_PIXEL_DEPTH(*png_ptr);3189# endif3190png_uint_32 row_width = png_ptr->width; /* output width */3191/* The first source pixel is written to PNG_COL_FROM_PASS of the3192* destination:3193*/3194png_uint_32 dx = PNG_COL_FROM_PASS_COL(x, pass);3195/* The corresponding offset within the 8x8 block: */3196const unsigned int dstart = dx & 0x7U;3197/* Find the first pixel written in any 8x8 block IN THIS PASS: */3198const unsigned int pass_start = PNG_PASS_START_COL(pass);3199/* Subsequent pixels are written PNG_PASS_COL_OFFSET further on: */3200const unsigned int doffset = PNG_PASS_COL_OFFSET(pass);3201/* In 'block' mode when PNG_PASS_START_COL(pass) is 0 (PNG passes 1,3,5,7)3202* the same pixel is replicated doffset times, when PNG_PASS_START_COL is3203* non-zero (PNG passes 2,4,6) it is replicated PNG_PASS_START_COL times.3204* For 'sparkle' mode only one copy of the pixel is written:3205*/3206unsigned int drep = display ? (pass_start ? pass_start : doffset) : 1;32073208/* Standard check for byte alignment */3209debug(((x * pixel_depth/*OVERFLOW OK*/) & 0x7U) == 0U);32103211/* The caller should have excluded the narrow cases: */3212affirm(row_width > dx);3213row_width -= dx;3214/* Advance dp to the start of the 8x8 block containing the first pixel to3215* write, adjust dx to be an offset within the block:3216*/3217dp += png_calc_rowbytes(png_ptr, pixel_depth, dx & ~0x7U);3218dx &= 0x7U;32193220/* So each source pixel sp[i] is written to:3221*3222* dp[dstart + i*doffset]..dp[dstart + i*doffset + (drep-1)]3223*3224* Until we get to row_width. This is easy for pixels that are 8 or more3225* bits deep; whole bytes are read and written, slightly more difficult3226* when pixel_depth * drep is at least 8 bits, because then dstart *3227* pixel_depth will always be a whole byte and most complex when source3228* and destination require sub-byte addressing.3229*3230* Cherry pick the easy cases:3231*/3232if (pixel_depth > 8U)3233{3234/* Convert to bytes: */3235const unsigned int pixel_bytes = pixel_depth >> 3;32363237dp += dstart * pixel_bytes;32383239for (;;)3240{3241unsigned int c;32423243if (drep > row_width)3244drep = row_width;32453246for (c=0U; c<drep; ++c)3247memcpy(dp, sp, pixel_bytes), dp += pixel_bytes;32483249if (doffset >= row_width)3250break;32513252row_width -= doffset;3253dp += (doffset-drep) * pixel_bytes;3254sp += pixel_bytes;3255}3256}32573258else if (pixel_depth == 8U)3259{3260/* Optimize the common 1-byte per pixel case (typical case for palette3261* mapped images):3262*/3263dp += dstart;32643265for (;;)3266{3267if (drep > row_width)3268drep = row_width;32693270memset(dp, *sp++, drep);32713272if (doffset >= row_width)3273break;32743275row_width -= doffset;3276dp += doffset;3277}3278}32793280else /* pixel_depth < 8 */3281{3282/* Pixels are 1, 2 or 4 bits in size. */3283unsigned int spixel = *sp++;3284unsigned int dbrep = pixel_depth * drep;3285unsigned int spos = 0U;3286# ifdef PNG_READ_PACKSWAP_SUPPORTED3287const int lsb =3288(png_ptr->row_format & PNG_FORMAT_FLAG_SWAPPED) != 0;3289# endif /* READ_PACKSWAP */32903291if (dbrep >= 8U)3292{3293/* brep must be greater than 1, the destination does not require3294* sub-byte addressing except, maybe, at the end.3295*3296* db is the count of bytes required to replicate the source pixel3297* drep times.3298*/3299debug((dbrep & 7U) == 0U);3300dbrep >>= 3;3301debug((dstart * pixel_depth & 7U) == 0U);3302dp += (dstart * pixel_depth) >> 3;33033304for (;;)3305{3306/* Fill a byte with copies of the next pixel: */3307unsigned int spixel_rep = spixel;33083309# ifdef PNG_READ_PACKSWAP_SUPPORTED3310if (lsb)3311spixel_rep >>= spos;3312else3313# endif /* READ_PACKSWAP */3314spixel_rep >>= (8U-pixel_depth)-spos;33153316switch (pixel_depth)3317{3318case 1U: spixel_rep &= 1U; spixel_rep |= spixel_rep << 1;3319/*FALL THROUGH*/3320case 2U: spixel_rep &= 3U; spixel_rep |= spixel_rep << 2;3321/*FALL THROUGH*/3322case 4U: spixel_rep &= 15U; spixel_rep |= spixel_rep << 4;3323/*FALL THROUGH*/3324default: break;3325}33263327/* This may leave some pixels unwritten when there is a partial3328* byte write required at the end:3329*/3330if (drep > row_width)3331drep = row_width, dbrep = (pixel_depth * drep) >> 3;33323333memset(dp, spixel_rep, dbrep);33343335if (doffset >= row_width)3336{3337/* End condition; were all 'drep' pixels written at the end?3338*/3339drep = (pixel_depth * drep - (dbrep << 3));33403341if (drep)3342{3343unsigned int mask;33443345debug(drep < 8U);3346dp += dbrep;33473348/* Set 'mask' to have 0's where *dp must be overwritten3349* with spixel_rep:3350*/3351# ifdef PNG_READ_PACKSWAP_SUPPORTED3352if (lsb)3353mask = 0xff << drep;3354else3355# endif /* READ_PACKSWAP */3356mask = 0xff >> drep;33573358*dp = PNG_BYTE((*dp & mask) | (spixel_rep & ~mask));3359}33603361break;3362}33633364row_width -= doffset;3365dp += (doffset * pixel_depth) >> 3;3366spos += pixel_depth;3367if (spos == 8U)3368spixel = *sp++, spos = 0U;3369} /* for (;;) */3370} /* pixel_depth * drep >= 8 */33713372else /* pixel_depth * drep < 8 */3373{3374/* brep may be 1, pixel_depth may be 1, 2 or 4, dbrep is the number3375* of bits to set.3376*/3377unsigned int bstart = dstart * pixel_depth; /* in bits */3378unsigned int dpixel;33793380dp += bstart >> 3;3381bstart &= 7U;3382dpixel = *dp;33833384/* dpixel: current *dp, being modified3385* bstart: bit offset within dpixel3386* drep: pixel size to write (used as a check against row_width)3387* doffset: pixel step to next written destination3388*3389* spixel: current *sp, being read, and:3390* spixel_rep: current pixel, replicated to fill a byte3391* spos: bit offset within spixel3392*3393* Set dbrep to a mask for the bits to set:3394*/3395dbrep = (1U<<dbrep)-1U;3396for (;;)3397{3398/* Fill a byte with copies of the next pixel: */3399unsigned int spixel_rep = spixel;34003401# ifdef PNG_READ_PACKSWAP_SUPPORTED3402if (lsb)3403spixel_rep >>= spos;3404else3405# endif /* READ_PACKSWAP */3406spixel_rep >>= (8U-pixel_depth)-spos;34073408switch (pixel_depth)3409{3410case 1U: spixel_rep &= 1U; spixel_rep |= spixel_rep << 1;3411/*FALL THROUGH*/3412case 2U: spixel_rep &= 3U; spixel_rep |= spixel_rep << 2;3413/*FALL THROUGH*/3414case 4U: spixel_rep &= 15U; spixel_rep |= spixel_rep << 4;3415/*FALL THROUGH*/3416default: break;3417}34183419/* This may leave some pixels unwritten when there is a partial3420* byte write required at the end:3421*/3422if (drep > row_width)3423drep = row_width, dbrep = (1U<<(pixel_depth*drep))-1U;34243425{3426unsigned int mask;34273428/* Mask dbrep bits at bstart: */3429# ifdef PNG_READ_PACKSWAP_SUPPORTED3430if (lsb)3431mask = bstart;3432else3433# endif /* READ_PACKSWAP */3434mask = (8U-pixel_depth)-bstart;3435mask = dbrep << mask;34363437dpixel &= ~mask;3438dpixel |= spixel_rep & mask;3439}34403441if (doffset >= row_width)3442{3443*dp = PNG_BYTE(dpixel);3444break;3445}34463447row_width -= doffset;3448bstart += doffset * pixel_depth;34493450if (bstart >= 8U)3451{3452*dp = PNG_BYTE(dpixel);3453dp += bstart >> 3;3454bstart &= 7U;3455dpixel = *dp;3456}34573458spos += pixel_depth;3459if (spos == 8U)3460spixel = *sp++, spos = 0U;3461} /* for (;;) */3462} /* pixel_depth * drep < 8 */3463} /* pixel_depth < 8 */3464} /* not a simple copy */3465}34663467#ifdef PNG_PROGRESSIVE_READ_SUPPORTED3468void PNGAPI3469png_progressive_combine_row(png_const_structrp png_ptr, png_bytep old_row,3470png_const_bytep new_row)3471{3472/* new_row is a flag here - if it is NULL then the app callback was called3473* from an empty row (see the calls to png_struct::row_fn above), otherwise3474* it must be png_struct::transformed_row3475*/3476if (png_ptr != NULL && new_row != NULL)3477{3478if (new_row != png_ptr->row_buffer3479# ifdef PNG_TRANSFORM_MECH_SUPPORTED3480&& new_row != png_ptr->transformed_row3481# endif /* TRANSFORM_MECH */3482)3483png_app_error(png_ptr, "invalid call to png_progressive_combine_row");3484else3485{3486png_uint_32 width = png_ptr->width;34873488if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)3489{3490const unsigned int pass = png_ptr->pass;3491width = PNG_PASS_COLS(width, pass);3492}34933494combine_row(png_ptr, old_row, new_row, 0U, width, 1/*blocky display*/);3495}3496}3497}3498#endif /* PROGRESSIVE_READ */3499#else /* !READ_INTERLACING */3500/* No read deinterlace support, so 'combine' always reduces to 'copy', there3501* is no 'display' argument:3502*/3503# define combine_row(pp, dp, sp, x, w, display)\3504copy_row(pp, dp, sp, x, w, 0/*!clear*/)3505#endif /* !READ_INTERLACING */35063507static void3508png_read_filter_row_sub(png_alloc_size_t row_bytes, unsigned int bpp,3509png_bytep row, png_const_bytep prev_row, png_const_bytep prev_pixels)3510{3511while (row_bytes >= bpp)3512{3513unsigned int i;35143515for (i=0; i<bpp; ++i)3516row[i] = PNG_BYTE(row[i] + prev_pixels[i]);35173518prev_pixels = row;3519row += bpp;3520row_bytes -= bpp;3521}35223523PNG_UNUSED(prev_row)3524}35253526static void3527png_read_filter_row_up(png_alloc_size_t row_bytes, unsigned int bpp,3528png_bytep row, png_const_bytep prev_row, png_const_bytep prev_pixels)3529{3530while (row_bytes > 0)3531{3532*row = PNG_BYTE(*row + *prev_row);3533++row;3534++prev_row;3535--row_bytes;3536}35373538PNG_UNUSED(bpp)3539PNG_UNUSED(prev_pixels)3540}35413542static void3543png_read_filter_row_avg(png_alloc_size_t row_bytes, unsigned int bpp,3544png_bytep row, png_const_bytep prev_row, png_const_bytep prev_pixels)3545{3546while (row_bytes >= bpp)3547{3548unsigned int i;35493550for (i=0; i<bpp; ++i)3551row[i] = PNG_BYTE(row[i] + (prev_pixels[i] + prev_row[i])/2U);35523553prev_pixels = row;3554row += bpp;3555prev_row += bpp;3556row_bytes -= bpp;3557}3558}35593560static void3561png_read_filter_row_paeth_1byte_pixel(png_alloc_size_t row_bytes,3562unsigned int bpp, png_bytep row, png_const_bytep prev_row,3563png_const_bytep prev_pixels)3564{3565png_const_bytep rp_end = row + row_bytes;3566png_byte a, c;35673568/* prev_pixels stores pixel a then c */3569a = prev_pixels[0];3570c = prev_pixels[1];35713572while (row < rp_end)3573{3574png_byte b;3575int pa, pb, pc, p;35763577b = *prev_row++;35783579p = b - c;3580pc = a - c;35813582# ifdef PNG_USE_ABS3583pa = abs(p);3584pb = abs(pc);3585pc = abs(p + pc);3586# else3587pa = p < 0 ? -p : p;3588pb = pc < 0 ? -pc : pc;3589pc = (p + pc) < 0 ? -(p + pc) : p + pc;3590# endif35913592/* Find the best predictor, the least of pa, pb, pc favoring the earlier3593* ones in the case of a tie.3594*/3595if (pb < pa)3596{3597pa = pb; a = b;3598}3599if (pc < pa) a = c;36003601/* Calculate the current pixel in a, and move the previous row pixel to c3602* for the next time round the loop3603*/3604c = b;3605a = 0xFFU & (a + *row);3606*row++ = a;3607}36083609PNG_UNUSED(bpp)3610}36113612static void3613png_read_filter_row_paeth_multibyte_pixel(png_alloc_size_t row_bytes,3614unsigned int bpp, png_bytep row, png_const_bytep prev_row,3615png_const_bytep prev_pixels)3616{3617png_bytep rp_end = row + bpp;36183619/* 'a' and 'c' for the first pixel come from prev_pixels: */3620while (row < rp_end)3621{3622png_byte a, b, c;3623int pa, pb, pc, p;36243625/* prev_pixels stores bpp bytes for 'a', the bpp for 'c': */3626c = *(prev_pixels+bpp);3627a = *prev_pixels++;3628b = *prev_row++;36293630p = b - c;3631pc = a - c;36323633# ifdef PNG_USE_ABS3634pa = abs(p);3635pb = abs(pc);3636pc = abs(p + pc);3637# else3638pa = p < 0 ? -p : p;3639pb = pc < 0 ? -pc : pc;3640pc = (p + pc) < 0 ? -(p + pc) : p + pc;3641# endif36423643if (pb < pa)3644{3645pa = pb; a = b;3646}3647if (pc < pa) a = c;36483649a = 0xFFU & (a + *row);3650*row++ = a;3651}36523653/* Remainder */3654rp_end += row_bytes - bpp;36553656while (row < rp_end)3657{3658png_byte a, b, c;3659int pa, pb, pc, p;36603661c = *(prev_row-bpp);3662a = *(row-bpp);3663b = *prev_row++;36643665p = b - c;3666pc = a - c;36673668# ifdef PNG_USE_ABS3669pa = abs(p);3670pb = abs(pc);3671pc = abs(p + pc);3672# else3673pa = p < 0 ? -p : p;3674pb = pc < 0 ? -pc : pc;3675pc = (p + pc) < 0 ? -(p + pc) : p + pc;3676# endif36773678if (pb < pa)3679{3680pa = pb; a = b;3681}3682if (pc < pa) a = c;36833684a = 0xFFU & (a + *row);3685*row++ = a;3686}3687}36883689static void3690png_init_filter_functions(png_structrp pp, unsigned int bpp)3691/* This function is called once for every PNG image (except for PNG images3692* that only use PNG_FILTER_VALUE_NONE for all rows) to set the3693* implementations required to reverse the filtering of PNG rows. Reversing3694* the filter is the first transformation performed on the row data. It is3695* performed in place, therefore an implementation can be selected based on3696* the image pixel format. If the implementation depends on image width then3697* take care to ensure that it works correctly if the image is interlaced -3698* interlacing causes the actual row width to vary.3699*/3700{3701pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;3702pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;3703pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;3704if (bpp == 1)3705pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =3706png_read_filter_row_paeth_1byte_pixel;3707else3708pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =3709png_read_filter_row_paeth_multibyte_pixel;37103711#ifdef PNG_FILTER_OPTIMIZATIONS3712/* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to3713* call to install hardware optimizations for the above functions; simply3714* replace whatever elements of the pp->read_filter[] array with a hardware3715* specific (or, for that matter, generic) optimization.3716*3717* To see an example of this examine what configure.ac does when3718* --enable-arm-neon is specified on the command line.3719*/3720PNG_FILTER_OPTIMIZATIONS(pp, bpp);3721#endif3722}37233724/* This is an IDAT specific wrapper for png_zlib_inflate; the input is already3725* in png_ptr->zstream.{next,avail}_in however the output uses the full3726* capabilities of png_zlib_inflate, returning a byte count of bytes read.3727* This is just a convenience for IDAT processing.3728*3729* NOTE: this function works just fine after the zstream has ended, it just3730* fills the buffer with zeros (outputing an error message once.)3731*/3732static png_alloc_size_t3733png_inflate_IDAT(png_structrp png_ptr, int finish,3734/* OUTPUT: */ png_bytep output, png_alloc_size_t output_size)3735{3736/* Expect Z_OK if !finsh and Z_STREAM_END if finish; if Z_STREAM_END is3737* delivered when finish is not set the IDAT stream is truncated, if Z_OK is3738* delivered when finish is set this is harmless and indicates that the3739* stream end code has not been read.3740*3741* finish should be set as follows:3742*3743* 0: not reading the last row, stream not expected to end3744* 1: reading the last row, stream expected to end3745* 2: looking for stream end after the last row has been read, expect no3746* more output and stream end.3747*/3748png_alloc_size_t original_size = output_size;3749int ret = Z_STREAM_END; /* In case it ended ok before. */37503751if (!png_ptr->zstream_ended)3752{3753png_const_bytep next_in = png_ptr->zstream.next_in;3754png_uint_32 avail_in = png_ptr->zstream.avail_in;37553756ret = png_zlib_inflate(png_ptr, png_IDAT, finish,3757&next_in, &avail_in, &output, &output_size/*remaining*/);37583759debug(next_in == png_ptr->zstream.next_in);3760debug(avail_in == png_ptr->zstream.avail_in);3761debug(output == png_ptr->zstream.next_out);3762/* But zstream.avail_out may be truncated to uInt */37633764switch (ret)3765{3766case Z_STREAM_END:3767/* The caller must set finish on the last row of the image (not3768* the last row of the pass!)3769*/3770debug(png_ptr->zstream_ended);37713772if (!finish) /* early end */3773break;37743775if (output_size > 0) /* incomplete read */3776{3777if (finish == 2) /* looking for end; it has been found */3778return original_size - output_size;37793780/* else those bytes are really needed: */3781break;3782}37833784/* else: FALL THROUGH: success */37853786case Z_BUF_ERROR:3787/* this is the success case: output or input is empty: */3788original_size -= output_size; /* bytes written */37893790if (output_size > 0)3791{3792/* Some output still needed; if the next chunk is known3793* to not be an IDAT then this is the truncation case.3794*/3795affirm(avail_in == 0);37963797if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)3798{3799/* Zlib doesn't know we are out of data, so this must be3800* done here:3801*/3802png_ptr->zstream_ended = 1;3803break;3804}3805}38063807return original_size; /* bytes written */38083809default:3810/* error */3811break;3812}38133814/* The 'ended' flag should always be set if we get here, the success3815* cases where the LZ stream hasn't reached an end or an error leave3816* the function at the return above.3817*/3818debug(png_ptr->zstream_ended);3819}38203821/* This is the error return case; there was missing data, or an error.3822* Either continue with a warning (once; hence the zstream_error flag)3823* or png_error.3824*/3825if (!png_ptr->zstream_error) /* first time */3826{3827#ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED3828switch (png_ptr->IDAT_error_action)3829{3830case PNG_ERROR:3831if(!strncmp(png_ptr->zstream.msg,"incorrect data check",20))3832{3833if (png_ptr->current_crc != crc_quiet_use)3834png_chunk_warning(png_ptr, "ADLER32 checksum mismatch");3835}38363837else3838{3839png_chunk_error(png_ptr, png_ptr->zstream.msg);3840}3841break;38423843case PNG_WARN:3844png_chunk_warning(png_ptr, png_ptr->zstream.msg);3845break;38463847default: /* ignore */3848/* Keep going */3849break;3850}3851#else3852{3853if(!strncmp(png_ptr->zstream.msg,"incorrect data check",20))3854png_chunk_warning(png_ptr, "ADLER32 checksum mismatch");3855else3856png_chunk_error(png_ptr, png_ptr->zstream.msg);3857}3858#endif /* !BENIGN_ERRORS */38593860/* And prevent the report about too many IDATs on streams with internal3861* LZ errors:3862*/3863png_ptr->zstream_error = 1;3864}38653866/* This is the error recovery case; fill the buffer with zeros. This is3867* safe because it makes the filter byte 'NONE' and the row fairly innocent.3868*/3869memset(output, 0, output_size);3870return original_size;3871}38723873/* SHARED IDAT HANDLING.3874*3875* This is the 1.7+ common read code; shared by both the progressive and3876* sequential readers.3877*/3878/* Initialize the row buffers, etc. */3879void /* PRIVATE */3880png_read_start_IDAT(png_structrp png_ptr)3881{3882# ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED3883/* This won't work at all if the app turned on unknown handling for IDAT3884* chunks; the first IDAT has already been consumed!3885*/3886if (png_ptr->known_unknown & 1U)3887png_error(png_ptr, "Attempt to read image with unknown IDAT");3888# endif /* HANDLE_AS_UNKNOWN */38893890/* This is a missing read of the header information; we still haven't3891* countered the first IDAT chunk. This can only happen in the sequential3892* reader if the app didn't call png_read_info.3893*/3894if (png_ptr->chunk_name != png_IDAT)3895png_error(png_ptr, "Missing call to png_read_info");38963897/* Two things need to happen: first work out the effect of any3898* transformations (if supported) on the row size, second, allocate3899* row_buffer and claim the zstream.3900*/3901png_init_row_info(png_ptr);39023903/* Now allocate the row buffer and, if that succeeds, claim the zstream.3904*/3905png_ptr->row_buffer = png_voidcast(png_bytep, png_malloc(png_ptr,3906png_calc_rowbytes(png_ptr, PNG_PIXEL_DEPTH(*png_ptr), png_ptr->width)));39073908if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)3909png_error(png_ptr, png_ptr->zstream.msg);3910}39113912/* The process function gets called when there is some IDAT data to process3913* and it just does the right thing with it. The zstream must have been claimed3914* (owner png_IDAT) and the input data is in zstream.{next,avail}_in. The3915* output next_{in,out} must not be changed by the caller; it is used3916* internally.3917*3918* Result codes are as follows:3919*3920* png_row_incomplete: Insufficient IDAT data (from zstream) was present to3921* process the next row. zstream.avail_in will be 0.3922* png_row_process: A new row is available in the input buffer, it should be3923* handled before the next call (if any) to this function.3924* png_row_repeat: For interlaced images (only) this row is not in the pass,3925* however the existing buffer may be displayed in lieu; if doing the3926* 'blocky' (not 'sparkle') display the row should be displayed,3927* otherwise treat as:3928* png_row_skip: For interlaced images (only) the interlace pass has no data3929* appropriate to this row, it should be skipped.3930*3931* In both of the two cases zstream.avail_in may be non-0, indicating that some3932* IDAT data at zstream.next_in remains to be consumed. This data must be3933* preserved and preset at the next call to the function.3934*3935* The function may also call png_error if an unrecoverable error occurs.3936*3937* The caller passes in a callback function and parameter to be called when row3938* data is available. The callback is called repeatedly for each row to handle3939* all the transformed row data.3940*/3941png_row_op /*PRIVATE*/3942png_read_process_IDAT(png_structrp png_ptr, png_bytep transformed_row,3943png_bytep display_row, int save_row)3944{3945/* Common sub-expressions. These are all constant across the whole PNG, but3946* are recalculated here each time because this is fast and it only happens3947* once per row + once per block of input data.3948*/3949const unsigned int max_pixels = png_max_pixel_block(png_ptr);3950const unsigned int pixel_depth = png_ptr->row_input_pixel_depth;3951/* The number of input bytes read each time (cannot overflow because it is3952* limited by PNG_ROW_BUFFER_SIZE):3953*/3954const unsigned int input_byte_count = (max_pixels * pixel_depth) / 8U;3955const unsigned int bpp = (pixel_depth+0x7U)>>3;3956const png_uint_32 width = png_ptr->width;3957const unsigned int interlaced = png_ptr->interlaced != PNG_INTERLACE_NONE;39583959png_uint_32 row_number = png_ptr->row_number;3960unsigned int pass = png_ptr->pass;3961enum anonymous {3962start_of_row = 0U, /* at the start of the row; read a filter byte */3963need_row_bytes = 2U, /* reading the row */3964processing_row = 3U /* control returned to caller to process the row */3965} state = png_upcast(enum anonymous, png_ptr->row_state);39663967/* The caller is responsible for calling png_read_start_IDAT: */3968affirm(png_ptr->zowner == png_IDAT);39693970/* Basic sanity checks: */3971affirm(pixel_depth > 0U && pixel_depth <= 64U &&3972input_byte_count <= PNG_ROW_BUFFER_SIZE &&3973pixel_depth <= 8U*PNG_MAX_PIXEL_BYTES);39743975for (;;) switch (state)3976{3977png_alloc_size_t row_bytes_processed;3978png_alloc_size_t bytes_read; /* bytes in pixel_buffer */3979png_uint_32 pass_width;3980png_byte row_filter;3981union3982{3983PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;3984png_byte buffer[16U];3985} previous_pixels;3986union3987{3988PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;3989png_byte buffer[PNG_ROW_BUFFER_SIZE];3990} pixel_buffer;39913992case need_row_bytes:3993/* The above variables need to be restored: */3994row_bytes_processed = png_ptr->row_bytes_read;3995bytes_read = row_bytes_processed % input_byte_count;3996row_bytes_processed -= bytes_read;39973998pass_width = width;3999if (interlaced)4000pass_width = PNG_PASS_COLS(pass_width, pass);40014002memcpy(pixel_buffer.buffer, png_ptr->scratch, bytes_read);4003memcpy(previous_pixels.buffer, png_ptr->scratch+bytes_read, 2*bpp);4004row_filter = png_ptr->scratch[bytes_read+2*bpp];40054006goto pixel_loop;40074008case processing_row:4009/* When there was a previous row (not at the start of the image) the4010* row number needs to be updated and, possibly, the pass number.4011*/4012if (++row_number == png_ptr->height)4013{4014affirm(interlaced && pass < 6); /* else too many calls */40154016/* Start a new pass: there never is a pending filter byte so it4017* is always necessary to read the filter byte of the next row.4018*/4019png_ptr->pass = ++pass & 0x7;4020row_number = 0U;4021} /* end of pass */40224023png_ptr->row_number = row_number;40244025/* This is a new row, but it may not be in the pass data so it4026* may be possible to simply return control to the caller to4027* skip it or use the previous row as appropriate.4028*/4029if (interlaced)4030{4031debug(pass <= 6);40324033/* This macro cannot overflow because the PNG width (and height)4034* have already been checked to ensure that they are less than4035* 2^31 (i.e. they are 31-bit values, not 32-bit values.)4036*/4037pass_width = PNG_PASS_COLS(width, pass);40384039/* On average most rows are skipped, so do this first: */4040if (pass_width == 0 ||4041!PNG_ROW_IN_INTERLACE_PASS(row_number, pass))4042{4043/* Using the PNG specification numbering (pass+1), passes 1,4044* 2, 4, 6 contribute to all the rows in 'block' interlaced4045* filling mode. Pass 3 contributes to four rows (5,6,7,8),4046* pass 5 to two rows (3,4 then 7,8) and pass 7 only to one4047* (the one on which it is processed). have_row must be set4048* appropriately; it is set when a row is processed (end of4049* this function) and remains set while the 'block' mode of4050* interlace handling should reuse the previous row for this4051* row.4052*4053* Each pass row can be used in a fixed number of rows, shown4054* in 'rows' below, the '*' indicates that the row is actually4055* in the pass, the '^' that the previous '*' row is used in4056* block display update and the '@' that the pass doesn't4057* contribte at all to that row in block display mode:4058*4059* PASS: 0 1 2 3 4 5 64060* rows: 8 8 4 4 2 2 14061* 0: * * @ * @ * @4062* 1: ^ ^ @ ^ @ ^ *4063* 2: ^ ^ @ ^ * * @4064* 3: ^ ^ @ ^ ^ ^ *4065* 4: ^ ^ * * @ * @4066* 5: ^ ^ ^ ^ @ ^ *4067* 6: ^ ^ ^ ^ * * @4068* 7: ^ ^ ^ ^ ^ ^ *4069*4070* The '@' signs are the interesting thing, since we know that4071* this row isn't present in the pass data. Rewriting the4072* above table with '1' for '@', little endian (i.e. row 0 at4073* the LSB end):4074*4075* row: 765432104076* Pass 0: 00000000 0x00 [bit 3, 0x8 of row unset (always)]4077* Pass 1: 00000000 0x004078* Pass 2: 00001111 0x0F [bit 2, 0x4 of row unset]4079* Pass 3: 00000000 0x004080* Pass 4: 00110011 0x33 [bit 1, 0x2 of row unset]4081* Pass 5: 00000000 0x004082* Pass 6: 01010101 0x55 [bit 0, 0x1 of row unset]4083*4084* PNG_PASS_BLOCK_SKIP(pass, row) can be written two ways;4085*4086* As a shift and a mask:4087* (0x55330F00 >> ((pass >> 1) + (row & 7))) & ~pass & 14088*4089* And, somewhat simpler, as a bit check on the low bits of4090* row:4091*4092* ~((row) >> (3-(pass >> 1))) & ~pass & 14093*/4094# define PNG_PASS_BLOCK_SKIP(pass, row)\4095(~((row) >> (3U-((pass) >> 1))) & ~(pass) & 0x1U)40964097/* Hence: */4098debug(png_ptr->row_state == processing_row);4099return pass_width == 0 || PNG_PASS_BLOCK_SKIP(pass,4100row_number) ? png_row_skip : png_row_repeat;4101} /* skipped row */41024103/* processed; fall through to start_of_row */4104} /* interlaced */41054106/* FALL THROUGH */4107case start_of_row:4108{4109/* Read the filter byte for the next row, previous_pixels is just4110* used as a temporary buffer; it is reset below.4111*/4112png_alloc_size_t cb = png_inflate_IDAT(png_ptr, 0/*finish*/,4113previous_pixels.buffer, 1U);41144115/* This can be temporary; it verifies the invariants on how4116* png_inflate_IDAT updates the {next,avail}_out fields:4117*/4118#ifndef __COVERITY__ /* Suppress bogus Coverity complaint */4119debug(png_ptr->zstream.avail_out == 1-cb &&4120png_ptr->zstream.next_out == cb + previous_pixels.buffer);4121#endif41224123/* next_out points to previous_pixels, for security do this: */4124png_ptr->zstream.next_out = NULL;4125png_ptr->zstream.avail_out = 0U;41264127/* One byte, so we either got it or have to get more input data: */4128if (cb != 1U)4129{4130affirm(cb == 0U && png_ptr->zstream.avail_in == 0U);4131png_ptr->row_state = start_of_row;4132return png_row_incomplete;4133}4134}41354136/* Check the filter byte. */4137row_filter = previous_pixels.buffer[0];4138if (row_filter >= PNG_FILTER_VALUE_LAST)4139png_chunk_error(png_ptr, "invalid PNG filter");41404141/* These are needed for the filter check below: */4142pass_width = width;4143if (interlaced)4144pass_width = PNG_PASS_COLS(pass_width, pass);41454146/* The filter is followed by the row data, but first check the4147* filter byte; the spec requires that we invent an empty row4148* if the first row of a pass requires it.4149*4150* Note that row_number is the image row.4151*/4152if (row_number == PNG_PASS_START_ROW(pass)) switch (row_filter)4153{4154case PNG_FILTER_VALUE_UP:4155/* x-0 == x, so do this optimization: */4156row_filter = PNG_FILTER_VALUE_NONE;4157break;41584159case PNG_FILTER_VALUE_PAETH:4160/* The Paeth predictor is always the preceding (leftwards)4161* value, so this is the same as sub:4162*/4163row_filter = PNG_FILTER_VALUE_SUB;4164break;41654166case PNG_FILTER_VALUE_AVG:4167/* It would be possible to 'invent' a new filter that did4168* AVG using only the previous byte; it's 'SUB' of half the4169* preceding value, but this seems pointless. Zero out the4170* row buffer to make AVG work.4171*/4172memset(png_ptr->row_buffer, 0U,4173PNG_ROWBYTES(pixel_depth, pass_width));4174break;41754176default:4177break;4178} /* switch row_filter */41794180/* Always zero the 'previous pixel' out at the start of a row; this4181* allows the filter code to ignore the row start.4182*/4183memset(previous_pixels.buffer, 0U, sizeof previous_pixels.buffer);41844185row_bytes_processed = 0U;4186bytes_read = 0U;41874188pixel_loop:4189/* At this point the following must be set correctly:4190*4191* row_bytes_processed: bytes processed so far4192* pass_width: width of a row in this pass in pixels4193* pixel_depth: depth in bits of a pixel4194* bytes_read: count of filtered bytes in pixel_buffer4195* row_filter: filter byte for this row4196* previous_pixels[0]: pixel 'a' for the filter4197* previous_pixels[1]: pixel 'c' for the filter4198* pixel_buffer[]: bytes_read filtered bytes4199*4200* The code in the loop decompresses PNG_ROW_BUFFER_SIZE filterd pixels4201* from the input, unfilters and transforms them, then saves them to4202* png_struct::row_buffer[row_bytes_processed...].4203*/4204{ /* pixel loop */4205const png_alloc_size_t row_bytes =4206PNG_ROWBYTES(pixel_depth, pass_width);4207png_bytep row_buffer = png_ptr->row_buffer + row_bytes_processed;4208unsigned int pixels;4209png_uint_32 x;42104211/* Sanity check for potential buffer overwrite: */4212affirm(row_bytes > row_bytes_processed);42134214/* Work out the current pixel index of the pixel at the start of the4215* row buffer:4216*/4217switch (pixel_depth)4218{4219case 1U: x = (png_uint_32)/*SAFE*/(row_bytes_processed << 3);4220break;4221case 2U: x = (png_uint_32)/*SAFE*/(row_bytes_processed << 2);4222break;4223case 4U: x = (png_uint_32)/*SAFE*/(row_bytes_processed << 1);4224break;4225case 8U: x = (png_uint_32)/*SAFE*/row_bytes_processed;4226break;4227default: x = (png_uint_32)/*SAFE*/(row_bytes_processed / bpp);4228debug(row_bytes_processed % bpp == 0U);4229break;4230}42314232for (pixels = max_pixels; x < pass_width; x += pixels)4233{4234if (pixels > pass_width - x)4235pixels = (unsigned int)/*SAFE*/(pass_width - x);42364237/* At the end of the image pass Z_FINISH to zlib to optimize the4238* final read (very slightly, is this worth doing?) To do this4239* work out if we are at the end.4240*/4241{4242const png_uint_32 height = png_ptr->height;42434244/* last_pass_row indicates that this is the last row in this4245* pass (the test is optimized for the non-interlaced case):4246*/4247const int last_pass_row = row_number+1 >= height ||4248(interlaced && PNG_LAST_PASS_ROW(row_number,pass,height));42494250/* Set 'finish' if this is the last row in the last pass of4251* the image:4252*/4253const int finish = last_pass_row && (!interlaced ||4254pass >= PNG_LAST_PASS(width, height));42554256const png_alloc_size_t bytes_to_read =4257PNG_ROWBYTES(pixel_depth, pixels);42584259png_alloc_size_t cb;42604261affirm(bytes_to_read > bytes_read);4262cb = png_inflate_IDAT(png_ptr, finish,4263pixel_buffer.buffer + bytes_read,4264bytes_to_read - bytes_read);4265bytes_read += cb;42664267if (bytes_read < bytes_to_read)4268{4269/* Fewer bytes were read than needed: we need to stash all4270* the information required at pixel_loop in png_struct so4271* that the need_row_bytes case can restore it when more4272* input is available.4273*/4274debug(png_ptr->zstream.avail_in == 0U);4275png_ptr->zstream.next_out = NULL;4276png_ptr->zstream.avail_out = 0U;42774278png_ptr->row_bytes_read = row_bytes_processed + bytes_read;4279memcpy(png_ptr->scratch, pixel_buffer.buffer, bytes_read);4280memcpy(png_ptr->scratch+bytes_read, previous_pixels.buffer,42812*bpp);4282png_ptr->scratch[bytes_read+2*bpp] = row_filter;4283png_ptr->row_state = need_row_bytes;4284return png_row_incomplete;4285}42864287debug(bytes_read == bytes_to_read);4288} /* fill pixel_buffer */42894290/* The buffer is full or the row is complete but the calculation4291* was done using the pixel count, so double check against the4292* byte count here:4293*/4294implies(bytes_read != input_byte_count,4295bytes_read == row_bytes - row_bytes_processed);42964297/* At this point all the required information to process the next4298* block of pixels in the row has been read from the input stream4299* and the original, filtered, row data is held in pixel_buffer.4300*4301* Because the buffer will be transformed after the unfilter4302* operation we require whole pixels:4303*/4304debug(bytes_read >= bpp && bytes_read % bpp == 0);43054306if (row_filter > PNG_FILTER_VALUE_NONE)4307{4308/* This is checked in the read code above: */4309debug(row_filter < PNG_FILTER_VALUE_LAST);43104311/* Lazy init of the read functions, which allows hand crafted4312* optimizations for 'bpp' (which does not change.)4313*/4314if (png_ptr->read_filter[0] == NULL)4315png_init_filter_functions(png_ptr, bpp);43164317/* Pixels 'a' then 'c' are in previous_pixels, pixel 'b' is in4318* row_buffer and pixel 'x' (filtered) is in pixel_buffer.4319*/4320png_ptr->read_filter[row_filter-1](bytes_read, bpp,4321pixel_buffer.buffer, row_buffer, previous_pixels.buffer);4322} /* do the filter */43234324/* Now pixel_buffer.buffer contains the *un*filtered bytes of the4325* current row and row_buffer needs updating with these. First4326* preserve pixels 'a' and 'c' for the next time round the loop4327* (if necessary).4328*/4329if (bytes_read < row_bytes - row_bytes_processed)4330{4331debug(bytes_read == input_byte_count);4332memcpy(previous_pixels.buffer/* pixel 'a' */,4333pixel_buffer.buffer + bytes_read - bpp, bpp);4334memcpy(previous_pixels.buffer+bpp/* pixel 'c' */,4335row_buffer + bytes_read - bpp, bpp);4336}43374338/* Now overwrite the previous row pixels in row_buffer with the4339* current row pixels:4340*/4341memcpy(row_buffer, pixel_buffer.buffer, bytes_read);4342row_buffer += bytes_read;4343row_bytes_processed += bytes_read;4344bytes_read = 0U; /* for next buffer */43454346/* Any transforms can now be performed along with any output4347* handling (copy or interlace handling).4348*/4349# ifdef PNG_TRANSFORM_MECH_SUPPORTED4350if (png_ptr->transform_list != NULL)4351{4352unsigned int max_depth;4353png_transform_control tc;43544355png_init_transform_control(&tc, png_ptr);43564357tc.width = pixels;4358tc.sp = tc.dp = pixel_buffer.buffer;43594360/* Run the list. It is ok if it doesn't end up doing4361* anything; this can happen with a lazy init.4362*4363* NOTE: if the only thing in the list is a palette check4364* function it can remove itself at this point.4365*/4366max_depth = png_run_transform_list_forwards(png_ptr, &tc);43674368/* This is too late, a stack overwrite has already4369* happened, but it may still prevent exploits:4370*/4371affirm(max_depth <= png_ptr->row_max_pixel_depth);43724373/* It is very important that the transform produces the4374* same pixel format as the TC_INIT steps:4375*/4376affirm(png_ptr->row_format == tc.format &&4377png_ptr->row_range == tc.range &&4378png_ptr->row_bit_depth == tc.bit_depth);4379# ifdef PNG_READ_GAMMA_SUPPORTED4380/* This checks the output gamma taking into account the4381* fact that small gamma changes are eliminated.4382*/4383debug(png_ptr->row_gamma == tc.gamma ||4384png_gamma_check(png_ptr, &tc));4385# endif /* READ_GAMMA */43864387/* If the caller needs the row saved (for the progressive4388* read API) or if this PNG is interlaced and this row may4389* be required in a subsequent pass (any pass before the4390* last one) then it is stored in4391* png_struct::transformed_row, and that may need to be4392* allocated here.4393*/4394# if defined(PNG_PROGRESSIVE_READ_SUPPORTED) ||\4395defined(PNG_READ_INTERLACING_SUPPORTED)4396if (png_ptr->transform_list != NULL &&4397(save_row4398# ifdef PNG_READ_INTERLACING_SUPPORTED4399|| (png_ptr->do_interlace && pass < 6U)4400# endif /* READ_INTERLACING */4401))4402{4403if (png_ptr->transformed_row == NULL)4404png_ptr->transformed_row = png_voidcast(png_bytep,4405png_malloc(png_ptr, png_calc_rowbytes(png_ptr,4406png_ptr->row_bit_depth *4407PNG_FORMAT_CHANNELS(png_ptr->row_format),4408save_row ? width : (width+1U)>>1)));44094410copy_row(png_ptr, png_ptr->transformed_row,4411pixel_buffer.buffer, x, pixels, 1/*clear*/);4412}4413# endif /* PROGRESSIVE_READ || READ_INTERLACING */4414} /* transform_list != NULL */4415# endif /* TRANSFORM_MECH */44164417/* There are now 'pixels' possibly transformed pixels starting at4418* row pixel x, where 'x' is an index in the interlaced row if4419* interlacing is happening. Handle this row.4420*/4421if (transformed_row != NULL)4422combine_row(png_ptr, transformed_row, pixel_buffer.buffer,4423x, pixels, 0/*!display*/);44244425if (display_row != NULL)4426combine_row(png_ptr, display_row, pixel_buffer.buffer, x,4427pixels, 1/*display*/);4428} /* for x < pass_width */4429} /* pixel loop */44304431png_ptr->row_state = processing_row;4432return png_row_process;44334434default:4435impossible("bad row state");4436} /* forever switch */44374438PNG_UNUSED(save_row) /* May not be used above */4439}44404441void /* PRIVATE */4442png_read_free_row_buffers(png_structrp png_ptr)4443{4444/* The transformed row only gets saved if needed: */4445# if (defined(PNG_PROGRESSIVE_READ_SUPPORTED) ||\4446defined(PNG_READ_INTERLACING_SUPPORTED)) &&\4447defined(PNG_TRANSFORM_MECH_SUPPORTED)4448if (png_ptr->transformed_row != NULL)4449{4450png_free(png_ptr, png_ptr->transformed_row);4451png_ptr->transformed_row = NULL;4452}4453# endif /* PROGRESSIVE_READ || READ_INTERLACING */44544455if (png_ptr->row_buffer != NULL)4456{4457png_free(png_ptr, png_ptr->row_buffer);4458png_ptr->row_buffer = NULL;4459}4460}44614462/* Complete reading of the IDAT chunks. This returns 0 if more data is to4463* be read, 1 if the zlib stream has terminated. Call this routine with4464* zstream.avail_in greater than zero unless there is no more input data.4465* When zstream_avail_in is 0 on entry and the stream does not terminate4466* an "IDAT truncated" error will be output.4467*/4468int /* PRIVATE */4469png_read_finish_IDAT(png_structrp png_ptr)4470{4471enum4472{4473no_error = 0,4474LZ_too_long,4475IDAT_too_long,4476IDAT_truncated4477} error = no_error;44784479/* Release the rowd buffers first; they can use considerable amounts of4480* memory.4481*/4482png_read_free_row_buffers(png_ptr);44834484affirm(png_ptr->zowner == png_IDAT); /* else this should not be called */44854486/* We don't need any more data and the stream should have ended, however the4487* LZ end code may actually not have been processed. In this case we must4488* read it otherwise stray unread IDAT data or, more likely, an IDAT chunk4489* may still remain to be consumed.4490*/4491if (!png_ptr->zstream_ended)4492{4493int end_of_IDAT = png_ptr->zstream.avail_in == 0;4494png_byte b[1];4495png_alloc_size_t cb = png_inflate_IDAT(png_ptr, 2/*finish*/, b, 1);44964497debug(png_ptr->zstream.avail_out == 1-cb &&4498png_ptr->zstream.next_out == cb + b);44994500/* As above, for safety do this: */4501png_ptr->zstream.next_out = NULL;4502png_ptr->zstream.avail_out = 0;45034504/* No data is expected, either compressed or in the IDAT: */4505if (cb != 0)4506error = LZ_too_long;45074508else if (png_ptr->zstream.avail_in == 0 /* && cb == 0 */)4509{4510/* This is the normal case but there may still be some waiting codes4511* (including the adler32 that follow the LZ77 end code; so we can4512* have at least 5 bytes after the end of the row data before the4513* end of the stream.4514*/4515if (!png_ptr->zstream_ended)4516{4517if (!end_of_IDAT)4518return 0; /* keep reading, no detectable error yet */45194520error = IDAT_truncated;4521}45224523/* Else there may still be an error; too much IDAT, but we can't4524* tell.4525*/4526}4527}45284529/* If there is still pending zstream input then there was too much IDAT4530* data:4531*/4532if (!error && png_ptr->zstream.avail_in > 0)4533error = IDAT_too_long;45344535/* Either this is the success case or an error has been detected and4536* warned about.4537*/4538{4539int ret = inflateEnd(&png_ptr->zstream);45404541/* In fact we expect this to always succeed, so it is a good idea to4542* catch it in pre-release builds:4543*/4544debug_handled(ret == Z_OK);45454546if (ret != Z_OK)4547{4548/* This is just a warning; it's safe, and the zstream_error flag is4549* not set.4550*/4551png_zstream_error(&png_ptr->zstream, ret);4552png_chunk_warning(png_ptr, png_ptr->zstream.msg);4553}4554}45554556/* Output an error message if required: */4557if (error && !png_ptr->zstream_error)4558{4559switch (error)4560{4561case LZ_too_long:4562png_benign_error(png_ptr, "compressed data too long");4563break;45644565case IDAT_too_long:4566png_benign_error(png_ptr, "uncompressed data too long");4567break;45684569case IDAT_truncated:4570png_benign_error(png_ptr, "data truncated");4571break;45724573default:4574case no_error: /* Satisfy the compiler */4575break;4576}45774578png_ptr->zstream_error = 1;4579}45804581/* WARNING: leave {next,avail}_in set here, the progressive reader uses these4582* to complete the PNG chunk CRC calculation.4583*/4584png_ptr->zstream_ended = 1;4585png_ptr->zowner = 0;45864587return 1; /* end of stream */4588}45894590/* Optional call to update the users info_ptr structure, can be used from both4591* the progressive and sequential reader, but the app must call it.4592*/4593void PNGAPI4594png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)4595{4596png_debug(1, "in png_read_update_info");45974598if (png_ptr != NULL)4599{4600if (png_ptr->zowner != png_IDAT)4601{4602png_read_start_IDAT(png_ptr);46034604# ifdef PNG_READ_TRANSFORMS_SUPPORTED4605png_read_transform_info(png_ptr, info_ptr);4606# else4607PNG_UNUSED(info_ptr)4608# endif4609}46104611/* New in 1.6.0 this avoids the bug of doing the initializations twice */4612else4613png_app_error(png_ptr,4614"png_read_update_info/png_start_read_image: duplicate call");4615}4616}46174618png_int_32 /* PRIVATE */4619png_read_setting(png_structrp png_ptr, png_uint_32 setting,4620png_uint_32 parameter, png_int_32 value)4621{4622/* Caller checks the arguments for basic validity */4623int only_get = (setting & PNG_SF_GET) != 0U;46244625if (only_get) /* spurious: in case it isn't used */4626setting &= ~PNG_SF_GET;46274628switch (setting)4629{4630# ifdef PNG_SEQUENTIAL_READ_SUPPORTED4631case PNG_SR_COMPRESS_buffer_size:4632if (parameter > 0 && parameter <= ZLIB_IO_MAX)4633{4634png_ptr->IDAT_size = parameter;4635return 0; /* Cannot return a 32-bit value */4636}46374638else4639return PNG_EINVAL;4640# endif /* SEQUENTIAL_READ */46414642# ifdef PNG_READ_GAMMA_SUPPORTED4643case PNG_SR_GAMMA_threshold:4644if (parameter <= 0xFFFF)4645{4646if (!only_get)4647png_ptr->gamma_threshold = PNG_UINT_16(parameter);46484649return (png_int_32)/*SAFE*/parameter;4650}46514652return PNG_EDOM;46534654#if 0 /*NYI*/4655case PNG_SR_GAMMA_accuracy:4656if (parameter <= 1600)4657{4658if (!only_get)4659png_ptr->gamma_accuracy = parameter;46604661return (png_int_32)/*SAFE*/parameter;4662}46634664return PNG_EDOM;4665#endif /*NYI*/4666# endif /* READ_GAMMA */46674668case PNG_SR_CRC_ACTION:4669/* Tell libpng how we react to CRC errors in critical chunks */4670switch (parameter)4671{4672case PNG_CRC_NO_CHANGE: /* Leave setting as is */4673break;46744675case PNG_CRC_WARN_USE: /* Warn/use data */4676png_ptr->critical_crc = crc_warn_use;4677break;46784679case PNG_CRC_QUIET_USE: /* Quiet/use data */4680png_ptr->critical_crc = crc_quiet_use;4681break;46824683default:4684case PNG_CRC_WARN_DISCARD: /* Not valid for critical data */4685return PNG_EINVAL;46864687case PNG_CRC_ERROR_QUIT: /* Error/quit */4688case PNG_CRC_DEFAULT:4689png_ptr->critical_crc = crc_error_quit;4690break;4691}46924693/* Tell libpng how we react to CRC errors in ancillary chunks */4694switch (value)4695{4696case PNG_CRC_NO_CHANGE: /* Leave setting as is */4697break;46984699case PNG_CRC_WARN_USE: /* Warn/use data */4700png_ptr->ancillary_crc = crc_warn_use;4701break;47024703case PNG_CRC_QUIET_USE: /* Quiet/use data */4704png_ptr->ancillary_crc = crc_quiet_use;4705break;47064707case PNG_CRC_ERROR_QUIT: /* Error/quit */4708png_ptr->ancillary_crc = crc_error_quit;4709break;47104711case PNG_CRC_WARN_DISCARD: /* Warn/discard data */4712case PNG_CRC_DEFAULT:4713png_ptr->ancillary_crc = crc_warn_discard;4714break;47154716default:4717return PNG_EINVAL;4718}47194720return 0; /* success */47214722# ifdef PNG_SET_OPTION_SUPPORTED4723case PNG_SRW_OPTION:4724switch (parameter)4725{4726case PNG_MAXIMUM_INFLATE_WINDOW:4727if (png_ptr->maximum_inflate_window)4728{4729if (!value && !only_get)4730png_ptr->maximum_inflate_window = 0U;4731return PNG_OPTION_ON;4732}47334734else4735{4736if (value && !only_get)4737png_ptr->maximum_inflate_window = 1U;4738return PNG_OPTION_OFF;4739}47404741default:4742return PNG_OPTION_UNSET;4743}4744# endif /* SET_OPTION */47454746# ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED4747case PNG_SRW_CHECK_FOR_INVALID_INDEX:4748/* The 'enabled' value is a FORTRAN style three-state: */4749if (value > 0)4750png_ptr->palette_index_check = PNG_PALETTE_CHECK_ON;47514752else if (value < 0)4753png_ptr->palette_index_check = PNG_PALETTE_CHECK_OFF;47544755else4756png_ptr->palette_index_check = PNG_PALETTE_CHECK_DEFAULT;47574758return 0;4759# endif /* READ_CHECK_FOR_INVALID_INDEX */47604761# ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED4762case PNG_SRW_ERROR_HANDLING:4763/* The parameter is a bit mask of what to set, the value is what to4764* set it to.4765*/4766if (value >= PNG_IGNORE && value <= PNG_ERROR &&4767parameter <= PNG_ALL_ERRORS)4768{4769if ((parameter & PNG_BENIGN_ERRORS) != 0U)4770png_ptr->benign_error_action = value & 0x3U;47714772if ((parameter & PNG_APP_WARNINGS) != 0U)4773png_ptr->app_warning_action = value & 0x3U;47744775if ((parameter & PNG_APP_ERRORS) != 0U)4776png_ptr->app_error_action = value & 0x3U;47774778if ((parameter & PNG_IDAT_ERRORS) != 0U)4779png_ptr->IDAT_error_action = value & 0x3U;47804781return 0;4782}47834784return PNG_EINVAL;4785# endif /* BENIGN_READ_ERRORS */47864787default:4788return PNG_ENOSYS; /* not supported (whatever it is) */4789}4790}4791#endif /* READ */479247934794