pngfix.c 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037
  1. /* pngfix.c
  2. *
  3. * Copyright (c) 2014 John Cunningham Bowler
  4. *
  5. * Last changed in libpng 1.6.10 [March 6, 2014]
  6. *
  7. * This code is released under the libpng license.
  8. * For conditions of distribution and use, see the disclaimer
  9. * and license in png.h
  10. *
  11. * Tool to check and fix the zlib inflate 'too far back' problem, see the usage
  12. * message for more information.
  13. */
  14. #include <stdlib.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <ctype.h>
  18. #include <limits.h>
  19. #include <errno.h>
  20. #include <assert.h>
  21. #define implies(x,y) assert(!(x) || (y))
  22. #ifdef __GNUC__
  23. /* This is used to fix the error:
  24. *
  25. * pngfix.c:
  26. * In function 'zlib_advance':
  27. * pngfix.c:181:13: error: assuming signed overflow does not
  28. * occur when simplifying conditional to constant [-Werror=strict-overflow]
  29. */
  30. # define FIX_GCC volatile
  31. #else
  32. # define FIX_GCC
  33. #endif
  34. #define PROGRAM_NAME "pngfix"
  35. /* Define the following to use this program against your installed libpng,
  36. * rather than the one being built here:
  37. */
  38. #ifdef PNG_FREESTANDING_TESTS
  39. # include <png.h>
  40. #else
  41. # include "../../png.h"
  42. #endif
  43. #if PNG_LIBPNG_VER < 10603 /* 1.6.3 */
  44. # error "pngfix will not work with libpng prior to 1.6.3"
  45. #endif
  46. #if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED)
  47. /* zlib.h defines the structure z_stream, an instance of which is included
  48. * in this structure and is required for decompressing the LZ compressed
  49. * data in PNG files.
  50. */
  51. #ifndef ZLIB_CONST
  52. /* We must ensure that zlib uses 'const' in declarations. */
  53. # define ZLIB_CONST
  54. #endif
  55. #include <zlib.h>
  56. #ifdef const
  57. /* zlib.h sometimes #defines const to nothing, undo this. */
  58. # undef const
  59. #endif
  60. /* zlib.h has mediocre z_const use before 1.2.6, this stuff is for compatibility
  61. * with older builds.
  62. */
  63. #if ZLIB_VERNUM < 0x1260
  64. # define PNGZ_MSG_CAST(s) png_constcast(char*,s)
  65. # define PNGZ_INPUT_CAST(b) png_constcast(png_bytep,b)
  66. #else
  67. # define PNGZ_MSG_CAST(s) (s)
  68. # define PNGZ_INPUT_CAST(b) (b)
  69. #endif
  70. #ifndef PNG_MAXIMUM_INFLATE_WINDOW
  71. # error "pngfix not supported in this libpng version"
  72. #endif
  73. #if PNG_ZLIB_VERNUM >= 0x1240
  74. /* Copied from pngpriv.h */
  75. #ifdef __cplusplus
  76. # define png_voidcast(type, value) static_cast<type>(value)
  77. # define png_constcast(type, value) const_cast<type>(value)
  78. # define png_aligncast(type, value) \
  79. static_cast<type>(static_cast<void*>(value))
  80. # define png_aligncastconst(type, value) \
  81. static_cast<type>(static_cast<const void*>(value))
  82. #else
  83. # define png_voidcast(type, value) (value)
  84. # define png_constcast(type, value) ((type)(value))
  85. # define png_aligncast(type, value) ((void*)(value))
  86. # define png_aligncastconst(type, value) ((const void*)(value))
  87. #endif /* __cplusplus */
  88. #if PNG_LIBPNG_VER < 10700
  89. /* Chunk tags (copied from pngpriv.h) */
  90. #define PNG_32b(b,s) ((png_uint_32)(b) << (s))
  91. #define PNG_U32(b1,b2,b3,b4) \
  92. (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
  93. /* Constants for known chunk types. */
  94. #define png_IDAT PNG_U32( 73, 68, 65, 84)
  95. #define png_IEND PNG_U32( 73, 69, 78, 68)
  96. #define png_IHDR PNG_U32( 73, 72, 68, 82)
  97. #define png_PLTE PNG_U32( 80, 76, 84, 69)
  98. #define png_bKGD PNG_U32( 98, 75, 71, 68)
  99. #define png_cHRM PNG_U32( 99, 72, 82, 77)
  100. #define png_fRAc PNG_U32(102, 82, 65, 99) /* registered, not defined */
  101. #define png_gAMA PNG_U32(103, 65, 77, 65)
  102. #define png_gIFg PNG_U32(103, 73, 70, 103)
  103. #define png_gIFt PNG_U32(103, 73, 70, 116) /* deprecated */
  104. #define png_gIFx PNG_U32(103, 73, 70, 120)
  105. #define png_hIST PNG_U32(104, 73, 83, 84)
  106. #define png_iCCP PNG_U32(105, 67, 67, 80)
  107. #define png_iTXt PNG_U32(105, 84, 88, 116)
  108. #define png_oFFs PNG_U32(111, 70, 70, 115)
  109. #define png_pCAL PNG_U32(112, 67, 65, 76)
  110. #define png_pHYs PNG_U32(112, 72, 89, 115)
  111. #define png_sBIT PNG_U32(115, 66, 73, 84)
  112. #define png_sCAL PNG_U32(115, 67, 65, 76)
  113. #define png_sPLT PNG_U32(115, 80, 76, 84)
  114. #define png_sRGB PNG_U32(115, 82, 71, 66)
  115. #define png_sTER PNG_U32(115, 84, 69, 82)
  116. #define png_tEXt PNG_U32(116, 69, 88, 116)
  117. #define png_tIME PNG_U32(116, 73, 77, 69)
  118. #define png_tRNS PNG_U32(116, 82, 78, 83)
  119. #define png_zTXt PNG_U32(122, 84, 88, 116)
  120. #endif
  121. /* The 8 byte signature as a pair of 32 bit quantities */
  122. #define sig1 PNG_U32(137, 80, 78, 71)
  123. #define sig2 PNG_U32( 13, 10, 26, 10)
  124. /* Is the chunk critical? */
  125. #define CRITICAL(chunk) (((chunk) & PNG_U32(32,0,0,0)) == 0)
  126. /* Is it safe to copy? */
  127. #define SAFE_TO_COPY(chunk) (((chunk) & PNG_U32(0,0,0,32)) != 0)
  128. /* Fix ups for builds with limited read support */
  129. #ifndef PNG_ERROR_TEXT_SUPPORTED
  130. # define png_error(a,b) png_err(a)
  131. #endif
  132. /********************************* UTILITIES **********************************/
  133. /* UNREACHED is a value to cause an assert to fail. Because of the way the
  134. * assert macro is written the string "UNREACHED" is produced in the error
  135. * message.
  136. */
  137. #define UNREACHED 0
  138. /* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8 byte
  139. * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so
  140. * arithmetic of 80-bit numbers is sufficient. This representation uses an
  141. * arbitrary length array of png_uint_16 digits (0..65535). The representation
  142. * is little endian.
  143. *
  144. * The arithmetic functions take zero to two uarb values together with the
  145. * number of digits in those values and write the result to the given uarb
  146. * (always the first argument) returning the number of digits in the result.
  147. * If the result is negative the return value is also negative (this would
  148. * normally be an error).
  149. */
  150. typedef png_uint_16 udigit; /* A 'unum' is an array of these */
  151. typedef png_uint_16p uarb;
  152. typedef png_const_uint_16p uarbc;
  153. #define UDIGITS(unum) ((sizeof unum)/(sizeof (udigit))
  154. /* IMPORTANT: only apply this to an array, applied to a pointer the result
  155. * will typically be '2', which is not useful.
  156. */
  157. static int
  158. uarb_set(uarb result, png_alloc_size_t val)
  159. /* Set (initialize) 'result' to 'val'. The size required for 'result' must
  160. * be determined by the caller from a knowledge of the maximum for 'val'.
  161. */
  162. {
  163. int ndigits = 0;
  164. while (val > 0)
  165. {
  166. result[ndigits++] = (png_uint_16)(val & 0xffff);
  167. val >>= 16;
  168. }
  169. return ndigits;
  170. }
  171. static int
  172. uarb_copy(uarb to, uarb from, int idigits)
  173. /* Copy a uarb, may reduce the digit count */
  174. {
  175. int d, odigits;
  176. for (d=odigits=0; d<idigits; ++d)
  177. if ((to[d] = from[d]) != 0)
  178. odigits = d+1;
  179. return odigits;
  180. }
  181. static int
  182. uarb_inc(uarb num, int in_digits, png_int_32 add)
  183. /* This is a signed 32-bit add, except that to avoid overflow the value added
  184. * or subtracted must be no more than 2^31-65536. A negative result
  185. * indicates a negative number (which is an error below). The size of
  186. * 'num' should be max(in_digits+1,2) for arbitrary 'add' but can be just
  187. * in_digits+1 if add is known to be in the range -65535..65535.
  188. */
  189. {
  190. FIX_GCC int out_digits = 0;
  191. while (out_digits < in_digits)
  192. {
  193. add += num[out_digits];
  194. num[out_digits++] = (png_uint_16)(add & 0xffff);
  195. add >>= 16;
  196. }
  197. while (add != 0 && add != (-1))
  198. {
  199. num[out_digits++] = (png_uint_16)(add & 0xffff);
  200. add >>= 16;
  201. }
  202. if (add == 0)
  203. {
  204. while (out_digits > 0 && num[out_digits-1] == 0)
  205. --out_digits;
  206. return out_digits; /* may be 0 */
  207. }
  208. else /* negative result */
  209. {
  210. while (out_digits > 1 && num[out_digits-1] == 0xffff)
  211. --out_digits;
  212. return -out_digits;
  213. }
  214. }
  215. static int
  216. uarb_add32(uarb num, int in_digits, png_uint_32 add)
  217. /* As above but this works with any 32-bit value and only does 'add' */
  218. {
  219. if (in_digits > 0)
  220. {
  221. in_digits = uarb_inc(num, in_digits, add & 0xffff);
  222. return uarb_inc(num+1, in_digits-1, add >> 16)+1;
  223. }
  224. return uarb_set(num, add);
  225. }
  226. static int
  227. uarb_mult_digit(uarb acc, int a_digits, uarb num, FIX_GCC int n_digits,
  228. png_uint_16 val)
  229. /* Primitive one-digit multiply - 'val' must be 0..65535. Note that this
  230. * primitive is a multiply and accumulate - the result of *num * val is added
  231. * to *acc.
  232. *
  233. * This is a one-digit multiply, so the product may be up to one digit longer
  234. * than 'num', however the add to 'acc' means that the caller must ensure
  235. * that 'acc' is at least one digit longer than this *and* at least one digit
  236. * longer than the current length of 'acc'. (Or the caller must otherwise
  237. * ensure 'adigits' is adequate from knowledge of the values.)
  238. */
  239. {
  240. /* The digits in *acc, *num and val are in the range 0..65535, so the
  241. * result below is at most (65535*65535)+2*65635 = 65535*(65535+2), which is
  242. * exactly 0xffffffff.
  243. */
  244. if (val > 0 && n_digits > 0) /* Else the product is 0 */
  245. {
  246. png_uint_32 carry = 0;
  247. int out_digits = 0;
  248. while (out_digits < n_digits || carry > 0)
  249. {
  250. if (out_digits < a_digits)
  251. carry += acc[out_digits];
  252. if (out_digits < n_digits)
  253. carry += (png_uint_32)num[out_digits] * val;
  254. acc[out_digits++] = (png_uint_16)(carry & 0xffff);
  255. carry >>= 16;
  256. }
  257. /* So carry is 0 and all the input digits have been consumed. This means
  258. * that it is possible to skip any remaining digits in acc.
  259. */
  260. if (out_digits > a_digits)
  261. return out_digits;
  262. }
  263. return a_digits;
  264. }
  265. static int
  266. uarb_mult32(uarb acc, int a_digits, uarb num, int n_digits, png_uint_32 val)
  267. /* calculate acc += num * val, 'val' may be any 32-bit value, 'acc' and 'num'
  268. * may be any value, returns the number of digits in 'acc'.
  269. */
  270. {
  271. if (n_digits > 0 && val > 0)
  272. {
  273. a_digits = uarb_mult_digit(acc, a_digits, num, n_digits,
  274. (png_uint_16)(val & 0xffff));
  275. /* Because n_digits and val are >0 the following must be true: */
  276. assert(a_digits > 0);
  277. val >>= 16;
  278. if (val > 0)
  279. a_digits = uarb_mult_digit(acc+1, a_digits-1, num, n_digits,
  280. (png_uint_16)val) + 1;
  281. }
  282. return a_digits;
  283. }
  284. static int
  285. uarb_shift(uarb inout, int ndigits, unsigned int right_shift)
  286. /* Shift inout right by right_shift bits, right_shift must be in the range
  287. * 1..15
  288. */
  289. {
  290. FIX_GCC int i = ndigits;
  291. png_uint_16 carry = 0;
  292. assert(right_shift >= 1 && right_shift <= 15);
  293. while (--i >= 0)
  294. {
  295. png_uint_16 temp = (png_uint_16)(carry | (inout[i] >> right_shift));
  296. /* Bottom bits to top bits of carry */
  297. carry = (png_uint_16)((inout[i] << (16-right_shift)) & 0xffff);
  298. inout[i] = temp;
  299. /* The shift may reduce ndigits */
  300. if (i == ndigits-1 && temp == 0)
  301. ndigits = i;
  302. }
  303. return ndigits;
  304. }
  305. static int
  306. uarb_cmp(uarb a, int adigits, uarb b, int bdigits)
  307. /* Return -1/0/+1 according as a<b/a==b/a>b */
  308. {
  309. if (adigits < bdigits)
  310. return -1;
  311. if (adigits > bdigits)
  312. return 1;
  313. while (adigits-- > 0)
  314. if (a[adigits] < b[adigits])
  315. return -1;
  316. else if (a[adigits] > b[adigits])
  317. return 1;
  318. return 0;
  319. }
  320. #if 0 /*UNUSED*/
  321. static int
  322. uarb_eq32(uarb num, int digits, png_uint_32 val)
  323. /* Return true if the uarb is equal to 'val' */
  324. {
  325. switch (digits)
  326. {
  327. case 0: return val == 0;
  328. case 1: return val == num[0];
  329. case 2: return (val & 0xffff) == num[0] && (val >> 16) == num[1];
  330. default: return 0;
  331. }
  332. }
  333. #endif
  334. static void
  335. uarb_printx(uarb num, int digits, FILE *out)
  336. /* Print 'num' as a hexadecimal number (easier than decimal!) */
  337. {
  338. while (digits > 0)
  339. if (num[--digits] > 0)
  340. {
  341. fprintf(out, "0x%x", num[digits]);
  342. while (digits > 0)
  343. fprintf(out, "%.4x", num[--digits]);
  344. }
  345. else if (digits == 0) /* the number is 0 */
  346. fputs("0x0", out);
  347. }
  348. static void
  349. uarb_print(uarb num, int digits, FILE *out)
  350. /* Prints 'num' as a decimal if it will fit in an unsigned long, else as a
  351. * hexadecimal number. Notice that the results vary for images over 4GByte
  352. * in a system dependent way, and the hexadecimal form doesn't work very well
  353. * in awk script input.
  354. *
  355. *
  356. * TODO: write uarb_div10
  357. */
  358. {
  359. if (digits * sizeof (udigit) > sizeof (unsigned long))
  360. uarb_printx(num, digits, out);
  361. else
  362. {
  363. unsigned long n = 0;
  364. while (digits > 0)
  365. n = (n << 16) + num[--digits];
  366. fprintf(out, "%lu", n);
  367. }
  368. }
  369. /* Generate random bytes. This uses a boring repeatable algorithm and it
  370. * is implemented here so that it gives the same set of numbers on every
  371. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  372. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  373. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  374. * Generation.)
  375. *
  376. * (Copied from contrib/libtests/pngvalid.c)
  377. */
  378. static void
  379. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  380. {
  381. png_uint_32 u0 = seed[0], u1 = seed[1];
  382. png_bytep bytes = png_voidcast(png_bytep, pv);
  383. /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
  384. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  385. */
  386. size_t i;
  387. for (i=0; i<size; ++i)
  388. {
  389. /* First generate 8 new bits then shift them in at the end. */
  390. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  391. u1 <<= 8;
  392. u1 |= u0 >> 24;
  393. u0 <<= 8;
  394. u0 |= u;
  395. *bytes++ = (png_byte)u;
  396. }
  397. seed[0] = u0;
  398. seed[1] = u1;
  399. }
  400. /* Clear an object to a random value. */
  401. static void
  402. clear(void *pv, size_t size)
  403. {
  404. static png_uint_32 clear_seed[2] = { 0x12345678, 0x9abcdef0 };
  405. make_random_bytes(clear_seed, pv, size);
  406. }
  407. #define CLEAR(object) clear(&(object), sizeof (object))
  408. /* Copied from unreleased 1.7 code.
  409. *
  410. * CRC checking uses a local pre-built implementation of the Ethernet CRC32.
  411. * This is to avoid a function call to the zlib DLL and to optimize the
  412. * byte-by-byte case.
  413. */
  414. static png_uint_32 crc_table[256] =
  415. {
  416. 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
  417. 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
  418. 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
  419. 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
  420. 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
  421. 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
  422. 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
  423. 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
  424. 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
  425. 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
  426. 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
  427. 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
  428. 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
  429. 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
  430. 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
  431. 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
  432. 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
  433. 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
  434. 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
  435. 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
  436. 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
  437. 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
  438. 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
  439. 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
  440. 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
  441. 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
  442. 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
  443. 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
  444. 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
  445. 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
  446. 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
  447. 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
  448. 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
  449. 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
  450. 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
  451. 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
  452. 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
  453. 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
  454. 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
  455. 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
  456. 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
  457. 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
  458. 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
  459. 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
  460. 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
  461. 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
  462. 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
  463. 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
  464. 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
  465. 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
  466. 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
  467. 0x2d02ef8d
  468. };
  469. /* The CRC calculated here *IS* conditioned, the corresponding value used by
  470. * zlib and the result value is obtained by XORing with CRC_INIT, which is also
  471. * the first value that must be passed in (for the first byte) to crc_one_byte.
  472. */
  473. #define CRC_INIT 0xffffffff
  474. static png_uint_32
  475. crc_one_byte(png_uint_32 crc, int b)
  476. {
  477. return crc_table[(crc ^ b) & 0xff] ^ (crc >> 8);
  478. }
  479. static png_uint_32
  480. crc_init_4(png_uint_32 value)
  481. {
  482. /* This is an alternative to the algorithm used in zlib, which requires four
  483. * separate tables to parallelize the four byte operations, it only works for
  484. * a CRC of the first four bytes of the stream, but this is what happens in
  485. * the parser below where length+chunk-name is read and chunk-name used to
  486. * initialize the CRC. Notice that the calculation here avoids repeated
  487. * conditioning (xor with 0xffffffff) by storing the conditioned value.
  488. */
  489. png_uint_32 crc = crc_table[(~value >> 24)] ^ 0xffffff;
  490. crc = crc_table[(crc ^ (value >> 16)) & 0xff] ^ (crc >> 8);
  491. crc = crc_table[(crc ^ (value >> 8)) & 0xff] ^ (crc >> 8);
  492. return crc_table[(crc ^ value) & 0xff] ^ (crc >> 8);
  493. }
  494. static int
  495. chunk_type_valid(png_uint_32 c)
  496. /* Bit whacking approach to chunk name validation that is intended to avoid
  497. * branches. The cost is that it uses a lot of 32-bit constants, which might
  498. * be bad on some architectures.
  499. */
  500. {
  501. png_uint_32 t;
  502. /* Remove bit 5 from all but the reserved byte; this means every
  503. * 8-bit unit must be in the range 65-90 to be valid. So bit 5
  504. * must be zero, bit 6 must be set and bit 7 zero.
  505. */
  506. c &= ~PNG_U32(32,32,0,32);
  507. t = (c & ~0x1f1f1f1f) ^ 0x40404040;
  508. /* Subtract 65 for each 8 bit quantity, this must not overflow
  509. * and each byte must then be in the range 0-25.
  510. */
  511. c -= PNG_U32(65,65,65,65);
  512. t |=c ;
  513. /* Subtract 26, handling the overflow which should set the top
  514. * three bits of each byte.
  515. */
  516. c -= PNG_U32(25,25,25,26);
  517. t |= ~c;
  518. return (t & 0xe0e0e0e0) == 0;
  519. }
  520. /**************************** CONTROL INFORMATION *****************************/
  521. /* Information about a sequence of IDAT chunks, the chunks have been re-synced
  522. * using sync_stream below and the new lengths are recorded here. Because the
  523. * number of chunks is unlimited this is handled using a linked list of these
  524. * structures.
  525. */
  526. struct IDAT_list
  527. {
  528. struct IDAT_list *next; /* Linked list */
  529. unsigned int length; /* Actual length of the array below */
  530. unsigned int count; /* Number of entries that are valid */
  531. # define IDAT_INIT_LENGTH 16
  532. png_uint_32 lengths[IDAT_INIT_LENGTH];
  533. };
  534. static void
  535. IDAT_list_init(struct IDAT_list *list)
  536. {
  537. CLEAR(*list);
  538. list->next = NULL;
  539. list->length = IDAT_INIT_LENGTH;
  540. }
  541. static size_t
  542. IDAT_list_size(struct IDAT_list *list, unsigned int length)
  543. /* Return the size in bytes of an IDAT_list of the given length. */
  544. {
  545. if (list != NULL)
  546. length = list->length;
  547. return sizeof *list - sizeof list->lengths +
  548. length * sizeof list->lengths[0];
  549. }
  550. static void
  551. IDAT_list_end(struct IDAT_list *IDAT_list)
  552. {
  553. struct IDAT_list *list = IDAT_list->next;
  554. CLEAR(*IDAT_list);
  555. while (list != NULL)
  556. {
  557. struct IDAT_list *next = list->next;
  558. clear(list, IDAT_list_size(list, 0));
  559. free(list);
  560. list = next;
  561. }
  562. }
  563. static struct IDAT_list *
  564. IDAT_list_extend(struct IDAT_list *tail)
  565. {
  566. /* Use the previous cached value if available. */
  567. struct IDAT_list *next = tail->next;
  568. if (next == NULL)
  569. {
  570. /* Insert a new, malloc'ed, block of IDAT information buffers, this
  571. * one twice as large as the previous one:
  572. */
  573. unsigned int length = 2 * tail->length;
  574. if (length < tail->length) /* arithmetic overflow */
  575. length = tail->length;
  576. next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
  577. CLEAR(*next);
  578. /* The caller must handle this: */
  579. if (next == NULL)
  580. return NULL;
  581. next->next = NULL;
  582. next->length = length;
  583. tail->next = next;
  584. }
  585. return next;
  586. }
  587. /* GLOBAL CONTROL STRUCTURE */
  588. struct global
  589. {
  590. /* PUBLIC GLOBAL VARIABLES: OWNER INITIALIZE */
  591. unsigned int errors :1; /* print file errors to stderr */
  592. unsigned int warnings :1; /* print libpng warnings to stderr */
  593. unsigned int optimize_zlib :1; /* Run optimization search */
  594. unsigned int quiet :2; /* don't output summaries */
  595. unsigned int verbose :3; /* various internal tracking */
  596. unsigned int skip :3; /* Non-critical chunks to skip */
  597. # define SKIP_NONE 0
  598. # define SKIP_BAD_CRC 1 /* Chunks with a bad CRC */
  599. # define SKIP_UNSAFE 2 /* Chunks not safe to copy */
  600. # define SKIP_UNUSED 3 /* Chunks not used by libpng */
  601. # define SKIP_TRANSFORM 4 /* Chunks only used in transforms */
  602. # define SKIP_COLOR 5 /* Everything but tRNS, sBIT, gAMA and sRGB */
  603. # define SKIP_ALL 6 /* Everything but tRNS and sBIT */
  604. png_uint_32 idat_max; /* 0 to perform no re-chunking */
  605. int status_code; /* Accumulated status code */
  606. # define TOO_FAR_BACK 0x01 /* found a too-far-back error */
  607. # define CRC_ERROR 0x02 /* fixed an invalid CRC */
  608. # define STREAM_ERROR 0x04 /* damaged PNG stream (may be fixable) */
  609. # define TRUNCATED 0x08 /* truncated but still readable */
  610. # define FILE_ERROR 0x10 /* could not read the file */
  611. # define WRITE_ERROR 0x20 /* write error (this terminates the read) */
  612. # define INTERNAL_ERROR 0x40 /* internal limits/errors encountered */
  613. /* PUBLIC GLOBAL VARIABLES: USED INTERNALLY BY IDAT READ CODE */
  614. struct IDAT_list idat_cache; /* Cache of file IDAT information buffers */
  615. /* The structure is shared across all uses of this global control
  616. * structure to avoid reallocation between IDAT streams.
  617. */
  618. };
  619. static int
  620. global_end(struct global *global)
  621. {
  622. int rc;
  623. IDAT_list_end(&global->idat_cache);
  624. rc = global->status_code;
  625. CLEAR(*global);
  626. return rc;
  627. }
  628. static void
  629. global_init(struct global *global)
  630. /* Call this once (and only once) to initialize the control */
  631. {
  632. CLEAR(*global);
  633. /* Globals */
  634. global->errors = 0;
  635. global->warnings = 0;
  636. global->quiet = 0;
  637. global->verbose = 0;
  638. global->idat_max = 0; /* no re-chunking of IDAT */
  639. global->optimize_zlib = 0;
  640. global->skip = SKIP_NONE;
  641. global->status_code = 0;
  642. IDAT_list_init(&global->idat_cache);
  643. }
  644. static int
  645. skip_chunk_type(const struct global *global, png_uint_32 type)
  646. /* Return true if this chunk is to be skipped according to the --strip
  647. * option. This code needs to recognize all known ancillary chunks in order
  648. * to handle the --strip=unsafe option.
  649. */
  650. {
  651. /* Never strip critical chunks: */
  652. if (CRITICAL(type))
  653. return 0;
  654. switch (type)
  655. {
  656. /* Chunks that are treated as, effectively, critical because they affect
  657. * correct interpretation of the pixel values:
  658. */
  659. case png_tRNS: case png_sBIT:
  660. return 0;
  661. /* Chunks that specify gamma encoding which should therefore only be
  662. * removed the the user insists:
  663. */
  664. case png_gAMA: case png_sRGB:
  665. if (global->skip >= SKIP_ALL)
  666. return 1;
  667. return 0;
  668. /* Chunks that affect color interpretation - not used by libpng and rarely
  669. * used by applications, but technically still required for correct
  670. * interpretation of the image data:
  671. */
  672. case png_cHRM: case png_iCCP:
  673. if (global->skip >= SKIP_COLOR)
  674. return 1;
  675. return 0;
  676. /* Other chunks that are used by libpng in image transformations (as
  677. * opposed to known chunks that have get/set APIs but are not otherwise
  678. * used.)
  679. */
  680. case png_bKGD:
  681. if (global->skip >= SKIP_TRANSFORM)
  682. return 1;
  683. return 0;
  684. /* All other chunks that libpng knows about and affect neither image
  685. * interpretation nor libpng transforms - chunks that are effectively
  686. * unused by libpng even though libpng might recognize and store them.
  687. */
  688. case png_fRAc: case png_gIFg: case png_gIFt: case png_gIFx: case png_hIST:
  689. case png_iTXt: case png_oFFs: case png_pCAL: case png_pHYs: case png_sCAL:
  690. case png_sPLT: case png_sTER: case png_tEXt: case png_tIME: case png_zTXt:
  691. if (global->skip >= SKIP_UNUSED)
  692. return 1;
  693. return 0;
  694. /* Chunks that libpng does not know about (notice that this depends on the
  695. * list above including all known chunks!) The decision here depends on
  696. * whether the safe-to-copy bit is set in the chunk type.
  697. */
  698. default:
  699. if (SAFE_TO_COPY(type))
  700. {
  701. if (global->skip >= SKIP_UNUSED) /* as above */
  702. return 1;
  703. }
  704. else if (global->skip >= SKIP_UNSAFE)
  705. return 1;
  706. return 0;
  707. }
  708. }
  709. /* PER-FILE CONTROL STRUCTURE */
  710. struct chunk;
  711. struct IDAT;
  712. struct file
  713. {
  714. /* ANCESTORS */
  715. struct global *global;
  716. /* PUBLIC PER-FILE VARIABLES: CALLER INITIALIZE */
  717. const char * file_name;
  718. const char * out_name; /* Name of output file (if required) */
  719. /* PUBLIC PER-FILE VARIABLES: SET BY PNG READ CODE */
  720. /* File specific result codes */
  721. int status_code; /* Set to a bit mask of the following: */
  722. int read_errno; /* Records a read error errno */
  723. int write_errno; /* Records a write error errno */
  724. /* IHDR information */
  725. png_uint_32 width;
  726. png_uint_32 height;
  727. png_byte bit_depth;
  728. png_byte color_type;
  729. png_byte compression_method;
  730. png_byte filter_method;
  731. png_byte interlace_method;
  732. udigit image_bytes[5];
  733. int image_digits;
  734. /* PROTECTED PER-FILE VARIABLES: USED BY THE READ CODE */
  735. FILE * file; /* Original PNG file */
  736. FILE * out; /* If a new one is being written */
  737. jmp_buf jmpbuf; /* Set while reading a PNG */
  738. /* PROTECTED CHUNK SPECIFIC VARIABLES: USED BY CHUNK CODE */
  739. /* The following variables are used during reading to record the length, type
  740. * and data position of the *next* chunk or, right at the start, the
  741. * signature (in length,type).
  742. *
  743. * When a chunk control structure is instantiated these values are copied
  744. * into the structure and can then be overritten with the data for the next
  745. * chunk.
  746. */
  747. fpos_t data_pos; /* Position of first byte of chunk data */
  748. png_uint_32 length; /* First word (length or signature start) */
  749. png_uint_32 type; /* Second word (type or signature end) */
  750. png_uint_32 crc; /* Running chunk CRC (used by read_chunk) */
  751. /* These counts are maintained by the read and write routines below and are
  752. * reset by the chunk handling code. They record the total number of bytes
  753. * read or written for the chunk, including the header (length,type) bytes.
  754. */
  755. png_uint_32 read_count; /* Count of bytes read (in the chunk) */
  756. png_uint_32 write_count; /* Count of bytes written (in the chunk) */
  757. int state; /* As defined here: */
  758. # define STATE_SIGNATURE 0 /* The signature is being written */
  759. # define STATE_CHUNKS 1 /* Non-IDAT chunks are being written */
  760. # define STATE_IDAT 2 /* An IDAT stream is being written */
  761. /* Two pointers used to enable clean-up in the event of fatal errors and to
  762. * hold state about the parser process (only one of each at present.)
  763. */
  764. struct chunk * chunk;
  765. struct IDAT * idat;
  766. /* Interface to allocate a new chunk or IDAT control structure. The result
  767. * is returned by setting one or other of the above variables. Note that the
  768. * relevant initializer is called by the allocator function. The alloc_ptr
  769. * is used only by the implementation of the allocate function.
  770. */
  771. void * alloc_ptr;
  772. void (*alloc)(struct file*,int idat);
  773. /* idat: allocate IDAT not chunk */
  774. };
  775. /* Valid longjmp (stop) codes are: */
  776. #define LIBPNG_WARNING_CODE 1 /* generic png_error */
  777. #define LIBPNG_ERROR_CODE 2 /* generic png_error */
  778. #define ZLIB_ERROR_CODE 3 /* generic zlib error */
  779. #define INVALID_ERROR_CODE 4 /* detected an invalid PNG */
  780. #define READ_ERROR_CODE 5 /* read failed */
  781. #define WRITE_ERROR_CODE 6 /* error in write */
  782. #define UNEXPECTED_ERROR_CODE 7 /* unexpected (internal?) error */
  783. static void
  784. emit_string(const char *str, FILE *out)
  785. /* Print a string with spaces replaced by '_' and non-printing characters by
  786. * an octal escape.
  787. */
  788. {
  789. for (; *str; ++str)
  790. if (isgraph(UCHAR_MAX & *str))
  791. putc(*str, out);
  792. else if (isspace(UCHAR_MAX & *str))
  793. putc('_', out);
  794. else
  795. fprintf(out, "\\%.3o", *str);
  796. }
  797. static const char *
  798. strcode(int code)
  799. {
  800. switch (code)
  801. {
  802. case LIBPNG_WARNING_CODE: return "warning";
  803. case LIBPNG_ERROR_CODE: return "libpng";
  804. case ZLIB_ERROR_CODE: return "zlib";
  805. case INVALID_ERROR_CODE: return "invalid";
  806. case READ_ERROR_CODE: return "read";
  807. case WRITE_ERROR_CODE: return "write";
  808. case UNEXPECTED_ERROR_CODE: return "unexpected";
  809. default: return "INVALID";
  810. }
  811. }
  812. static void
  813. emit_error(struct file *file, int code, const char *what)
  814. /* Generic error message routine, takes a 'stop' code but can be used
  815. * elsewhere. Always outputs a message.
  816. */
  817. {
  818. const char *reason;
  819. int err = 0;
  820. switch (code)
  821. {
  822. case LIBPNG_WARNING_CODE: reason = "libpng warning:"; break;
  823. case LIBPNG_ERROR_CODE: reason = "libpng error:"; break;
  824. case ZLIB_ERROR_CODE: reason = "zlib error:"; break;
  825. case INVALID_ERROR_CODE: reason = "invalid"; break;
  826. case READ_ERROR_CODE: reason = "read failure:";
  827. err = file->read_errno;
  828. break;
  829. case WRITE_ERROR_CODE: reason = "write error";
  830. err = file->write_errno;
  831. break;
  832. case UNEXPECTED_ERROR_CODE: reason = "unexpected error:";
  833. err = file->read_errno;
  834. if (err == 0)
  835. err = file->write_errno;
  836. break;
  837. default: reason = "INVALID (internal error):"; break;
  838. }
  839. if (err != 0)
  840. fprintf(stderr, "%s: %s %s [%s]\n", file->file_name, reason, what,
  841. strerror(err));
  842. else
  843. fprintf(stderr, "%s: %s %s\n", file->file_name, reason, what);
  844. }
  845. static void chunk_end(struct chunk **);
  846. static void IDAT_end(struct IDAT **);
  847. static int
  848. file_end(struct file *file)
  849. {
  850. int rc;
  851. /* If either of the chunk pointers are set end them here, the IDAT structure
  852. * must be deallocated first as it may deallocate the chunk structure.
  853. */
  854. if (file->idat != NULL)
  855. IDAT_end(&file->idat);
  856. if (file->chunk != NULL)
  857. chunk_end(&file->chunk);
  858. rc = file->status_code;
  859. if (file->file != NULL)
  860. (void)fclose(file->file);
  861. if (file->out != NULL)
  862. {
  863. /* NOTE: this is bitwise |, all the following functions must execute and
  864. * must succeed.
  865. */
  866. if (ferror(file->out) | fflush(file->out) | fclose(file->out))
  867. {
  868. perror(file->out_name);
  869. emit_error(file, READ_ERROR_CODE, "output write error");
  870. rc |= WRITE_ERROR;
  871. }
  872. }
  873. /* Accumulate the result codes */
  874. file->global->status_code |= rc;
  875. CLEAR(*file);
  876. return rc; /* status code: non-zero on read or write error */
  877. }
  878. static int
  879. file_init(struct file *file, struct global *global, const char *file_name,
  880. const char *out_name, void *alloc_ptr, void (*alloc)(struct file*,int))
  881. /* Initialize a file control structure. This will open the given files as
  882. * well. The status code returned is 0 on success, non zero (using the flags
  883. * above) on a file open error.
  884. */
  885. {
  886. CLEAR(*file);
  887. file->global = global;
  888. file->file_name = file_name;
  889. file->out_name = out_name;
  890. file->status_code = 0;
  891. file->read_errno = 0;
  892. file->write_errno = 0;
  893. file->file = NULL;
  894. file->out = NULL;
  895. /* jmpbuf is garbage: must be set by read_png */
  896. file->read_count = 0;
  897. file->state = STATE_SIGNATURE;
  898. file->chunk = NULL;
  899. file->idat = NULL;
  900. file->alloc_ptr = alloc_ptr;
  901. file->alloc = alloc;
  902. /* Open the files: */
  903. assert(file_name != NULL);
  904. file->file = fopen(file_name, "rb");
  905. if (file->file == NULL)
  906. {
  907. file->read_errno = errno;
  908. file->status_code |= FILE_ERROR;
  909. /* Always output: please give a readable file! */
  910. perror(file_name);
  911. return FILE_ERROR;
  912. }
  913. if (out_name != NULL)
  914. {
  915. file->out = fopen(out_name, "wb");
  916. if (file->out == NULL)
  917. {
  918. file->write_errno = errno;
  919. file->status_code |= WRITE_ERROR;
  920. perror(out_name);
  921. return WRITE_ERROR;
  922. }
  923. }
  924. return 0;
  925. }
  926. static void
  927. log_error(struct file *file, int code, const char *what)
  928. /* Like emit_error but checks the global 'errors' flag */
  929. {
  930. if (file->global->errors)
  931. emit_error(file, code, what);
  932. }
  933. static char
  934. type_char(png_uint_32 v)
  935. {
  936. /* In fact because chunk::chunk_type is validated prior to any call to this
  937. * function it will always return a-zA-Z, but the extra codes are just there
  938. * to help in finding internal (programming) errors. Note that the code only
  939. * ever considers the low 7 bits of the value (so it is not necessary for the
  940. * type_name function to mask of the byte.)
  941. */
  942. if (v & 32)
  943. return "!abcdefghijklmnopqrstuvwxyz56789"[(v-96)&31];
  944. else
  945. return "@ABCDEFGHIJKLMNOPQRSTUVWXYZ01234"[(v-64)&31];
  946. }
  947. static void
  948. type_name(png_uint_32 type, FILE *out)
  949. {
  950. putc(type_char(type >> 24), out);
  951. putc(type_char(type >> 16), out);
  952. putc(type_char(type >> 8), out);
  953. putc(type_char(type ), out);
  954. }
  955. static void
  956. type_sep(FILE *out)
  957. {
  958. putc(':', out);
  959. putc(' ', out);
  960. }
  961. static png_uint_32 current_type(struct file *file, int code);
  962. PNG_NORETURN static void
  963. stop(struct file *file, int code, const char *what)
  964. /* Return control when a PNG file cannot be read. This outputs an 'ERR'
  965. * summary line too.
  966. */
  967. {
  968. log_error(file, code, what);
  969. /* The chunk being read is typically identified by file->chunk or, if this is
  970. * NULL, by file->type. This may be wrong if libpng reads ahead, but this
  971. * only happens with IDAT where libpng reads the header then jumps around
  972. * finding errors in the previous chunks. We know that is happening because
  973. * we are at the start of the IDAT (i.e. no IDAT data has yet been written.)
  974. *
  975. * SUMMARY FORMAT (stop):
  976. *
  977. * IDAT ERR status code read-errno write-errno message file
  978. *
  979. * 'uncompressed' will be 0 if there was a problem in the IHDR. The errno
  980. * values are emit_string(strerror(errno)).
  981. */
  982. if (file->global->quiet < 2) /* need two quiets to stop this. */
  983. {
  984. png_uint_32 type;
  985. if (file->chunk != NULL)
  986. type = current_type(file, code); /* Gropes in struct chunk and IDAT */
  987. else
  988. type = file->type;
  989. if (type)
  990. type_name(type, stdout);
  991. else /* magic: an IDAT header, produces bogons for too many IDATs */
  992. fputs("HEAD", stdout); /* not a registered chunk! */
  993. printf(" ERR %.2x %s ", file->status_code, strcode(code));
  994. /* This only works one strerror at a time, because of the way strerror is
  995. * implemented.
  996. */
  997. emit_string(strerror(file->read_errno), stdout);
  998. putc(' ', stdout);
  999. emit_string(strerror(file->write_errno), stdout);
  1000. putc(' ', stdout);
  1001. emit_string(what, stdout);
  1002. putc(' ', stdout);
  1003. fputs(file->file_name, stdout);
  1004. putc('\n', stdout);
  1005. }
  1006. file->status_code |= FILE_ERROR;
  1007. longjmp(file->jmpbuf, code);
  1008. }
  1009. PNG_NORETURN static void
  1010. stop_invalid(struct file *file, const char *what)
  1011. {
  1012. stop(file, INVALID_ERROR_CODE, what);
  1013. }
  1014. static void
  1015. type_message(struct file *file, png_uint_32 type, const char *what)
  1016. /* Error message for a chunk; the chunk name comes from 'type' */
  1017. {
  1018. if (file->global->errors)
  1019. {
  1020. fputs(file->file_name, stderr);
  1021. type_sep(stderr);
  1022. type_name(type, stderr);
  1023. type_sep(stderr);
  1024. fputs(what, stderr);
  1025. putc('\n', stderr);
  1026. }
  1027. }
  1028. /* Input file positioning - we jump around in the input file while reading
  1029. * stuff, these wrappers deal with the error handling.
  1030. */
  1031. static void
  1032. file_getpos(struct file *file, fpos_t *pos)
  1033. {
  1034. if (fgetpos(file->file, pos))
  1035. {
  1036. /* This is unexpected, so perror it */
  1037. perror(file->file_name);
  1038. stop(file, READ_ERROR_CODE, "fgetpos");
  1039. }
  1040. }
  1041. static void
  1042. file_setpos(struct file *file, const fpos_t *pos)
  1043. {
  1044. if (fsetpos(file->file, pos))
  1045. {
  1046. perror(file->file_name);
  1047. stop(file, READ_ERROR_CODE, "fsetpos");
  1048. }
  1049. }
  1050. static void
  1051. getpos(struct file *file)
  1052. /* Get the current position and store it in 'data_pos'. The corresponding
  1053. * setpos() function is chunk specific because it uses the copy of the
  1054. * position for the specific chunk.
  1055. */
  1056. {
  1057. file_getpos(file, &file->data_pos);
  1058. }
  1059. /* Read utility - read a single byte, returns a value in the range 0..255 or EOF
  1060. * on a read error. In the latter case status_code and read_errno are updated
  1061. * appropriately.
  1062. */
  1063. static int
  1064. read_byte(struct file *file)
  1065. {
  1066. int ch = getc(file->file);
  1067. if (ch >= 0 && ch <= 255)
  1068. {
  1069. ++(file->read_count);
  1070. return ch;
  1071. }
  1072. else if (ch != EOF)
  1073. {
  1074. file->status_code |= INTERNAL_ERROR;
  1075. file->read_errno = ERANGE; /* out of range character */
  1076. /* This is very unexpected; an error message is always output: */
  1077. emit_error(file, UNEXPECTED_ERROR_CODE, "file read");
  1078. }
  1079. # ifdef EINTR
  1080. else if (errno == EINTR) /* Interrupted, try again */
  1081. {
  1082. errno = 0;
  1083. return read_byte(file);
  1084. }
  1085. # endif
  1086. else
  1087. {
  1088. /* An error, it doesn't really matter what the error is but it gets
  1089. * recorded anyway.
  1090. */
  1091. if (ferror(file->file))
  1092. file->read_errno = errno;
  1093. else if (feof(file->file))
  1094. file->read_errno = 0; /* I.e. a regular EOF, no error */
  1095. else /* unexpected */
  1096. file->read_errno = EDOM;
  1097. }
  1098. /* 'TRUNCATED' is used for all cases of failure to read a byte, because of
  1099. * the way libpng works a byte read is never attempted unless the byte is
  1100. * expected to be there, so EOF should not occur.
  1101. */
  1102. file->status_code |= TRUNCATED;
  1103. return EOF;
  1104. }
  1105. static png_byte
  1106. reread_byte(struct file *file)
  1107. /* Read a byte when an error is not expected to happen because the byte has
  1108. * been read before without error.
  1109. */
  1110. {
  1111. int ch = getc(file->file);
  1112. if (errno != 0)
  1113. file->read_errno = errno;
  1114. if (ch < 0 || ch > 255)
  1115. stop(file, UNEXPECTED_ERROR_CODE, "reread");
  1116. return (png_byte)ch;
  1117. }
  1118. static png_uint_32
  1119. reread_4(struct file *file)
  1120. /* The same but for a four byte quantity */
  1121. {
  1122. png_uint_32 result = 0;
  1123. int i = 0;
  1124. while (++i <= 4)
  1125. result = (result << 8) + reread_byte(file);
  1126. return result;
  1127. }
  1128. static void
  1129. skip_12(struct file *file)
  1130. /* Skip exactly 12 bytes in the input stream - used to skip a CRC and chunk
  1131. * header that has been read before.
  1132. */
  1133. {
  1134. /* Since the chunks were read before this shouldn't fail: */
  1135. if (fseek(file->file, 12, SEEK_CUR) != 0)
  1136. {
  1137. if (errno != 0)
  1138. file->read_errno = errno;
  1139. stop(file, UNEXPECTED_ERROR_CODE, "reskip");
  1140. }
  1141. }
  1142. static void
  1143. write_byte(struct file *file, int b)
  1144. /* Write one byte to the output - this causes a fatal error if the write
  1145. * fails and the read of this PNG file immediately terminates. Just
  1146. * increments the write count if there is no output file.
  1147. */
  1148. {
  1149. if (file->out != NULL)
  1150. {
  1151. if (putc(b, file->out) != b)
  1152. {
  1153. file->write_errno = errno;
  1154. file->status_code |= WRITE_ERROR;
  1155. stop(file, WRITE_ERROR_CODE, "write byte");
  1156. }
  1157. }
  1158. ++(file->write_count);
  1159. }
  1160. /* Derivatives of the read/write functions. */
  1161. static unsigned int
  1162. read_4(struct file *file, png_uint_32 *pu)
  1163. /* Read four bytes, returns the number of bytes read successfully and, if all
  1164. * four bytes are read, assigns the result to *pu.
  1165. */
  1166. {
  1167. unsigned int i = 0;
  1168. png_uint_32 val = 0;
  1169. do
  1170. {
  1171. int ch = read_byte(file);
  1172. if (ch == EOF)
  1173. return i;
  1174. val = (val << 8) + ch;
  1175. } while (++i < 4);
  1176. *pu = val;
  1177. return i;
  1178. }
  1179. /* CRC handling - read but calculate the CRC while doing so. */
  1180. static int
  1181. crc_read_many(struct file *file, png_uint_32 length)
  1182. /* Reads 'length' bytes and updates the CRC, returns true on success, false
  1183. * if the input is truncated.
  1184. */
  1185. {
  1186. if (length > 0)
  1187. {
  1188. png_uint_32 crc = file->crc;
  1189. do
  1190. {
  1191. int ch = read_byte(file);
  1192. if (ch == EOF)
  1193. return 0; /* Truncated */
  1194. crc = crc_one_byte(crc, ch);
  1195. }
  1196. while (--length > 0);
  1197. file->crc = crc;
  1198. }
  1199. return 1; /* OK */
  1200. }
  1201. static int
  1202. calc_image_size(struct file *file)
  1203. /* Fill in the image_bytes field given the IHDR information, calls stop on
  1204. * error.
  1205. */
  1206. {
  1207. png_uint_16 pd = file->bit_depth;
  1208. switch (file->color_type)
  1209. {
  1210. default:
  1211. stop_invalid(file, "IHDR: colour type");
  1212. invalid_bit_depth:
  1213. stop_invalid(file, "IHDR: bit depth");
  1214. case 0: /* g */
  1215. if (pd != 1 && pd != 2 && pd != 4 && pd != 8 && pd != 16)
  1216. goto invalid_bit_depth;
  1217. break;
  1218. case 3:
  1219. if (pd != 1 && pd != 2 && pd != 4 && pd != 8)
  1220. goto invalid_bit_depth;
  1221. break;
  1222. case 2: /* rgb */
  1223. if (pd != 8 && pd != 16)
  1224. goto invalid_bit_depth;
  1225. pd = (png_uint_16)(pd * 3);
  1226. break;
  1227. case 4: /* ga */
  1228. if (pd != 8 && pd != 16)
  1229. goto invalid_bit_depth;
  1230. pd = (png_uint_16)(pd * 2);
  1231. break;
  1232. case 6: /* rgba */
  1233. if (pd != 8 && pd != 16)
  1234. goto invalid_bit_depth;
  1235. pd = (png_uint_16)(pd * 4);
  1236. break;
  1237. }
  1238. if (file->width < 1 || file->width > 0x7fffffff)
  1239. stop_invalid(file, "IHDR: width");
  1240. else if (file->height < 1 || file->height > 0x7fffffff)
  1241. stop_invalid(file, "IHDR: height");
  1242. else if (file->compression_method != 0)
  1243. stop_invalid(file, "IHDR: compression method");
  1244. else if (file->filter_method != 0)
  1245. stop_invalid(file, "IHDR: filter method");
  1246. else switch (file->interlace_method)
  1247. {
  1248. case PNG_INTERLACE_ADAM7:
  1249. /* Interlacing makes the image larger because of the replication of
  1250. * both the filter byte and the padding to a byte boundary.
  1251. */
  1252. {
  1253. int pass;
  1254. int image_digits = 0;
  1255. udigit row_width[2], row_bytes[3];
  1256. for (pass=0; pass<=6; ++pass)
  1257. {
  1258. png_uint_32 pw = PNG_PASS_COLS(file->width, pass);
  1259. if (pw > 0)
  1260. {
  1261. int digits;
  1262. /* calculate 1+((pw*pd+7)>>3) in row_bytes */
  1263. digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
  1264. row_width, uarb_set(row_width, pw), pd);
  1265. digits = uarb_shift(row_bytes, digits, 3);
  1266. digits = uarb_inc(row_bytes, digits, 1);
  1267. /* Add row_bytes * pass-height to the file image_bytes field
  1268. */
  1269. image_digits = uarb_mult32(file->image_bytes, image_digits,
  1270. row_bytes, digits,
  1271. PNG_PASS_ROWS(file->height, pass));
  1272. }
  1273. }
  1274. file->image_digits = image_digits;
  1275. }
  1276. break;
  1277. case PNG_INTERLACE_NONE:
  1278. {
  1279. int digits;
  1280. udigit row_width[2], row_bytes[3];
  1281. /* As above, but use image_width in place of the pass width: */
  1282. digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
  1283. row_width, uarb_set(row_width, file->width), pd);
  1284. digits = uarb_shift(row_bytes, digits, 3);
  1285. digits = uarb_inc(row_bytes, digits, 1);
  1286. /* Set row_bytes * image-height to the file image_bytes field */
  1287. file->image_digits = uarb_mult32(file->image_bytes, 0,
  1288. row_bytes, digits, file->height);
  1289. }
  1290. break;
  1291. default:
  1292. stop_invalid(file, "IHDR: interlace method");
  1293. }
  1294. assert(file->image_digits >= 1 && file->image_digits <= 5);
  1295. return 1;
  1296. }
  1297. /* PER-CHUNK CONTROL STRUCTURE
  1298. * This structure is instantiated for each chunk, except for the IDAT chunks
  1299. * where one chunk control structure is used for the whole of a single stream of
  1300. * IDAT chunks (see the IDAT control structure below).
  1301. */
  1302. struct chunk
  1303. {
  1304. /* ANCESTORS */
  1305. struct file * file;
  1306. struct global * global;
  1307. /* PUBLIC IDAT INFORMATION: SET BY THE ZLIB CODE */
  1308. udigit uncompressed_bytes[5];
  1309. int uncompressed_digits;
  1310. udigit compressed_bytes[5];
  1311. int compressed_digits;
  1312. /* PUBLIC PER-CHUNK INFORMATION: USED BY CHUNK READ CODE */
  1313. /* This information is filled in by chunk_init from the data in the file
  1314. * control structure, but chunk_length may be changed later.
  1315. */
  1316. fpos_t chunk_data_pos; /* Position of first byte of chunk data */
  1317. png_uint_32 chunk_length; /* From header (or modified below) */
  1318. png_uint_32 chunk_type; /* From header */
  1319. /* PUBLIC PER-CHUNK INFORMATION: FOR THE CHUNK WRITE CODE */
  1320. png_uint_32 write_crc; /* Output CRC (may differ from read_crc) */
  1321. png_uint_32 rewrite_offset; /* Count of bytes before rewrite. */
  1322. int rewrite_length; /* Number of bytes left to change */
  1323. png_byte rewrite_buffer[2]; /* Buffer of new byte values */
  1324. };
  1325. static void
  1326. chunk_message(struct chunk *chunk, const char *message)
  1327. {
  1328. type_message(chunk->file, chunk->chunk_type, message);
  1329. }
  1330. static void
  1331. chunk_end(struct chunk **chunk_var)
  1332. {
  1333. struct chunk *chunk = *chunk_var;
  1334. *chunk_var = NULL;
  1335. CLEAR(*chunk);
  1336. }
  1337. static void
  1338. chunk_init(struct chunk * const chunk, struct file * const file)
  1339. /* When a chunk is initialized the file length/type/pos are copied into the
  1340. * corresponding chunk fields and the new chunk is registered in the file
  1341. * structure. There can only be one chunk at a time.
  1342. *
  1343. * NOTE: this routine must onely be called from the file alloc routine!
  1344. */
  1345. {
  1346. assert(file->chunk == NULL);
  1347. CLEAR(*chunk);
  1348. chunk->file = file;
  1349. chunk->global = file->global;
  1350. chunk->chunk_data_pos = file->data_pos;
  1351. chunk->chunk_length = file->length;
  1352. chunk->chunk_type = file->type;
  1353. /* Compresssed/uncompressed size information (from the zlib control structure
  1354. * that is used to check the compressed data in a chunk.)
  1355. */
  1356. chunk->uncompressed_digits = 0;
  1357. chunk->compressed_digits = 0;
  1358. file->chunk = chunk;
  1359. }
  1360. static png_uint_32
  1361. current_type(struct file *file, int code)
  1362. /* Guess the actual chunk type that causes a stop() */
  1363. {
  1364. /* This may return png_IDAT for errors detected (late) in the header; that
  1365. * includes any inter-chunk consistency check that libpng performs. Assume
  1366. * that if the chunk_type is png_IDAT and the file write count is 8 this is
  1367. * what is happening.
  1368. */
  1369. if (file->chunk != NULL)
  1370. {
  1371. png_uint_32 type = file->chunk->chunk_type;
  1372. /* This is probably wrong for the excess IDATs case, because then libpng
  1373. * whines about too many of them (apparently in some cases erroneously)
  1374. * when the header is read.
  1375. */
  1376. if (code <= LIBPNG_ERROR_CODE && type == png_IDAT &&
  1377. file->write_count == 8)
  1378. type = 0; /* magic */
  1379. return type;
  1380. }
  1381. else
  1382. return file->type;
  1383. }
  1384. static void
  1385. setpos(struct chunk *chunk)
  1386. /* Reset the position to 'chunk_data_pos' - the start of the data for this
  1387. * chunk. As a side effect the read_count in the file is reset to 8, just
  1388. * after the length/type header.
  1389. */
  1390. {
  1391. chunk->file->read_count = 8;
  1392. file_setpos(chunk->file, &chunk->chunk_data_pos);
  1393. }
  1394. /* Specific chunk handling - called for each chunk header, all special chunk
  1395. * processing is initiated in these functions.
  1396. */
  1397. /* The next functions handle special processing for those chunks with LZ data,
  1398. * the data is identified and checked for validity. If there are problems which
  1399. * cannot be corrected the routines return false, otherwise true (although
  1400. * modification to the zlib header may be required.)
  1401. *
  1402. * The compressed data is in zlib format (RFC1950) and consequently has a
  1403. * minimum length of 7 bytes.
  1404. */
  1405. static int zlib_check(struct file *file, png_uint_32 offset);
  1406. static int
  1407. process_zTXt_iCCP(struct file *file)
  1408. /* zTXt and iCCP have exactly the same form - keyword, null, compression
  1409. * method then compressed data.
  1410. */
  1411. {
  1412. struct chunk *chunk = file->chunk;
  1413. png_uint_32 length;
  1414. png_uint_32 index = 0;
  1415. assert(chunk != NULL && file->idat == NULL);
  1416. length = chunk->chunk_length;
  1417. setpos(chunk);
  1418. while (length >= 9)
  1419. {
  1420. --length;
  1421. ++index;
  1422. if (reread_byte(file) == 0) /* keyword null terminator */
  1423. {
  1424. --length;
  1425. ++index;
  1426. (void)reread_byte(file); /* compression method */
  1427. return zlib_check(file, index);
  1428. }
  1429. }
  1430. chunk_message(chunk, "too short");
  1431. return 0; /* skip */
  1432. }
  1433. static int
  1434. process_iTXt(struct file *file)
  1435. {
  1436. /* Like zTXt but more fields. */
  1437. struct chunk *chunk = file->chunk;
  1438. png_uint_32 length;
  1439. png_uint_32 index = 0;
  1440. assert(chunk != NULL && file->idat == NULL);
  1441. length = chunk->chunk_length;
  1442. setpos(chunk);
  1443. while (length >= 5)
  1444. {
  1445. --length;
  1446. ++index;
  1447. if (reread_byte(file) == 0) /* keyword null terminator */
  1448. {
  1449. --length;
  1450. ++index;
  1451. if (reread_byte(file) == 0) /* uncompressed text */
  1452. return 1; /* nothing to check */
  1453. --length;
  1454. ++index;
  1455. (void)reread_byte(file); /* compression method */
  1456. /* Skip the language tag (null terminated). */
  1457. while (length >= 9)
  1458. {
  1459. --length;
  1460. ++index;
  1461. if (reread_byte(file) == 0) /* terminator */
  1462. {
  1463. /* Skip the translated keyword */
  1464. while (length >= 8)
  1465. {
  1466. --length;
  1467. ++index;
  1468. if (reread_byte(file) == 0) /* terminator */
  1469. return zlib_check(file, index);
  1470. }
  1471. }
  1472. }
  1473. /* Ran out of bytes in the compressed case. */
  1474. break;
  1475. }
  1476. }
  1477. log_error(file, INVALID_ERROR_CODE, "iTXt chunk length");
  1478. return 0; /* skip */
  1479. }
  1480. /* IDAT READ/WRITE CONTROL STRUCTURE */
  1481. struct IDAT
  1482. {
  1483. /* ANCESTORS */
  1484. struct file * file;
  1485. struct global * global;
  1486. /* PROTECTED IDAT INFORMATION: SET BY THE IDAT READ CODE */
  1487. struct IDAT_list *idat_list_head; /* START of the list of IDAT information */
  1488. struct IDAT_list *idat_list_tail; /* *END* of the list of IDAT information */
  1489. /* PROTECTED IDAT INFORMATION: USED BY THE IDAT WRITE CODE */
  1490. struct IDAT_list *idat_cur; /* Current list entry */
  1491. unsigned int idat_count; /* And the *current* index into the list */
  1492. png_uint_32 idat_index; /* Index of *next* input byte to write */
  1493. png_uint_32 idat_length; /* Cache of current chunk length */
  1494. };
  1495. /* NOTE: there is currently no IDAT_reset, so a stream cannot contain more than
  1496. * one IDAT sequence (i.e. MNG is not supported).
  1497. */
  1498. static void
  1499. IDAT_end(struct IDAT **idat_var)
  1500. {
  1501. struct IDAT *idat = *idat_var;
  1502. struct file *file = idat->file;
  1503. *idat_var = NULL;
  1504. CLEAR(*idat);
  1505. assert(file->chunk != NULL);
  1506. chunk_end(&file->chunk);
  1507. /* Regardless of why the IDAT was killed set the state back to CHUNKS (it may
  1508. * already be CHUNKS because the state isn't changed until process_IDAT
  1509. * returns; a stop will cause IDAT_end to be entered in state CHUNKS!)
  1510. */
  1511. file->state = STATE_CHUNKS;
  1512. }
  1513. static void
  1514. IDAT_init(struct IDAT * const idat, struct file * const file)
  1515. /* When the chunk is png_IDAT instantiate an IDAT control structure in place
  1516. * of a chunk control structure. The IDAT will instantiate a chunk control
  1517. * structure using the file alloc routine.
  1518. *
  1519. * NOTE: this routine must only be called from the file alloc routine!
  1520. */
  1521. {
  1522. assert(file->chunk == NULL);
  1523. assert(file->idat == NULL);
  1524. CLEAR(*idat);
  1525. idat->file = file;
  1526. idat->global = file->global;
  1527. /* Initialize the tail to the pre-allocated buffer and set the count to 0
  1528. * (empty.)
  1529. */
  1530. idat->global->idat_cache.count = 0;
  1531. idat->idat_list_head = idat->idat_list_tail = &idat->global->idat_cache;
  1532. /* Now the chunk. The allocator calls the initializer of the new chunk and
  1533. * stores the result in file->chunk:
  1534. */
  1535. file->alloc(file, 0/*chunk*/);
  1536. assert(file->chunk != NULL);
  1537. /* And store this for cleanup (and to check for double alloc or failure to
  1538. * free.)
  1539. */
  1540. file->idat = idat;
  1541. }
  1542. static png_uint_32
  1543. rechunk_length(struct IDAT *idat)
  1544. /* Return the length for the next IDAT chunk, taking into account
  1545. * rechunking.
  1546. */
  1547. {
  1548. png_uint_32 len = idat->global->idat_max;
  1549. if (len == 0) /* use original chunk lengths */
  1550. {
  1551. const struct IDAT_list *cur;
  1552. unsigned int count;
  1553. if (idat->idat_index == 0) /* at the new chunk (first time) */
  1554. return idat->idat_length; /* use the cache */
  1555. /* Otherwise rechunk_length is called at the end of a chunk for the length
  1556. * of the next one.
  1557. */
  1558. cur = idat->idat_cur;
  1559. count = idat->idat_count;
  1560. assert(idat->idat_index == idat->idat_length &&
  1561. idat->idat_length == cur->lengths[count]);
  1562. /* Return length of the *next* chunk */
  1563. if (++count < cur->count)
  1564. return cur->lengths[count];
  1565. /* End of this list */
  1566. assert(cur != idat->idat_list_tail);
  1567. cur = cur->next;
  1568. assert(cur != NULL && cur->count > 0);
  1569. return cur->lengths[0];
  1570. }
  1571. else /* rechunking */
  1572. {
  1573. /* The chunk size is the lesser of file->idat_max and the number
  1574. * of remaining bytes.
  1575. */
  1576. png_uint_32 have = idat->idat_length - idat->idat_index;
  1577. if (len > have)
  1578. {
  1579. struct IDAT_list *cur = idat->idat_cur;
  1580. unsigned int j = idat->idat_count+1; /* the next IDAT in the list */
  1581. do
  1582. {
  1583. /* Add up the remaining bytes. This can't overflow because the
  1584. * individual lengths are always <= 0x7fffffff, so when we add two
  1585. * of them overflow is not possible.
  1586. */
  1587. assert(cur != NULL);
  1588. for (;;)
  1589. {
  1590. /* NOTE: IDAT_list::count here, not IDAT_list::length */
  1591. for (; j < cur->count; ++j)
  1592. {
  1593. have += cur->lengths[j];
  1594. if (len <= have)
  1595. return len;
  1596. }
  1597. /* If this was the end return the count of the available bytes */
  1598. if (cur == idat->idat_list_tail)
  1599. return have;
  1600. cur = cur->next;
  1601. j = 0;
  1602. }
  1603. }
  1604. while (len > have);
  1605. }
  1606. return len;
  1607. }
  1608. }
  1609. static int
  1610. process_IDAT(struct file *file)
  1611. /* Process the IDAT stream, this is the more complex than the preceding
  1612. * cases because the compressed data is spread across multiple IDAT chunks
  1613. * (typically). Rechunking of the data is not handled here; all this
  1614. * function does is establish whether the zlib header needs to be modified.
  1615. *
  1616. * Initially the function returns false, indicating that the chunk should not
  1617. * be written. It does this until the last IDAT chunk is passed in, then it
  1618. * checks the zlib data and returns true.
  1619. *
  1620. * It does not return false on a fatal error; it calls stop instead.
  1621. *
  1622. * The caller must have an instantiated (IDAT) control structure and it must
  1623. * have extent over the whole read of the IDAT stream. For a PNG this means
  1624. * the whole PNG read, for MNG it could have lesser extent.
  1625. */
  1626. {
  1627. struct IDAT_list *list;
  1628. assert(file->idat != NULL && file->chunk != NULL);
  1629. /* We need to first check the entire sequence of IDAT chunks to ensure the
  1630. * stream is in sync. Do this by building a list of all the chunks and
  1631. * recording the length of each because the length may have been fixed up by
  1632. * sync_stream below.
  1633. *
  1634. * At the end of the list of chunks, where the type of the next chunk is not
  1635. * png_IDAT, process the whole stream using the list data to check validity
  1636. * then return control to the start and rewrite everything.
  1637. */
  1638. list = file->idat->idat_list_tail;
  1639. if (list->count == list->length)
  1640. {
  1641. list = IDAT_list_extend(list);
  1642. if (list == NULL)
  1643. stop(file, READ_ERROR_CODE, "out of memory");
  1644. /* Move to the next block */
  1645. list->count = 0;
  1646. file->idat->idat_list_tail = list;
  1647. }
  1648. /* And fill in the next IDAT information buffer. */
  1649. list->lengths[(list->count)++] = file->chunk->chunk_length;
  1650. /* The type of the next chunk was recorded in the file control structure by
  1651. * the caller, if this is png_IDAT return 'skip' to the caller.
  1652. */
  1653. if (file->type == png_IDAT)
  1654. return 0; /* skip this for the moment */
  1655. /* This is the final IDAT chunk, so run the tests to check for the too far
  1656. * back error and possibly optimize the window bits. This means going back
  1657. * to the start of the first chunk data, which is stored in the original
  1658. * chunk allocation.
  1659. */
  1660. setpos(file->chunk);
  1661. if (zlib_check(file, 0))
  1662. {
  1663. struct IDAT *idat;
  1664. int cmp;
  1665. /* The IDAT stream was successfully uncompressed; see whether it
  1666. * contained the correct number of bytes of image data.
  1667. */
  1668. cmp = uarb_cmp(file->image_bytes, file->image_digits,
  1669. file->chunk->uncompressed_bytes, file->chunk->uncompressed_digits);
  1670. if (cmp < 0)
  1671. type_message(file, png_IDAT, "extra uncompressed data");
  1672. else if (cmp > 0)
  1673. stop(file, LIBPNG_ERROR_CODE, "IDAT: uncompressed data too small");
  1674. /* Return the stream to the start of the first IDAT chunk; the length
  1675. * is set in the write case below but the input chunk variables must be
  1676. * set (once) here:
  1677. */
  1678. setpos(file->chunk);
  1679. idat = file->idat;
  1680. idat->idat_cur = idat->idat_list_head;
  1681. idat->idat_length = idat->idat_cur->lengths[0];
  1682. idat->idat_count = 0; /* Count of chunks read in current list */
  1683. idat->idat_index = 0; /* Index into chunk data */
  1684. /* Update the chunk length to the correct value for the IDAT chunk: */
  1685. file->chunk->chunk_length = rechunk_length(idat);
  1686. /* Change the state to writing IDAT chunks */
  1687. file->state = STATE_IDAT;
  1688. return 1;
  1689. }
  1690. else /* Failure to decompress the IDAT stream; give up. */
  1691. stop(file, ZLIB_ERROR_CODE, "could not uncompress IDAT");
  1692. }
  1693. /* ZLIB CONTROL STRUCTURE */
  1694. struct zlib
  1695. {
  1696. /* ANCESTORS */
  1697. struct IDAT * idat; /* NOTE: May be NULL */
  1698. struct chunk * chunk;
  1699. struct file * file;
  1700. struct global *global;
  1701. /* GLOBAL ZLIB INFORMATION: SET BY THE CALLER */
  1702. png_uint_32 rewrite_offset;
  1703. /* GLOBAL ZLIB INFORMATION: SET BY THE ZLIB READ CODE */
  1704. udigit compressed_bytes[5];
  1705. int compressed_digits;
  1706. udigit uncompressed_bytes[5];
  1707. int uncompressed_digits;
  1708. int file_bits; /* window bits from the file */
  1709. int ok_bits; /* Set <16 on a successful read */
  1710. int cksum; /* Set on a checksum error */
  1711. /* PROTECTED ZLIB INFORMATION: USED BY THE ZLIB ROUTINES */
  1712. z_stream z;
  1713. png_uint_32 extra_bytes; /* Count of extra compressed bytes */
  1714. int state;
  1715. int rc; /* Last return code */
  1716. int window_bits; /* 0 if no change */
  1717. png_byte header[2];
  1718. };
  1719. static const char *
  1720. zlib_flevel(struct zlib *zlib)
  1721. {
  1722. switch (zlib->header[1] >> 6)
  1723. {
  1724. case 0: return "supfast";
  1725. case 1: return "stdfast";
  1726. case 2: return "default";
  1727. case 3: return "maximum";
  1728. default: assert(UNREACHED);
  1729. }
  1730. return "COMPILER BUG";
  1731. }
  1732. static const char *
  1733. zlib_rc(struct zlib *zlib)
  1734. /* Return a string for the zlib return code */
  1735. {
  1736. switch (zlib->rc)
  1737. {
  1738. case Z_OK: return "Z_OK";
  1739. case Z_STREAM_END: return "Z_STREAM_END";
  1740. case Z_NEED_DICT: return "Z_NEED_DICT";
  1741. case Z_ERRNO: return "Z_ERRNO";
  1742. case Z_STREAM_ERROR: return "Z_STREAM_ERROR";
  1743. case Z_DATA_ERROR: return "Z_DATA_ERROR";
  1744. case Z_MEM_ERROR: return "Z_MEM_ERROR";
  1745. case Z_BUF_ERROR: return "Z_BUF_ERROR";
  1746. case Z_VERSION_ERROR: return "Z_VERSION_ERROR";
  1747. default: return "Z_*INVALID_RC*";
  1748. }
  1749. }
  1750. static void
  1751. zlib_message(struct zlib *zlib, int unexpected)
  1752. /* Output a message given a zlib rc */
  1753. {
  1754. if (zlib->global->errors)
  1755. {
  1756. const char *reason = zlib->z.msg;
  1757. if (reason == NULL)
  1758. reason = "[no message]";
  1759. fputs(zlib->file->file_name, stderr);
  1760. type_sep(stderr);
  1761. type_name(zlib->chunk->chunk_type, stderr);
  1762. fprintf(stderr, ": %szlib error: %d (%s) (%s)\n",
  1763. unexpected ? "unexpected " : "", zlib->rc, zlib_rc(zlib), reason);
  1764. }
  1765. }
  1766. static void
  1767. zlib_end(struct zlib *zlib)
  1768. {
  1769. /* Output the summary line now; this ensures a summary line always gets
  1770. * output regardless of the manner of exit.
  1771. */
  1772. if (!zlib->global->quiet)
  1773. {
  1774. if (zlib->ok_bits < 16) /* stream was read ok */
  1775. {
  1776. const char *reason;
  1777. if (zlib->cksum)
  1778. reason = "CHK"; /* checksum error */
  1779. else if (zlib->ok_bits > zlib->file_bits)
  1780. reason = "TFB"; /* fixing a too-far-back error */
  1781. else if (zlib->ok_bits == zlib->file_bits)
  1782. reason = "OK ";
  1783. else
  1784. reason = "OPT"; /* optimizing window bits */
  1785. /* SUMMARY FORMAT (for a successful zlib inflate):
  1786. *
  1787. * IDAT reason flevel file-bits ok-bits compressed uncompressed file
  1788. */
  1789. type_name(zlib->chunk->chunk_type, stdout);
  1790. printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits,
  1791. zlib->ok_bits);
  1792. uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
  1793. putc(' ', stdout);
  1794. uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits,
  1795. stdout);
  1796. putc(' ', stdout);
  1797. fputs(zlib->file->file_name, stdout);
  1798. putc('\n', stdout);
  1799. }
  1800. else
  1801. {
  1802. /* This is a zlib read error; the chunk will be skipped. For an IDAT
  1803. * stream this will also cause a fatal read error (via stop()).
  1804. *
  1805. * SUMMARY FORMAT:
  1806. *
  1807. * IDAT SKP flevel file-bits z-rc compressed message file
  1808. *
  1809. * z-rc is the zlib failure code; message is the error message with
  1810. * spaces replaced by '-'. The compressed byte count indicates where
  1811. * in the zlib stream the error occured.
  1812. */
  1813. type_name(zlib->chunk->chunk_type, stdout);
  1814. printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits,
  1815. zlib_rc(zlib));
  1816. uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
  1817. putc(' ', stdout);
  1818. emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout);
  1819. putc(' ', stdout);
  1820. fputs(zlib->file->file_name, stdout);
  1821. putc('\n', stdout);
  1822. }
  1823. }
  1824. if (zlib->state >= 0)
  1825. {
  1826. zlib->rc = inflateEnd(&zlib->z);
  1827. if (zlib->rc != Z_OK)
  1828. zlib_message(zlib, 1/*unexpected*/);
  1829. }
  1830. CLEAR(*zlib);
  1831. }
  1832. static int
  1833. zlib_reset(struct zlib *zlib, int window_bits)
  1834. /* Reinitializes a zlib with a different window_bits */
  1835. {
  1836. assert(zlib->state >= 0); /* initialized by zlib_init */
  1837. zlib->z.next_in = Z_NULL;
  1838. zlib->z.avail_in = 0;
  1839. zlib->z.next_out = Z_NULL;
  1840. zlib->z.avail_out = 0;
  1841. zlib->window_bits = window_bits;
  1842. zlib->compressed_digits = 0;
  1843. zlib->uncompressed_digits = 0;
  1844. zlib->state = 0; /* initialized, once */
  1845. zlib->rc = inflateReset2(&zlib->z, 0);
  1846. if (zlib->rc != Z_OK)
  1847. {
  1848. zlib_message(zlib, 1/*unexpected*/);
  1849. return 0;
  1850. }
  1851. return 1;
  1852. }
  1853. static int
  1854. zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
  1855. int window_bits, png_uint_32 offset)
  1856. /* Initialize a zlib_control; the result is true/false */
  1857. {
  1858. CLEAR(*zlib);
  1859. zlib->idat = idat;
  1860. zlib->chunk = chunk;
  1861. zlib->file = chunk->file;
  1862. zlib->global = chunk->global;
  1863. zlib->rewrite_offset = offset; /* never changed for this zlib */
  1864. /* *_out does not need to be set: */
  1865. zlib->z.next_in = Z_NULL;
  1866. zlib->z.avail_in = 0;
  1867. zlib->z.zalloc = Z_NULL;
  1868. zlib->z.zfree = Z_NULL;
  1869. zlib->z.opaque = Z_NULL;
  1870. zlib->state = -1;
  1871. zlib->window_bits = window_bits;
  1872. zlib->compressed_digits = 0;
  1873. zlib->uncompressed_digits = 0;
  1874. /* These values are sticky across reset (in addition to the stuff in the
  1875. * first block, which is actually constant.)
  1876. */
  1877. zlib->file_bits = 16;
  1878. zlib->ok_bits = 16; /* unset */
  1879. zlib->cksum = 0; /* set when a checksum error is detected */
  1880. /* '0' means use the header; inflateInit2 should always succeed because it
  1881. * does nothing apart from allocating the internal zstate.
  1882. */
  1883. zlib->rc = inflateInit2(&zlib->z, 0);
  1884. if (zlib->rc != Z_OK)
  1885. {
  1886. zlib_message(zlib, 1/*unexpected*/);
  1887. return 0;
  1888. }
  1889. else
  1890. {
  1891. zlib->state = 0; /* initialized */
  1892. return 1;
  1893. }
  1894. }
  1895. static int
  1896. max_window_bits(uarbc size, int ndigits)
  1897. /* Return the zlib stream window bits required for data of the given size. */
  1898. {
  1899. png_uint_16 cb;
  1900. if (ndigits > 1)
  1901. return 15;
  1902. cb = size[0];
  1903. if (cb > 16384) return 15;
  1904. if (cb > 8192) return 14;
  1905. if (cb > 4096) return 13;
  1906. if (cb > 2048) return 12;
  1907. if (cb > 1024) return 11;
  1908. if (cb > 512) return 10;
  1909. if (cb > 256) return 9;
  1910. return 8;
  1911. }
  1912. static int
  1913. zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
  1914. /* Read nbytes compressed bytes; the stream will be initialized if required.
  1915. * Bytes are always being reread and errors are fatal. The return code is as
  1916. * follows:
  1917. *
  1918. * -1: saw the "too far back" error
  1919. * 0: ok, keep going
  1920. * 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
  1921. * 2: a zlib error that cannot be corrected (error message already
  1922. * output if required.)
  1923. */
  1924. # define ZLIB_TOO_FAR_BACK (-1)
  1925. # define ZLIB_OK 0
  1926. # define ZLIB_STREAM_END 1
  1927. # define ZLIB_FATAL 2
  1928. {
  1929. int state = zlib->state;
  1930. int endrc = ZLIB_OK;
  1931. png_uint_32 in_bytes = 0;
  1932. struct file *file = zlib->file;
  1933. assert(state >= 0);
  1934. while (in_bytes < nbytes && endrc == ZLIB_OK)
  1935. {
  1936. png_uint_32 out_bytes;
  1937. int flush;
  1938. png_byte bIn = reread_byte(file);
  1939. png_byte bOut;
  1940. switch (state)
  1941. {
  1942. case 0: /* first header byte */
  1943. {
  1944. int file_bits = 8+(bIn >> 4);
  1945. int new_bits = zlib->window_bits;
  1946. zlib->file_bits = file_bits;
  1947. /* Check against the existing value - it may not need to be
  1948. * changed.
  1949. */
  1950. if (new_bits == 0) /* no change */
  1951. zlib->window_bits = file_bits;
  1952. else if (new_bits != file_bits) /* rewrite required */
  1953. bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
  1954. }
  1955. zlib->header[0] = bIn;
  1956. zlib->state = state = 1;
  1957. break;
  1958. case 1: /* second header byte */
  1959. {
  1960. int b2 = bIn & 0xe0; /* top 3 bits */
  1961. /* The checksum calculation, on the first 11 bits: */
  1962. b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
  1963. /* Update the checksum byte if required: */
  1964. if (bIn != b2)
  1965. {
  1966. /* If the first byte wasn't changed this indicates an error in
  1967. * the checksum calculation; signal this by setting file_bits
  1968. * (not window_bits) to 0.
  1969. */
  1970. if (zlib->file_bits == zlib->window_bits)
  1971. zlib->cksum = 1;
  1972. bIn = (png_byte)b2;
  1973. }
  1974. }
  1975. zlib->header[1] = bIn;
  1976. zlib->state = state = 2;
  1977. break;
  1978. default: /* After the header bytes */
  1979. break;
  1980. }
  1981. /* For some streams, perhaps only those compressed with 'superfast
  1982. * compression' (which results in a lot of copying) Z_BUF_ERROR can happen
  1983. * immediately after all output has been flushed on the next input byte.
  1984. * This is handled below when Z_BUF_ERROR is detected by adding an output
  1985. * byte.
  1986. */
  1987. zlib->z.next_in = &bIn;
  1988. zlib->z.avail_in = 1;
  1989. zlib->z.next_out = &bOut;
  1990. zlib->z.avail_out = 0; /* Initially */
  1991. /* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
  1992. * byte without confusing what is going on with output.
  1993. */
  1994. flush = Z_NO_FLUSH;
  1995. out_bytes = 0;
  1996. /* NOTE: expression 3 is only evaluted on 'continue', because of the
  1997. * 'break' at the end of this loop below.
  1998. */
  1999. for (;endrc == ZLIB_OK;
  2000. flush = Z_SYNC_FLUSH,
  2001. zlib->z.next_out = &bOut,
  2002. zlib->z.avail_out = 1,
  2003. ++out_bytes)
  2004. {
  2005. zlib->rc = inflate(&zlib->z, flush);
  2006. out_bytes -= zlib->z.avail_out;
  2007. switch (zlib->rc)
  2008. {
  2009. case Z_BUF_ERROR:
  2010. if (zlib->z.avail_out == 0)
  2011. continue; /* Try another output byte. */
  2012. if (zlib->z.avail_in == 0)
  2013. break; /* Try another input byte */
  2014. /* Both avail_out and avail_in are 1 yet zlib returned a code
  2015. * indicating no progress was possible. This is unexpected.
  2016. */
  2017. zlib_message(zlib, 1/*unexpected*/);
  2018. endrc = ZLIB_FATAL; /* stop processing */
  2019. break;
  2020. case Z_OK:
  2021. /* Zlib is supposed to have made progress: */
  2022. assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
  2023. continue;
  2024. case Z_STREAM_END:
  2025. /* This is the successful end. */
  2026. zlib->state = 3; /* end of stream */
  2027. endrc = ZLIB_STREAM_END;
  2028. break;
  2029. case Z_NEED_DICT:
  2030. zlib_message(zlib, 0/*stream error*/);
  2031. endrc = ZLIB_FATAL;
  2032. break;
  2033. case Z_DATA_ERROR:
  2034. /* The too far back error can be corrected, others cannot: */
  2035. if (zlib->z.msg != NULL &&
  2036. strcmp(zlib->z.msg, "invalid distance too far back") == 0)
  2037. {
  2038. endrc = ZLIB_TOO_FAR_BACK;
  2039. break;
  2040. }
  2041. /* FALL THROUGH */
  2042. default:
  2043. zlib_message(zlib, 0/*stream error*/);
  2044. endrc = ZLIB_FATAL;
  2045. break;
  2046. } /* switch (inflate rc) */
  2047. /* Control gets here when further output is not possible; endrc may
  2048. * still be ZLIB_OK if more input is required.
  2049. */
  2050. break;
  2051. } /* for (output bytes) */
  2052. /* Keep a running count of output byte produced: */
  2053. zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
  2054. zlib->uncompressed_digits, out_bytes);
  2055. /* Keep going, the loop will terminate when endrc is no longer set to
  2056. * ZLIB_OK or all the input bytes have been consumed; meanwhile keep
  2057. * adding input bytes.
  2058. */
  2059. assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
  2060. in_bytes += 1 - zlib->z.avail_in;
  2061. } /* while (input bytes) */
  2062. assert(in_bytes == nbytes || endrc != ZLIB_OK);
  2063. /* Update the running total of input bytes consumed */
  2064. zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
  2065. zlib->compressed_digits, in_bytes - zlib->z.avail_in);
  2066. /* At the end of the stream update the chunk with the accumulated
  2067. * information if it is an improvement:
  2068. */
  2069. if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
  2070. {
  2071. struct chunk *chunk = zlib->chunk;
  2072. chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
  2073. zlib->uncompressed_bytes, zlib->uncompressed_digits);
  2074. chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
  2075. zlib->compressed_bytes, zlib->compressed_digits);
  2076. chunk->rewrite_buffer[0] = zlib->header[0];
  2077. chunk->rewrite_buffer[1] = zlib->header[1];
  2078. if (zlib->window_bits != zlib->file_bits || zlib->cksum)
  2079. {
  2080. /* A rewrite is required */
  2081. chunk->rewrite_offset = zlib->rewrite_offset;
  2082. chunk->rewrite_length = 2;
  2083. }
  2084. else
  2085. {
  2086. chunk->rewrite_offset = 0;
  2087. chunk->rewrite_length = 0;
  2088. }
  2089. if (in_bytes < nbytes)
  2090. chunk_message(chunk, "extra compressed data");
  2091. zlib->extra_bytes = nbytes - in_bytes;
  2092. zlib->ok_bits = zlib->window_bits;
  2093. }
  2094. return endrc;
  2095. }
  2096. static int
  2097. zlib_run(struct zlib *zlib)
  2098. /* Like zlib_advance but also handles a stream of IDAT chunks. */
  2099. {
  2100. /* The 'extra_bytes' field is set by zlib_advance if there is extra
  2101. * compressed data in the chunk it handles (if it sees Z_STREAM_END before
  2102. * all the input data has been used.) This function uses the value to update
  2103. * the correct chunk length, so the problem should only ever be detected once
  2104. * for each chunk. zlib_advance outputs the error message, though see the
  2105. * IDAT specific check below.
  2106. */
  2107. zlib->extra_bytes = 0;
  2108. if (zlib->idat != NULL)
  2109. {
  2110. struct IDAT_list *list = zlib->idat->idat_list_head;
  2111. struct IDAT_list *last = zlib->idat->idat_list_tail;
  2112. int skip = 0;
  2113. /* 'rewrite_offset' is the offset of the LZ data within the chunk, for
  2114. * IDAT it should be 0:
  2115. */
  2116. assert(zlib->rewrite_offset == 0);
  2117. /* Process each IDAT_list in turn; the caller has left the stream
  2118. * positioned at the start of the first IDAT chunk data.
  2119. */
  2120. for (;;)
  2121. {
  2122. const unsigned int count = list->count;
  2123. unsigned int i;
  2124. for (i = 0; i<count; ++i)
  2125. {
  2126. int rc;
  2127. if (skip > 0) /* Skip CRC and next IDAT header */
  2128. skip_12(zlib->file);
  2129. skip = 12; /* for the next time */
  2130. rc = zlib_advance(zlib, list->lengths[i]);
  2131. switch (rc)
  2132. {
  2133. case ZLIB_OK: /* keep going */
  2134. break;
  2135. case ZLIB_STREAM_END: /* stop */
  2136. /* There may be extra chunks; if there are and one of them is
  2137. * not zero length output the 'extra data' message. Only do
  2138. * this check if errors are being output.
  2139. */
  2140. if (zlib->global->errors && zlib->extra_bytes == 0)
  2141. {
  2142. struct IDAT_list *check = list;
  2143. int j = i+1, jcount = count;
  2144. for (;;)
  2145. {
  2146. for (; j<jcount; ++j)
  2147. if (check->lengths[j] > 0)
  2148. {
  2149. chunk_message(zlib->chunk,
  2150. "extra compressed data");
  2151. goto end_check;
  2152. }
  2153. if (check == last)
  2154. break;
  2155. check = check->next;
  2156. jcount = check->count;
  2157. j = 0;
  2158. }
  2159. }
  2160. end_check:
  2161. /* Terminate the list at the current position, reducing the
  2162. * length of the last IDAT too if required.
  2163. */
  2164. list->lengths[i] -= zlib->extra_bytes;
  2165. list->count = i+1;
  2166. zlib->idat->idat_list_tail = list;
  2167. /* FALL THROUGH */
  2168. default:
  2169. return rc;
  2170. }
  2171. }
  2172. /* At the end of the compressed data and Z_STREAM_END was not seen. */
  2173. if (list == last)
  2174. return ZLIB_OK;
  2175. list = list->next;
  2176. }
  2177. }
  2178. else
  2179. {
  2180. struct chunk *chunk = zlib->chunk;
  2181. int rc;
  2182. assert(zlib->rewrite_offset < chunk->chunk_length);
  2183. rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
  2184. /* The extra bytes in the chunk are handled now by adjusting the chunk
  2185. * length to exclude them; the zlib data is always stored at the end of
  2186. * the PNG chunk (although clearly this is not necessary.) zlib_advance
  2187. * has already output a warning message.
  2188. */
  2189. chunk->chunk_length -= zlib->extra_bytes;
  2190. return rc;
  2191. }
  2192. }
  2193. static int /* global function; not a member function */
  2194. zlib_check(struct file *file, png_uint_32 offset)
  2195. /* Check the stream of zlib compressed data in either idat (if given) or (if
  2196. * not) chunk. In fact it is zlib_run that handles the difference in reading
  2197. * a single chunk and a list of IDAT chunks.
  2198. *
  2199. * In either case the input file must be positioned at the first byte of zlib
  2200. * compressed data (the first header byte).
  2201. *
  2202. * The return value is true on success, including the case where the zlib
  2203. * header may need to be rewritten, and false on an unrecoverable error.
  2204. *
  2205. * In the case of IDAT chunks 'offset' should be 0.
  2206. */
  2207. {
  2208. fpos_t start_pos;
  2209. struct zlib zlib;
  2210. /* Record the start of the LZ data to allow a re-read. */
  2211. file_getpos(file, &start_pos);
  2212. /* First test the existing (file) window bits: */
  2213. if (zlib_init(&zlib, file->idat, file->chunk, 0/*window bits*/, offset))
  2214. {
  2215. int min_bits, max_bits, rc;
  2216. /* The first run using the existing window bits. */
  2217. rc = zlib_run(&zlib);
  2218. switch (rc)
  2219. {
  2220. case ZLIB_TOO_FAR_BACK:
  2221. /* too far back error */
  2222. file->status_code |= TOO_FAR_BACK;
  2223. min_bits = zlib.window_bits + 1;
  2224. max_bits = 15;
  2225. break;
  2226. case ZLIB_STREAM_END:
  2227. if (!zlib.global->optimize_zlib &&
  2228. zlib.window_bits == zlib.file_bits && !zlib.cksum)
  2229. {
  2230. /* The trivial case where the stream is ok and optimization was
  2231. * not requested.
  2232. */
  2233. zlib_end(&zlib);
  2234. return 1;
  2235. }
  2236. max_bits = max_window_bits(zlib.uncompressed_bytes,
  2237. zlib.uncompressed_digits);
  2238. if (zlib.ok_bits < max_bits)
  2239. max_bits = zlib.ok_bits;
  2240. min_bits = 8;
  2241. /* cksum is set if there is an error in the zlib header checksum
  2242. * calculation in the original file (and this may be the only reason
  2243. * a rewrite is required). We can't rely on the file window bits in
  2244. * this case, so do the optimization anyway.
  2245. */
  2246. if (zlib.cksum)
  2247. chunk_message(zlib.chunk, "zlib checkum");
  2248. break;
  2249. case ZLIB_OK:
  2250. /* Truncated stream; unrecoverable, gets converted to ZLIB_FATAL */
  2251. zlib.z.msg = PNGZ_MSG_CAST("[truncated]");
  2252. zlib_message(&zlib, 0/*expected*/);
  2253. /* FALL THROUGH */
  2254. default:
  2255. /* Unrecoverable error; skip the chunk; a zlib_message has already
  2256. * been output.
  2257. */
  2258. zlib_end(&zlib);
  2259. return 0;
  2260. }
  2261. /* Optimize window bits or fix a too-far-back error. min_bits and
  2262. * max_bits have been set appropriately, ok_bits records the bit value
  2263. * known to work.
  2264. */
  2265. while (min_bits < max_bits || max_bits < zlib.ok_bits/*if 16*/)
  2266. {
  2267. int test_bits = (min_bits + max_bits) >> 1;
  2268. if (zlib_reset(&zlib, test_bits))
  2269. {
  2270. file_setpos(file, &start_pos);
  2271. rc = zlib_run(&zlib);
  2272. switch (rc)
  2273. {
  2274. case ZLIB_TOO_FAR_BACK:
  2275. min_bits = test_bits+1;
  2276. if (min_bits > max_bits)
  2277. {
  2278. /* This happens when the stream really is damaged and it
  2279. * contains a distance code that addresses bytes before
  2280. * the start of the uncompressed data.
  2281. */
  2282. assert(test_bits == 15);
  2283. /* Output the error that wasn't output before: */
  2284. if (zlib.z.msg == NULL)
  2285. zlib.z.msg = PNGZ_MSG_CAST(
  2286. "invalid distance too far back");
  2287. zlib_message(&zlib, 0/*stream error*/);
  2288. zlib_end(&zlib);
  2289. return 0;
  2290. }
  2291. break;
  2292. case ZLIB_STREAM_END: /* success */
  2293. max_bits = test_bits;
  2294. break;
  2295. default:
  2296. /* A fatal error; this happens if a too-far-back error was
  2297. * hiding a more serious error, zlib_advance has already
  2298. * output a zlib_message.
  2299. */
  2300. zlib_end(&zlib);
  2301. return 0;
  2302. }
  2303. }
  2304. else /* inflateReset2 failed */
  2305. {
  2306. zlib_end(&zlib);
  2307. return 0;
  2308. }
  2309. }
  2310. /* The loop guarantees this */
  2311. assert(zlib.ok_bits == max_bits);
  2312. zlib_end(&zlib);
  2313. return 1;
  2314. }
  2315. else /* zlib initialization failed - skip the chunk */
  2316. {
  2317. zlib_end(&zlib);
  2318. return 0;
  2319. }
  2320. }
  2321. /***************************** LIBPNG CALLBACKS *******************************/
  2322. /* The strategy here is to run a regular libpng PNG file read but examine the
  2323. * input data (from the file) before passing it to libpng so as to be aware of
  2324. * the state we expect libpng to be in. Warning and error callbacks are also
  2325. * intercepted so that they can be quieted and interpreted. Interpretation
  2326. * depends on a somewhat risky string match for known error messages; let us
  2327. * hope that this can be fixed in the next version of libpng.
  2328. *
  2329. * The control structure is pointed to by the libpng error pointer. It contains
  2330. * that set of structures which must persist across multiple read callbacks,
  2331. * which is pretty much everything except the 'zlib' control structure.
  2332. *
  2333. * The file structure is instantiated in the caller of the per-file routine, but
  2334. * the per-file routine contains the chunk and IDAT control structures.
  2335. */
  2336. /* The three routines read_chunk, process_chunk and sync_stream can only be
  2337. * called via a call to read_chunk and only exit at a return from process_chunk.
  2338. * These routines could have been written as one confusing large routine,
  2339. * instead this code relies on the compiler to do tail call elimination. The
  2340. * possible calls are as follows:
  2341. *
  2342. * read_chunk
  2343. * -> sync_stream
  2344. * -> process_chunk
  2345. * -> process_chunk
  2346. * -> read_chunk
  2347. * returns
  2348. */
  2349. static void read_chunk(struct file *file);
  2350. static void
  2351. process_chunk(struct file *file, png_uint_32 file_crc, png_uint_32 next_length,
  2352. png_uint_32 next_type)
  2353. /* Called when the chunk data has been read, next_length and next_type
  2354. * will be set for the next chunk (or 0 if this is IEND).
  2355. *
  2356. * When this routine returns, chunk_length and chunk_type will be set for the
  2357. * next chunk to write because if a chunk is skipped this return calls back
  2358. * to read_chunk.
  2359. */
  2360. {
  2361. const png_uint_32 type = file->type;
  2362. if (file->global->verbose > 1)
  2363. {
  2364. fputs(" ", stderr);
  2365. type_name(file->type, stderr);
  2366. fprintf(stderr, " %lu 0x%.8x 0x%.8x\n", (unsigned long)file->length,
  2367. file->crc ^ 0xffffffff, file_crc);
  2368. }
  2369. /* The basic structure seems correct but the CRC may not match, in this
  2370. * case assume that it is simply a bad CRC, either wrongly calculated or
  2371. * because of damaged stream data.
  2372. */
  2373. if ((file->crc ^ 0xffffffff) != file_crc)
  2374. {
  2375. /* The behavior is set by the 'skip' setting; if it is anything other
  2376. * than SKIP_BAD_CRC ignore the bad CRC and return the chunk, with a
  2377. * corrected CRC and possibly processed, to libpng. Otherwise skip the
  2378. * chunk, which will result in a fatal error if the chunk is critical.
  2379. */
  2380. file->status_code |= CRC_ERROR;
  2381. /* Ignore the bad CRC */
  2382. if (file->global->skip != SKIP_BAD_CRC)
  2383. type_message(file, type, "bad CRC");
  2384. /* This will cause an IEND with a bad CRC to stop */
  2385. else if (CRITICAL(type))
  2386. stop(file, READ_ERROR_CODE, "bad CRC in critical chunk");
  2387. else
  2388. {
  2389. type_message(file, type, "skipped: bad CRC");
  2390. /* NOTE: this cannot be reached for IEND because it is critical. */
  2391. goto skip_chunk;
  2392. }
  2393. }
  2394. /* Check for other 'skip' cases and handle these; these only apply to
  2395. * ancillary chunks (and not tRNS, which should probably have been a critical
  2396. * chunk.)
  2397. */
  2398. if (skip_chunk_type(file->global, type))
  2399. goto skip_chunk;
  2400. /* The chunk may still be skipped if problems are detected in the LZ data,
  2401. * however the LZ data check requires a chunk. Handle this by instantiating
  2402. * a chunk unless an IDAT is already instantiated (IDAT control structures
  2403. * instantiate their own chunk.)
  2404. */
  2405. if (type != png_IDAT)
  2406. file->alloc(file, 0/*chunk*/);
  2407. else if (file->idat == NULL)
  2408. file->alloc(file, 1/*IDAT*/);
  2409. else
  2410. {
  2411. /* The chunk length must be updated for process_IDAT */
  2412. assert(file->chunk != NULL);
  2413. assert(file->chunk->chunk_type == png_IDAT);
  2414. file->chunk->chunk_length = file->length;
  2415. }
  2416. /* Record the 'next' information too, now that the original values for
  2417. * this chunk have been copied. Notice that the IDAT chunks only make a
  2418. * copy of the position of the first chunk, this is fine - process_IDAT does
  2419. * not need the position of this chunk.
  2420. */
  2421. file->length = next_length;
  2422. file->type = next_type;
  2423. getpos(file);
  2424. /* Do per-type processing, note that if this code does not return from the
  2425. * function the chunk will be skipped. The rewrite is cancelled here so that
  2426. * it can be set in the per-chunk processing.
  2427. */
  2428. file->chunk->rewrite_length = 0;
  2429. file->chunk->rewrite_offset = 0;
  2430. switch (type)
  2431. {
  2432. default:
  2433. return;
  2434. case png_IHDR:
  2435. /* Read this now and update the control structure with the information
  2436. * it contains. The header is validated completely to ensure this is a
  2437. * PNG.
  2438. */
  2439. {
  2440. struct chunk *chunk = file->chunk;
  2441. if (chunk->chunk_length != 13)
  2442. stop_invalid(file, "IHDR length");
  2443. /* Read all the IHDR information and validate it. */
  2444. setpos(chunk);
  2445. file->width = reread_4(file);
  2446. file->height = reread_4(file);
  2447. file->bit_depth = reread_byte(file);
  2448. file->color_type = reread_byte(file);
  2449. file->compression_method = reread_byte(file);
  2450. file->filter_method = reread_byte(file);
  2451. file->interlace_method = reread_byte(file);
  2452. /* This validates all the fields, and calls stop_invalid if
  2453. * there is a problem.
  2454. */
  2455. calc_image_size(file);
  2456. }
  2457. return;
  2458. /* Ancillary chunks that require further processing: */
  2459. case png_zTXt: case png_iCCP:
  2460. if (process_zTXt_iCCP(file))
  2461. return;
  2462. chunk_end(&file->chunk);
  2463. file_setpos(file, &file->data_pos);
  2464. break;
  2465. case png_iTXt:
  2466. if (process_iTXt(file))
  2467. return;
  2468. chunk_end(&file->chunk);
  2469. file_setpos(file, &file->data_pos);
  2470. break;
  2471. case png_IDAT:
  2472. if (process_IDAT(file))
  2473. return;
  2474. /* First pass: */
  2475. assert(next_type == png_IDAT);
  2476. break;
  2477. }
  2478. /* Control reaches this point if the chunk must be skipped. For chunks other
  2479. * than IDAT this means that the zlib compressed data is fatally damanged and
  2480. * the chunk will not be passed to libpng. For IDAT it means that the end of
  2481. * the IDAT stream has not yet been reached and we must handle the next
  2482. * (IDAT) chunk. If the LZ data in an IDAT stream cannot be read 'stop' must
  2483. * be used to halt parsing of the PNG.
  2484. */
  2485. read_chunk(file);
  2486. return;
  2487. /* This is the generic code to skip the current chunk; simply jump to the
  2488. * next one.
  2489. */
  2490. skip_chunk:
  2491. file->length = next_length;
  2492. file->type = next_type;
  2493. getpos(file);
  2494. read_chunk(file);
  2495. }
  2496. static png_uint_32
  2497. get32(png_bytep buffer, int offset)
  2498. /* Read a 32-bit value from an 8-byte circular buffer (used only below).
  2499. */
  2500. {
  2501. return
  2502. (buffer[ offset & 7] << 24) +
  2503. (buffer[(offset+1) & 7] << 16) +
  2504. (buffer[(offset+2) & 7] << 8) +
  2505. (buffer[(offset+3) & 7] );
  2506. }
  2507. static void
  2508. sync_stream(struct file *file)
  2509. /* The stream seems to be messed up, attempt to resync from the current chunk
  2510. * header. Executes stop on a fatal error, otherwise calls process_chunk.
  2511. */
  2512. {
  2513. png_uint_32 file_crc;
  2514. file->status_code |= STREAM_ERROR;
  2515. if (file->global->verbose)
  2516. {
  2517. fputs(" SYNC ", stderr);
  2518. type_name(file->type, stderr);
  2519. putc('\n', stderr);
  2520. }
  2521. /* Return to the start of the chunk data */
  2522. file_setpos(file, &file->data_pos);
  2523. file->read_count = 8;
  2524. if (read_4(file, &file_crc) == 4) /* else completely truncated */
  2525. {
  2526. /* Ignore the recorded chunk length, proceed through the data looking for
  2527. * a leading sequence of bytes that match the CRC in the following four
  2528. * bytes. Each time a match is found check the next 8 bytes for a valid
  2529. * length, chunk-type pair.
  2530. */
  2531. png_uint_32 length;
  2532. png_uint_32 type = file->type;
  2533. png_uint_32 crc = crc_init_4(type);
  2534. png_byte buffer[8];
  2535. unsigned int nread = 0, nused = 0;
  2536. for (length=0; length <= 0x7fffffff; ++length)
  2537. {
  2538. int ch;
  2539. if ((crc ^ 0xffffffff) == file_crc)
  2540. {
  2541. /* A match on the CRC; for IEND this is sufficient, but for anything
  2542. * else expect a following chunk header.
  2543. */
  2544. if (type == png_IEND)
  2545. {
  2546. file->length = length;
  2547. process_chunk(file, file_crc, 0, 0);
  2548. return;
  2549. }
  2550. else
  2551. {
  2552. /* Need 8 bytes */
  2553. while (nread < 8+nused)
  2554. {
  2555. ch = read_byte(file);
  2556. if (ch == EOF)
  2557. goto truncated;
  2558. buffer[(nread++) & 7] = (png_byte)ch;
  2559. }
  2560. /* Prevent overflow */
  2561. nread -= nused & ~7;
  2562. nused -= nused & ~7; /* or, nused &= 7 ;-) */
  2563. /* Examine the 8 bytes for a valid chunk header. */
  2564. {
  2565. png_uint_32 next_length = get32(buffer, nused);
  2566. if (next_length < 0x7fffffff)
  2567. {
  2568. png_uint_32 next_type = get32(buffer, nused+4);
  2569. if (chunk_type_valid(next_type))
  2570. {
  2571. file->read_count -= 8;
  2572. process_chunk(file, file_crc, next_length, next_type);
  2573. return;
  2574. }
  2575. }
  2576. /* Not valid, keep going. */
  2577. }
  2578. }
  2579. }
  2580. /* This catches up with the circular buffer which gets filled above
  2581. * while checking a chunk header. This code is slightly tricky - if
  2582. * the chunk_type is IEND the buffer will never be used, if it is not
  2583. * the code will always read ahead exactly 8 bytes and pass this on to
  2584. * process_chunk. So the invariant that IEND leaves the file position
  2585. * after the IEND CRC and other chunk leave it after the *next* chunk
  2586. * header is not broken.
  2587. */
  2588. if (nread <= nused)
  2589. {
  2590. ch = read_byte(file);
  2591. if (ch == EOF)
  2592. goto truncated;
  2593. }
  2594. else
  2595. ch = buffer[(++nused) & 7];
  2596. crc = crc_one_byte(crc, file_crc >> 24);
  2597. file_crc = (file_crc << 8) + ch;
  2598. }
  2599. /* Control gets to here if when 0x7fffffff bytes (plus 8) have been read,
  2600. * ok, treat this as a damaged stream too:
  2601. */
  2602. }
  2603. truncated:
  2604. stop(file, READ_ERROR_CODE, "damaged PNG stream");
  2605. }
  2606. static void
  2607. read_chunk(struct file *file)
  2608. /* On entry file::data_pos must be set to the position of the first byte
  2609. * of the chunk data *and* the input file must be at this position. This
  2610. * routine (via process_chunk) instantiates a chunk or IDAT control structure
  2611. * based on file::length and file::type and also resets these fields and
  2612. * file::data_pos for the chunk after this one. For an IDAT chunk the whole
  2613. * stream of IDATs will be read, until something other than an IDAT is
  2614. * encountered, and the file fields will be set for the chunk after the end
  2615. * of the stream of IDATs.
  2616. *
  2617. * For IEND the file::type field will be set to 0, and nothing beyond the end
  2618. * of the IEND chunk will have been read.
  2619. */
  2620. {
  2621. png_uint_32 length = file->length;
  2622. png_uint_32 type = file->type;
  2623. /* After IEND file::type is set to 0, if libpng attempts to read
  2624. * more data at this point this is a bug in libpng.
  2625. */
  2626. if (type == 0)
  2627. stop(file, UNEXPECTED_ERROR_CODE, "read beyond IEND");
  2628. if (file->global->verbose > 2)
  2629. {
  2630. fputs(" ", stderr);
  2631. type_name(type, stderr);
  2632. fprintf(stderr, " %lu\n", (unsigned long)length);
  2633. }
  2634. /* Start the read_crc calculation with the chunk type, then read to the end
  2635. * of the chunk data (without processing it in any way) to check that it is
  2636. * all there and calculate the CRC.
  2637. */
  2638. file->crc = crc_init_4(type);
  2639. if (crc_read_many(file, length)) /* else it was truncated */
  2640. {
  2641. png_uint_32 file_crc; /* CRC read from file */
  2642. unsigned int nread = read_4(file, &file_crc);
  2643. if (nread == 4)
  2644. {
  2645. if (type != png_IEND) /* do not read beyond IEND */
  2646. {
  2647. png_uint_32 next_length;
  2648. nread += read_4(file, &next_length);
  2649. if (nread == 8 && next_length <= 0x7fffffff)
  2650. {
  2651. png_uint_32 next_type;
  2652. nread += read_4(file, &next_type);
  2653. if (nread == 12 && chunk_type_valid(next_type))
  2654. {
  2655. /* Adjust the read count back to the correct value for this
  2656. * chunk.
  2657. */
  2658. file->read_count -= 8;
  2659. process_chunk(file, file_crc, next_length, next_type);
  2660. return;
  2661. }
  2662. }
  2663. }
  2664. else /* IEND */
  2665. {
  2666. process_chunk(file, file_crc, 0, 0);
  2667. return;
  2668. }
  2669. }
  2670. }
  2671. /* Control gets to here if the the stream seems invalid or damaged in some
  2672. * way. Either there was a problem reading all the expected data (this
  2673. * chunk's data, its CRC and the length and type of the next chunk) or the
  2674. * next chunk length/type are invalid. Notice that the cases that end up
  2675. * here all correspond to cases that would otherwise terminate the read of
  2676. * the PNG file.
  2677. */
  2678. sync_stream(file);
  2679. }
  2680. /* This returns a file* from a png_struct in an implementation specific way. */
  2681. static struct file *get_control(png_const_structrp png_ptr);
  2682. static void PNGCBAPI
  2683. error_handler(png_structp png_ptr, png_const_charp message)
  2684. {
  2685. stop(get_control(png_ptr), LIBPNG_ERROR_CODE, message);
  2686. }
  2687. static void PNGCBAPI
  2688. warning_handler(png_structp png_ptr, png_const_charp message)
  2689. {
  2690. struct file *file = get_control(png_ptr);
  2691. if (file->global->warnings)
  2692. emit_error(file, LIBPNG_WARNING_CODE, message);
  2693. }
  2694. /* Read callback - this is where the work gets done to check the stream before
  2695. * passing it to libpng
  2696. */
  2697. static void PNGCBAPI
  2698. read_callback(png_structp png_ptr, png_bytep buffer, size_t count)
  2699. /* Return 'count' bytes to libpng in 'buffer' */
  2700. {
  2701. struct file *file = get_control(png_ptr);
  2702. png_uint_32 type, length; /* For the chunk be *WRITTEN* */
  2703. struct chunk *chunk;
  2704. /* libpng should always ask for at least one byte */
  2705. if (count == 0)
  2706. stop(file, UNEXPECTED_ERROR_CODE, "read callback for 0 bytes");
  2707. /* The callback always reads ahead by 8 bytes - the signature or chunk header
  2708. * - these bytes are stored in chunk_length and chunk_type. This block is
  2709. * executed once for the signature and once for the first chunk right at the
  2710. * start.
  2711. */
  2712. if (file->read_count < 8)
  2713. {
  2714. assert(file->read_count == 0);
  2715. assert((file->status_code & TRUNCATED) == 0);
  2716. (void)read_4(file, &file->length);
  2717. if (file->read_count == 4)
  2718. (void)read_4(file, &file->type);
  2719. if (file->read_count < 8)
  2720. {
  2721. assert((file->status_code & TRUNCATED) != 0);
  2722. stop(file, READ_ERROR_CODE, "not a PNG (too short)");
  2723. }
  2724. if (file->state == STATE_SIGNATURE)
  2725. {
  2726. if (file->length != sig1 || file->type != sig2)
  2727. stop(file, LIBPNG_ERROR_CODE, "not a PNG (signature)");
  2728. /* Else write it (this is the initialization of write_count, prior to
  2729. * this it contains CLEAR garbage.)
  2730. */
  2731. file->write_count = 0;
  2732. }
  2733. else
  2734. {
  2735. assert(file->state == STATE_CHUNKS);
  2736. /* The first chunk must be a well formed IHDR (this could be relaxed to
  2737. * use the checks in process_chunk, but that seems unnecessary.)
  2738. */
  2739. if (file->length != 13 || file->type != png_IHDR)
  2740. stop(file, LIBPNG_ERROR_CODE, "not a PNG (IHDR)");
  2741. /* The position of the data must be stored too */
  2742. getpos(file);
  2743. }
  2744. }
  2745. /* Retrieve previous state (because the read callbacks are made pretty much
  2746. * byte-by-byte in the sequential reader prior to 1.7).
  2747. */
  2748. chunk = file->chunk;
  2749. if (chunk != NULL)
  2750. {
  2751. length = chunk->chunk_length;
  2752. type = chunk->chunk_type;
  2753. }
  2754. else
  2755. {
  2756. /* This is the signature case; for IDAT and other chunks these values will
  2757. * be overwritten when read_chunk is called below.
  2758. */
  2759. length = file->length;
  2760. type = file->type;
  2761. }
  2762. do
  2763. {
  2764. png_uint_32 b;
  2765. /* Complete the read of a chunk; as a side effect this also instantiates
  2766. * a chunk control structure and sets the file length/type/data_pos fields
  2767. * for the *NEXT* chunk header.
  2768. *
  2769. * NOTE: at an IDAT any following IDAT chunks will also be read and the
  2770. * next_ fields will refer to the chunk after the last IDAT.
  2771. *
  2772. * NOTE: read_chunk only returns when it has read a chunk that must now be
  2773. * written.
  2774. */
  2775. if (file->state != STATE_SIGNATURE && chunk == NULL)
  2776. {
  2777. assert(file->read_count == 8);
  2778. assert(file->idat == NULL);
  2779. read_chunk(file);
  2780. chunk = file->chunk;
  2781. assert(chunk != NULL);
  2782. /* Do the initialization that was not done before. */
  2783. length = chunk->chunk_length;
  2784. type = chunk->chunk_type;
  2785. /* And start writing the new chunk. */
  2786. file->write_count = 0;
  2787. }
  2788. /* The chunk_ fields describe a chunk that must be written, or hold the
  2789. * signature. Write the header first. In the signature case this
  2790. * rewrites the signature.
  2791. */
  2792. switch (file->write_count)
  2793. {
  2794. case 0: b = length >> 24; break;
  2795. case 1: b = length >> 16; break;
  2796. case 2: b = length >> 8; break;
  2797. case 3: b = length ; break;
  2798. case 4: b = type >> 24; break;
  2799. case 5: b = type >> 16; break;
  2800. case 6: b = type >> 8; break;
  2801. case 7: b = type ; break;
  2802. case 8:
  2803. /* The header has been written. If this is really the signature
  2804. * that's all that is required and we can go to normal chunk
  2805. * processing.
  2806. */
  2807. if (file->state == STATE_SIGNATURE)
  2808. {
  2809. /* The signature has been written, the tail call to read_callback
  2810. * below (it's just a goto to the start with a decent compiler)
  2811. * will read the IHDR header ahead and validate it.
  2812. */
  2813. assert(length == sig1 && type == sig2);
  2814. file->read_count = 0; /* Forces a header read */
  2815. file->state = STATE_CHUNKS; /* IHDR: checked above */
  2816. read_callback(png_ptr, buffer, count);
  2817. return;
  2818. }
  2819. else
  2820. {
  2821. assert(chunk != NULL);
  2822. /* Set up for write, notice that repositioning the input stream
  2823. * is only necessary if something is to be read from it. Also
  2824. * notice that for the IDAT stream this must only happen once -
  2825. * on the first IDAT - to get back to the start of the list and
  2826. * this is done inside process_IDAT:
  2827. */
  2828. chunk->write_crc = crc_init_4(type);
  2829. if (file->state != STATE_IDAT && length > 0)
  2830. setpos(chunk);
  2831. }
  2832. /* FALL THROUGH */
  2833. default:
  2834. assert(chunk != NULL);
  2835. /* NOTE: the arithmetic below overflows and gives a large positive
  2836. * png_uint_32 value until the whole chunk data has been written.
  2837. */
  2838. switch (file->write_count - length)
  2839. {
  2840. /* Write the chunk data, normally this just comes from
  2841. * the file. The only exception is for that part of a
  2842. * chunk which is zlib data and which must be rewritten,
  2843. * and IDAT chunks which can be completely
  2844. * reconstructed.
  2845. */
  2846. default:
  2847. if (file->state == STATE_IDAT)
  2848. {
  2849. struct IDAT *idat = file->idat;
  2850. assert(idat != NULL);
  2851. /* Read an IDAT byte from the input stream of IDAT chunks.
  2852. * Because the IDAT stream can be re-chunked this stream is
  2853. * held in the struct IDAT members. The chunk members, in
  2854. * particular chunk_length (and therefore the length local)
  2855. * refer to the output chunk.
  2856. */
  2857. while (idat->idat_index >= idat->idat_length)
  2858. {
  2859. /* Advance one chunk */
  2860. struct IDAT_list *cur = idat->idat_cur;
  2861. assert(idat->idat_index == idat->idat_length);
  2862. assert(cur != NULL && cur->count > 0);
  2863. /* NOTE: IDAT_list::count here, not IDAT_list::length */
  2864. if (++(idat->idat_count) >= cur->count)
  2865. {
  2866. assert(idat->idat_count == cur->count);
  2867. /* Move on to the next IDAT_list: */
  2868. cur = cur->next;
  2869. /* This is an internal error - read beyond the end of
  2870. * the pre-calculated stream.
  2871. */
  2872. if (cur == NULL || cur->count == 0)
  2873. stop(file, UNEXPECTED_ERROR_CODE,
  2874. "read beyond end of IDAT");
  2875. idat->idat_count = 0;
  2876. idat->idat_cur = cur;
  2877. }
  2878. idat->idat_index = 0;
  2879. /* Zero length IDAT chunks are permitted, so the length
  2880. * here may be 0.
  2881. */
  2882. idat->idat_length = cur->lengths[idat->idat_count];
  2883. /* And skip 12 bytes to the next chunk data */
  2884. skip_12(file);
  2885. }
  2886. /* The index is always that of the next byte, the rest of
  2887. * the information is always the current IDAT chunk and the
  2888. * current list.
  2889. */
  2890. ++(idat->idat_index);
  2891. }
  2892. /* Read the byte from the stream. */
  2893. b = reread_byte(file);
  2894. /* If the byte must be rewritten handle that here */
  2895. if (chunk->rewrite_length > 0)
  2896. {
  2897. if (chunk->rewrite_offset > 0)
  2898. --(chunk->rewrite_offset);
  2899. else
  2900. {
  2901. b = chunk->rewrite_buffer[0];
  2902. memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,
  2903. (sizeof chunk->rewrite_buffer)-
  2904. (sizeof chunk->rewrite_buffer[0]));
  2905. --(chunk->rewrite_length);
  2906. }
  2907. }
  2908. chunk->write_crc = crc_one_byte(chunk->write_crc, b);
  2909. break;
  2910. /* The CRC is written at:
  2911. *
  2912. * chunk_write == chunk_length+8..chunk_length+11
  2913. *
  2914. * so 8 to 11. The CRC is not (yet) conditioned.
  2915. */
  2916. case 8: b = chunk->write_crc >> 24; goto write_crc;
  2917. case 9: b = chunk->write_crc >> 16; goto write_crc;
  2918. case 10: b = chunk->write_crc >> 8; goto write_crc;
  2919. case 11:
  2920. /* This must happen before the chunk_end below: */
  2921. b = chunk->write_crc;
  2922. if (file->global->verbose > 2)
  2923. {
  2924. fputs(" ", stderr);
  2925. type_name(type, stderr);
  2926. fprintf(stderr, " %lu 0x%.8x\n", (unsigned long)length,
  2927. chunk->write_crc ^ 0xffffffff);
  2928. }
  2929. /* The IDAT stream is written without a call to read_chunk
  2930. * until the end is reached. rechunk_length() calculates the
  2931. * length of the output chunks. Control gets to this point at
  2932. * the end of an *output* chunk - the length calculated by
  2933. * rechunk_length. If this corresponds to the end of the
  2934. * input stream stop writing IDAT chunks, otherwise continue.
  2935. */
  2936. if (file->state == STATE_IDAT &&
  2937. (file->idat->idat_index < file->idat->idat_length ||
  2938. 1+file->idat->idat_count < file->idat->idat_cur->count ||
  2939. file->idat->idat_cur != file->idat->idat_list_tail))
  2940. {
  2941. /* Write another IDAT chunk. Call rechunk_length to
  2942. * calculate the length required.
  2943. */
  2944. length = chunk->chunk_length = rechunk_length(file->idat);
  2945. assert(type == png_IDAT);
  2946. file->write_count = 0; /* for the new chunk */
  2947. --(file->write_count); /* fake out the increment below */
  2948. }
  2949. else
  2950. {
  2951. /* Entered at the end of a non-IDAT chunk and at the end of
  2952. * the IDAT stream. The rewrite should have been cleared.
  2953. */
  2954. if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)
  2955. stop(file, UNEXPECTED_ERROR_CODE, "pending rewrite");
  2956. /* This is the last byte so reset chunk_read for the next
  2957. * chunk and move the input file to the position after the
  2958. * *next* chunk header if required.
  2959. */
  2960. file->read_count = 8;
  2961. file_setpos(file, &file->data_pos);
  2962. if (file->idat == NULL)
  2963. chunk_end(&file->chunk);
  2964. else
  2965. IDAT_end(&file->idat);
  2966. }
  2967. write_crc:
  2968. b ^= 0xff; /* conditioning */
  2969. break;
  2970. }
  2971. break;
  2972. }
  2973. /* Write one byte */
  2974. b &= 0xff;
  2975. *buffer++ = (png_byte)b;
  2976. --count;
  2977. write_byte(file, (png_byte)b); /* increments chunk_write */
  2978. }
  2979. while (count > 0);
  2980. }
  2981. /* Bundle the file and an uninitialized chunk and IDAT control structure
  2982. * together to allow implementation of the chunk/IDAT allocate routine.
  2983. */
  2984. struct control
  2985. {
  2986. struct file file;
  2987. struct chunk chunk;
  2988. struct IDAT idat;
  2989. };
  2990. static int
  2991. control_end(struct control *control)
  2992. {
  2993. return file_end(&control->file);
  2994. }
  2995. static struct file *
  2996. get_control(png_const_structrp png_ptr)
  2997. {
  2998. /* This just returns the (file*). The chunk and idat control structures
  2999. * don't always exist.
  3000. */
  3001. struct control *control = png_voidcast(struct control*,
  3002. png_get_error_ptr(png_ptr));
  3003. return &control->file;
  3004. }
  3005. static void
  3006. allocate(struct file *file, int allocate_idat)
  3007. {
  3008. struct control *control = png_voidcast(struct control*, file->alloc_ptr);
  3009. if (allocate_idat)
  3010. {
  3011. assert(file->idat == NULL);
  3012. IDAT_init(&control->idat, file);
  3013. }
  3014. else /* chunk */
  3015. {
  3016. assert(file->chunk == NULL);
  3017. chunk_init(&control->chunk, file);
  3018. }
  3019. }
  3020. static int
  3021. control_init(struct control *control, struct global *global,
  3022. const char *file_name, const char *out_name)
  3023. /* This wraps file_init(&control::file) and simply returns the result from
  3024. * file_init.
  3025. */
  3026. {
  3027. return file_init(&control->file, global, file_name, out_name, control,
  3028. allocate);
  3029. }
  3030. static int
  3031. read_png(struct control *control)
  3032. /* Read a PNG, return 0 on success else an error (status) code; a bit mask as
  3033. * defined for file::status_code as above.
  3034. */
  3035. {
  3036. png_structp png_ptr;
  3037. png_infop info_ptr = NULL;
  3038. volatile png_bytep row = NULL, display = NULL;
  3039. volatile int rc;
  3040. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
  3041. error_handler, warning_handler);
  3042. if (png_ptr == NULL)
  3043. {
  3044. /* This is not really expected. */
  3045. log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
  3046. control->file.status_code |= INTERNAL_ERROR;
  3047. return LIBPNG_ERROR_CODE;
  3048. }
  3049. rc = setjmp(control->file.jmpbuf);
  3050. if (rc == 0)
  3051. {
  3052. png_set_read_fn(png_ptr, control, read_callback);
  3053. info_ptr = png_create_info_struct(png_ptr);
  3054. if (info_ptr == NULL)
  3055. png_error(png_ptr, "OOM allocating info structure");
  3056. if (control->file.global->verbose)
  3057. fprintf(stderr, " INFO\n");
  3058. png_read_info(png_ptr, info_ptr);
  3059. {
  3060. png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  3061. row = png_voidcast(png_byte*, malloc(rowbytes));
  3062. display = png_voidcast(png_byte*, malloc(rowbytes));
  3063. if (row == NULL || display == NULL)
  3064. png_error(png_ptr, "OOM allocating row buffers");
  3065. {
  3066. png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
  3067. int passes = png_set_interlace_handling(png_ptr);
  3068. int pass;
  3069. png_start_read_image(png_ptr);
  3070. for (pass = 0; pass < passes; ++pass)
  3071. {
  3072. png_uint_32 y = height;
  3073. /* NOTE: this trashes the row each time; interlace handling won't
  3074. * work, but this avoids memory thrashing for speed testing.
  3075. */
  3076. while (y-- > 0)
  3077. png_read_row(png_ptr, row, display);
  3078. }
  3079. }
  3080. }
  3081. if (control->file.global->verbose)
  3082. fprintf(stderr, " END\n");
  3083. /* Make sure to read to the end of the file: */
  3084. png_read_end(png_ptr, info_ptr);
  3085. }
  3086. png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
  3087. if (row != NULL) free(row);
  3088. if (display != NULL) free(display);
  3089. return rc;
  3090. }
  3091. static int
  3092. one_file(struct global *global, const char *file_name, const char *out_name)
  3093. {
  3094. int rc;
  3095. struct control control;
  3096. if (global->verbose)
  3097. fprintf(stderr, "FILE %s -> %s\n", file_name,
  3098. out_name ? out_name : "<none>");
  3099. /* Although control_init can return a failure code the structure is always
  3100. * initialized, so control_end can be used to accumulate any status codes.
  3101. */
  3102. rc = control_init(&control, global, file_name, out_name);
  3103. if (rc == 0)
  3104. rc = read_png(&control);
  3105. rc |= control_end(&control);
  3106. return rc;
  3107. }
  3108. static void
  3109. usage(const char *prog)
  3110. {
  3111. /* ANSI C-90 limits strings to 509 characters, so use a string array: */
  3112. size_t i;
  3113. static const char *usage_string[] = {
  3114. " Tests, optimizes and optionally fixes the zlib header in PNG files.",
  3115. " Optionally, when fixing, strips ancilliary chunks from the file.",
  3116. 0,
  3117. "OPTIONS",
  3118. " OPERATION",
  3119. " By default files are just checked for readability with a summary of the",
  3120. " of zlib issues founds for each compressed chunk and the IDAT stream in",
  3121. " the file.",
  3122. " --optimize (-o):",
  3123. " Find the smallest deflate window size for the compressed data.",
  3124. " --strip=[none|crc|unsafe|unused|transform|color|all]:",
  3125. " none (default): Retain all chunks.",
  3126. " crc: Remove chunks with a bad CRC.",
  3127. " unsafe: Remove chunks that may be unsafe to retain if the image data",
  3128. " is modified. This is set automatically if --max is given but",
  3129. " may be cancelled by a later --strip=none.",
  3130. " unused: Remove chunks not used by libpng when decoding an image.",
  3131. " This retains any chunks that might be used by libpng image",
  3132. " transformations.",
  3133. " transform: unused+bKGD.",
  3134. " color: transform+iCCP and cHRM.",
  3135. " all: color+gAMA and sRGB.",
  3136. " Only ancillary chunks are ever removed. In addition the tRNS and sBIT",
  3137. " chunks are never removed as they affect exact interpretation of the",
  3138. " image pixel values. The following known chunks are treated specially",
  3139. " by the above options:",
  3140. " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
  3141. " values.",
  3142. " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also",
  3143. " specifies the exact encoding of a pixel value however in practice",
  3144. " most programs will ignore it.",
  3145. " bKGD [transform]: This is used by libpng transforms."
  3146. " --max=<number>:",
  3147. " Use IDAT chunks sized <number>. If no number is given the the IDAT",
  3148. " chunks will be the maximum size permitted; 2^31-1 bytes. If the option",
  3149. " is omitted the original chunk sizes will not be changed. When the",
  3150. " option is given --strip=unsafe is set automatically, this may be",
  3151. " cancelled if you know that all unknown unsafe-to-copy chunks really are",
  3152. " safe to copy across an IDAT size change. This is true of all chunks",
  3153. " that have ever been formally proposed as PNG extensions.",
  3154. " MESSAGES",
  3155. " By default the program only outputs summaries for each file.",
  3156. " --quiet (-q):",
  3157. " Do not output the summaries except for files which cannot be read. With",
  3158. " two --quiets these are not output either.",
  3159. " --errors (-e):",
  3160. " Output errors from libpng and the program (except too-far-back).",
  3161. " --warnings (-w):",
  3162. " Output warnings from libpng.",
  3163. " OUTPUT",
  3164. " By default nothing is written.",
  3165. " --out=<file>:",
  3166. " Write the optimized/corrected version of the next PNG to <file>. This",
  3167. " overrides the following two options",
  3168. " --suffix=<suffix>:",
  3169. " Set --out=<name><suffix> for all following files unless overridden on",
  3170. " a per-file basis by explicit --out.",
  3171. " --prefix=<prefix>:",
  3172. " Set --out=<prefix><name> for all the following files unless overridden",
  3173. " on a per-file basis by explicit --out.",
  3174. " These two options can be used together to produce a suffix and prefix.",
  3175. " INTERNAL OPTIONS",
  3176. #if 0 /*NYI*/
  3177. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  3178. " --test:",
  3179. " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables",
  3180. " output as this would produce a broken file.",
  3181. #endif
  3182. #endif
  3183. 0,
  3184. "EXIT CODES",
  3185. " *** SUBJECT TO CHANGE ***",
  3186. " The program exit code is value in the range 0..127 holding a bit mask of",
  3187. " the following codes. Notice that the results for each file are combined",
  3188. " together - check one file at a time to get a meaningful error code!",
  3189. " 0x01: The zlib too-far-back error existed in at least one chunk.",
  3190. " 0x02: At least once chunk had a CRC error.",
  3191. " 0x04: A chunk length was incorrect.",
  3192. " 0x08: The file was truncated.",
  3193. " Errors less than 16 are potentially recoverable, for a single file if the",
  3194. " exit code is less than 16 the file could be read (with corrections if a",
  3195. " non-zero code is returned).",
  3196. " 0x10: The file could not be read, even with corrections.",
  3197. " 0x20: The output file could not be written.",
  3198. " 0x40: An unexpected, potentially internal, error occured.",
  3199. " If the command line arguments are incorrect the program exits with exit",
  3200. " 255. Some older operating systems only support 7-bit exit codes, on those",
  3201. " systems it is suggested that this program is first tested by supplying",
  3202. " invalid arguments.",
  3203. 0,
  3204. "DESCRIPTION",
  3205. " " PROGRAM_NAME ":",
  3206. " checks each PNG file on the command line for errors. By default errors are",
  3207. " not output and the program just returns an exit code and prints a summary.",
  3208. " With the --quiet (-q) option the summaries are suppressed too and the",
  3209. " program only outputs unexpected errors (internal errors and file open",
  3210. " errors).",
  3211. " Various known problems in PNG files are fixed while the file is being read",
  3212. " The exit code says what problems were fixed. In particular the zlib error:",
  3213. 0,
  3214. " \"invalid distance too far back\"",
  3215. 0,
  3216. " caused by an incorrect optimization of a zlib stream is fixed in any",
  3217. " compressed chunk in which it is encountered. An integrity problem of the",
  3218. " PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
  3219. " is also fixed. Chunk CRC errors are automatically fixed up.",
  3220. 0,
  3221. " Setting one of the \"OUTPUT\" options causes the possibly modified file to",
  3222. " be written to a new file.",
  3223. 0,
  3224. " Notice that some PNG files with the zlib optimization problem can still be",
  3225. " read by libpng under some circumstances. This program will still detect",
  3226. " and, if requested, correct the error.",
  3227. 0,
  3228. " The program will reliably process all files on the command line unless",
  3229. " either an invalid argument causes the usage message (this message) to be",
  3230. " produced or the program crashes.",
  3231. 0,
  3232. " The summary lines describe issues encountered with the zlib compressed",
  3233. " stream of a chunk. They have the following format, which is SUBJECT TO",
  3234. " CHANGE in the future:",
  3235. 0,
  3236. " chunk reason comp-level p1 p2 p3 p4 file",
  3237. 0,
  3238. " p1 through p4 vary according to the 'reason'. There are always 8 space",
  3239. " separated fields. Reasons specific formats are:",
  3240. 0,
  3241. " chunk ERR status code read-errno write-errno message file",
  3242. " chunk SKP comp-level file-bits zlib-rc compressed message file",
  3243. " chunk ??? comp-level file-bits ok-bits compressed uncompress file",
  3244. 0,
  3245. " The various fields are",
  3246. 0,
  3247. "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem",
  3248. " is reported by libpng at the start of the IDAT stream.",
  3249. "$2 reason: One of:",
  3250. " CHK: A zlib header checksum was detected and fixed.",
  3251. " TFB: The zlib too far back error was detected and fixed.",
  3252. " OK : No errors were detected in the zlib stream and optimization",
  3253. " was not requested, or was not possible.",
  3254. " OPT: The zlib stream window bits value could be improved (and was).",
  3255. " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
  3256. " explanation 'message'",
  3257. " ERR: The read of the file was aborted. The parameters explain why.",
  3258. "$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above.",
  3259. " This is printed as a 2 digit hexadecimal value",
  3260. " comp-level: The recorded compression level (FLEVEL) of a zlib stream",
  3261. " expressed as a string {supfast,stdfast,default,maximum}",
  3262. "$4 code: The file exit code; where stop was called, as a fairly terse",
  3263. " string {warning,libpng,zlib,invalid,read,write,unexpected}.",
  3264. " file-bits: The zlib window bits recorded in the file.",
  3265. "$5 read-errno: A system errno value from a read translated by strerror(3).",
  3266. " zlib-rc: A zlib return code as a string (see zlib.h).",
  3267. " ok-bits: The smallest zlib window bits value that works.",
  3268. "$6 write-errno:A system errno value from a write translated by strerror(3).",
  3269. " compressed: The count of compressed bytes in the zlib stream, when the",
  3270. " reason is 'SKP'; this is a count of the bytes read from the",
  3271. " stream when the fatal error was encountered.",
  3272. "$7 message: An error message (spaces replaced by _, as in all parameters),",
  3273. " uncompress: The count of bytes from uncompressing the zlib stream; this",
  3274. " may not be the same as the number of bytes in the image.",
  3275. "$8 file: The name of the file (this may contain spaces).",
  3276. };
  3277. fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
  3278. for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
  3279. {
  3280. if (usage_string[i] != 0)
  3281. fputs(usage_string[i], stderr);
  3282. fputc('\n', stderr);
  3283. }
  3284. exit(255);
  3285. }
  3286. int
  3287. main(int argc, const char **argv)
  3288. {
  3289. const char * prog = *argv;
  3290. const char * outfile = NULL;
  3291. const char * suffix = NULL;
  3292. const char * prefix = NULL;
  3293. int done = 0; /* if at least one file is processed */
  3294. struct global global;
  3295. global_init(&global);
  3296. while (--argc > 0)
  3297. {
  3298. ++argv;
  3299. if (strcmp(*argv, "--debug") == 0)
  3300. {
  3301. /* To help debugging problems: */
  3302. global.errors = global.warnings = 1;
  3303. global.quiet = 0;
  3304. global.verbose = 7;
  3305. }
  3306. else if (strncmp(*argv, "--max=", 6) == 0)
  3307. {
  3308. global.idat_max = (png_uint_32)atol(6+*argv);
  3309. if (global.skip < SKIP_UNSAFE)
  3310. global.skip = SKIP_UNSAFE;
  3311. }
  3312. else if (strcmp(*argv, "--max") == 0)
  3313. {
  3314. global.idat_max = 0x7fffffff;
  3315. if (global.skip < SKIP_UNSAFE)
  3316. global.skip = SKIP_UNSAFE;
  3317. }
  3318. else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
  3319. global.optimize_zlib = 1;
  3320. else if (strncmp(*argv, "--out=", 6) == 0)
  3321. outfile = 6+*argv;
  3322. else if (strncmp(*argv, "--suffix=", 9) == 0)
  3323. suffix = 9+*argv;
  3324. else if (strncmp(*argv, "--prefix=", 9) == 0)
  3325. prefix = 9+*argv;
  3326. else if (strcmp(*argv, "--strip=none") == 0)
  3327. global.skip = SKIP_NONE;
  3328. else if (strcmp(*argv, "--strip=crc") == 0)
  3329. global.skip = SKIP_BAD_CRC;
  3330. else if (strcmp(*argv, "--strip=unsafe") == 0)
  3331. global.skip = SKIP_UNSAFE;
  3332. else if (strcmp(*argv, "--strip=unused") == 0)
  3333. global.skip = SKIP_UNUSED;
  3334. else if (strcmp(*argv, "--strip=transform") == 0)
  3335. global.skip = SKIP_TRANSFORM;
  3336. else if (strcmp(*argv, "--strip=color") == 0)
  3337. global.skip = SKIP_COLOR;
  3338. else if (strcmp(*argv, "--strip=all") == 0)
  3339. global.skip = SKIP_ALL;
  3340. else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
  3341. global.errors = 1;
  3342. else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
  3343. global.warnings = 1;
  3344. else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
  3345. {
  3346. if (global.quiet)
  3347. global.quiet = 2;
  3348. else
  3349. global.quiet = 1;
  3350. }
  3351. else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
  3352. ++global.verbose;
  3353. #if 0
  3354. /* NYI */
  3355. # ifdef PNG_MAXIMUM_INFLATE_WINDOW
  3356. else if (strcmp(*argv, "--test") == 0)
  3357. ++set_option;
  3358. # endif
  3359. #endif
  3360. else if ((*argv)[0] == '-')
  3361. usage(prog);
  3362. else
  3363. {
  3364. size_t outlen = strlen(*argv);
  3365. char temp_name[FILENAME_MAX+1];
  3366. if (outfile == NULL) /* else this takes precedence */
  3367. {
  3368. /* Consider the prefix/suffix options */
  3369. if (prefix != NULL)
  3370. {
  3371. size_t prefixlen = strlen(prefix);
  3372. if (prefixlen+outlen > FILENAME_MAX)
  3373. {
  3374. fprintf(stderr, "%s: output file name too long: %s%s%s\n",
  3375. prog, prefix, *argv, suffix ? suffix : "");
  3376. global.status_code |= WRITE_ERROR;
  3377. continue;
  3378. }
  3379. memcpy(temp_name, prefix, prefixlen);
  3380. memcpy(temp_name+prefixlen, *argv, outlen);
  3381. outlen += prefixlen;
  3382. outfile = temp_name;
  3383. }
  3384. else if (suffix != NULL)
  3385. memcpy(temp_name, *argv, outlen);
  3386. temp_name[outlen] = 0;
  3387. if (suffix != NULL)
  3388. {
  3389. size_t suffixlen = strlen(suffix);
  3390. if (outlen+suffixlen > FILENAME_MAX)
  3391. {
  3392. fprintf(stderr, "%s: output file name too long: %s%s\n",
  3393. prog, *argv, suffix);
  3394. global.status_code |= WRITE_ERROR;
  3395. continue;
  3396. }
  3397. memcpy(temp_name+outlen, suffix, suffixlen);
  3398. outlen += suffixlen;
  3399. temp_name[outlen] = 0;
  3400. outfile = temp_name;
  3401. }
  3402. }
  3403. (void)one_file(&global, *argv, outfile);
  3404. ++done;
  3405. outfile = NULL;
  3406. }
  3407. }
  3408. if (!done)
  3409. usage(prog);
  3410. return global_end(&global);
  3411. }
  3412. #else /* PNG_ZLIB_VERNUM < 0x1240 */
  3413. int
  3414. main(void)
  3415. {
  3416. fprintf(stderr,
  3417. "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n",
  3418. PNG_ZLIB_VERNUM);
  3419. return 77;
  3420. }
  3421. #endif /* PNG_ZLIB_VERNUM */
  3422. #else /* No read support */
  3423. int
  3424. main(void)
  3425. {
  3426. fprintf(stderr, "pngfix does not work without read support\n");
  3427. return 77;
  3428. }
  3429. #endif /* PNG_READ_SUPPORTED && PNG_EASY_ACCESS_SUPPORTED */