1From 40f3e3eb96adb4f1bfc612837653c8e81d8ad46d Mon Sep 17 00:00:00 2001
2From: "Benjamin A. Beasley" <code@musicinmybrain.net>
3Date: Wed, 8 Dec 2021 18:20:00 -0500
4Subject: [PATCH 3/4] Update stb_image from 2.25 to 2.27
5
6      2.27  (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
7      2.26  (2020-07-13) many minor fixes
8---
9 thirdparty/stb/stb_image.h     | 475 +++++++++++++++++++++++++--------
10 thirdparty/stb/stb_image.patch |   6 +-
11 2 files changed, 361 insertions(+), 120 deletions(-)
12
13diff --git a/thirdparty/stb/stb_image.h b/thirdparty/stb/stb_image.h
14index ee8f61c..c58bc0c 100644
15--- a/thirdparty/stb/stb_image.h
16+++ b/thirdparty/stb/stb_image.h
17@@ -1,4 +1,4 @@
18-/* stb_image - v2.25 - public domain image loader - http://nothings.org/stb
19+/* stb_image - v2.27 - public domain image loader - http://nothings.org/stb
20                                   no warranty implied; use at your own risk
21
22    Do this:
23@@ -48,6 +48,8 @@ LICENSE
24
25 RECENT REVISION HISTORY:
26
27+      2.27  (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
28+      2.26  (2020-07-13) many minor fixes
29       2.25  (2020-02-02) fix warnings
30       2.24  (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
31       2.23  (2019-08-11) fix clang static analysis warning
32@@ -88,27 +90,37 @@ RECENT REVISION HISTORY:
33                                            Jeremy Sawicki (handle all ImageNet JPGs)
34  Optimizations & bugfixes                  Mikhail Morozov (1-bit BMP)
35     Fabian "ryg" Giesen                    Anael Seghezzi (is-16-bit query)
36-    Arseny Kapoulkine
37+    Arseny Kapoulkine                      Simon Breuss (16-bit PNM)
38     John-Mark Allen
39     Carmelo J Fdez-Aguera
40
41  Bug & warning fixes
42-    Marc LeBlanc            David Woo          Guillaume George   Martins Mozeiko
43-    Christpher Lloyd        Jerry Jansson      Joseph Thomson     Phil Jordan
44-    Dave Moore              Roy Eltham         Hayaki Saito       Nathan Reed
45-    Won Chun                Luke Graham        Johan Duparc       Nick Verigakis
46-    the Horde3D community   Thomas Ruf         Ronny Chevalier    github:rlyeh
47-    Janez Zemva             John Bartholomew   Michal Cichon      github:romigrou
48-    Jonathan Blow           Ken Hamada         Tero Hanninen      github:svdijk
49-    Laurent Gomila          Cort Stratton      Sergio Gonzalez    github:snagar
50-    Aruelien Pocheville     Thibault Reuille   Cass Everitt       github:Zelex
51-    Ryamond Barbiero        Paul Du Bois       Engin Manap        github:grim210
52-    Aldo Culquicondor       Philipp Wiesemann  Dale Weiler        github:sammyhw
53-    Oriol Ferrer Mesia      Josh Tobin         Matthew Gregan     github:phprus
54-    Julian Raschke          Gregory Mullen     Baldur Karlsson    github:poppolopoppo
55-    Christian Floisand      Kevin Schmidt      JR Smith           github:darealshinji
56-    Brad Weinberger         Matvey Cherevko                       github:Michaelangel007
57-    Blazej Dariusz Roszkowski                  Alexander Veselov
58+    Marc LeBlanc            David Woo          Guillaume George     Martins Mozeiko
59+    Christpher Lloyd        Jerry Jansson      Joseph Thomson       Blazej Dariusz Roszkowski
60+    Phil Jordan                                Dave Moore           Roy Eltham
61+    Hayaki Saito            Nathan Reed        Won Chun
62+    Luke Graham             Johan Duparc       Nick Verigakis       the Horde3D community
63+    Thomas Ruf              Ronny Chevalier                         github:rlyeh
64+    Janez Zemva             John Bartholomew   Michal Cichon        github:romigrou
65+    Jonathan Blow           Ken Hamada         Tero Hanninen        github:svdijk
66+    Eugene Golushkov        Laurent Gomila     Cort Stratton        github:snagar
67+    Aruelien Pocheville     Sergio Gonzalez    Thibault Reuille     github:Zelex
68+    Cass Everitt            Ryamond Barbiero                        github:grim210
69+    Paul Du Bois            Engin Manap        Aldo Culquicondor    github:sammyhw
70+    Philipp Wiesemann       Dale Weiler        Oriol Ferrer Mesia   github:phprus
71+    Josh Tobin                                 Matthew Gregan       github:poppolopoppo
72+    Julian Raschke          Gregory Mullen     Christian Floisand   github:darealshinji
73+    Baldur Karlsson         Kevin Schmidt      JR Smith             github:Michaelangel007
74+                            Brad Weinberger    Matvey Cherevko      github:mosra
75+    Luca Sas                Alexander Veselov  Zack Middleton       [reserved]
76+    Ryan C. Gordon          [reserved]                              [reserved]
77+                     DO NOT ADD YOUR NAME HERE
78+
79+                     Jacko Dirks
80+
81+  To add your name to the credits, pick a random blank space in the middle and fill it.
82+  80% of merge conflicts on stb PRs are due to people adding their name at the end
83+  of the credits.
84 */
85
86 #ifndef STBI_INCLUDE_STB_IMAGE_H
87@@ -167,6 +179,32 @@ RECENT REVISION HISTORY:
88 //
89 // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
90 //
91+// To query the width, height and component count of an image without having to
92+// decode the full file, you can use the stbi_info family of functions:
93+//
94+//   int x,y,n,ok;
95+//   ok = stbi_info(filename, &x, &y, &n);
96+//   // returns ok=1 and sets x, y, n if image is a supported format,
97+//   // 0 otherwise.
98+//
99+// Note that stb_image pervasively uses ints in its public API for sizes,
100+// including sizes of memory buffers. This is now part of the API and thus
101+// hard to change without causing breakage. As a result, the various image
102+// loaders all have certain limits on image size; these differ somewhat
103+// by format but generally boil down to either just under 2GB or just under
104+// 1GB. When the decoded image would be larger than this, stb_image decoding
105+// will fail.
106+//
107+// Additionally, stb_image will reject image files that have any of their
108+// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
109+// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
110+// the only way to have an image with such dimensions load correctly
111+// is for it to have a rather extreme aspect ratio. Either way, the
112+// assumption here is that such larger images are likely to be malformed
113+// or malicious. If you do need to load an image with individual dimensions
114+// larger than that, and it still fits in the overall size limit, you can
115+// #define STBI_MAX_DIMENSIONS on your own to be something larger.
116+//
117 // ===========================================================================
118 //
119 // UNICODE:
120@@ -272,11 +310,10 @@ RECENT REVISION HISTORY:
121 //
122 // iPhone PNG support:
123 //
124-// By default we convert iphone-formatted PNGs back to RGB, even though
125-// they are internally encoded differently. You can disable this conversion
126-// by calling stbi_convert_iphone_png_to_rgb(0), in which case
127-// you will always just get the native iphone "format" through (which
128-// is BGR stored in RGB).
129+// We optionally support converting iPhone-formatted PNGs (which store
130+// premultiplied BGRA) back to RGB, even though they're internally encoded
131+// differently. To enable this conversion, call
132+// stbi_convert_iphone_png_to_rgb(1).
133 //
134 // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
135 // pixel to remove any premultiplied alpha *only* if the image file explicitly
136@@ -318,7 +355,14 @@ RECENT REVISION HISTORY:
137 //   - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
138 //     want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
139 //
140-
141+//  - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
142+//    than that size (in either width or height) without further processing.
143+//    This is to let programs in the wild set an upper bound to prevent
144+//    denial-of-service attacks on untrusted data, as one could generate a
145+//    valid image of gigantic dimensions and force stb_image to allocate a
146+//    huge block of memory and spend disproportionate time decoding it. By
147+//    default this is set to (1 << 24), which is 16777216, but that's still
148+//    very big.
149
150 #ifndef STBI_NO_STDIO
151 #include <stdio.h>
152@@ -473,6 +517,8 @@ STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
153 // as above, but only applies to images loaded on the thread that calls the function
154 // this function is only available if your compiler supports thread-local variables;
155 // calling it will fail to link if your compiler doesn't
156+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
157+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
158 STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
159
160 // ZLIB client - used by PNG, available for other purposes
161@@ -574,13 +620,19 @@ STBIDEF int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch
162 #ifndef STBI_NO_THREAD_LOCALS
163    #if defined(__cplusplus) &&  __cplusplus >= 201103L
164       #define STBI_THREAD_LOCAL       thread_local
165-   #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
166-      #define STBI_THREAD_LOCAL       _Thread_local
167-   #elif defined(__GNUC__)
168+   #elif defined(__GNUC__) && __GNUC__ < 5
169       #define STBI_THREAD_LOCAL       __thread
170    #elif defined(_MSC_VER)
171       #define STBI_THREAD_LOCAL       __declspec(thread)
172-#endif
173+   #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
174+      #define STBI_THREAD_LOCAL       _Thread_local
175+   #endif
176+
177+   #ifndef STBI_THREAD_LOCAL
178+      #if defined(__GNUC__)
179+        #define STBI_THREAD_LOCAL       __thread
180+      #endif
181+   #endif
182 #endif
183
184 #ifdef _MSC_VER
185@@ -612,7 +664,7 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
186 #ifdef STBI_HAS_LROTL
187    #define stbi_lrot(x,y)  _lrotl(x,y)
188 #else
189-   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (32 - (y))))
190+   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (-(y) & 31)))
191 #endif
192
193 #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
194@@ -726,14 +778,21 @@ static int stbi__sse2_available(void)
195
196 #ifdef STBI_NEON
197 #include <arm_neon.h>
198-// assume GCC or Clang on ARM targets
199+#ifdef _MSC_VER
200+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
201+#else
202 #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
203 #endif
204+#endif
205
206 #ifndef STBI_SIMD_ALIGN
207 #define STBI_SIMD_ALIGN(type, name) type name
208 #endif
209
210+#ifndef STBI_MAX_DIMENSIONS
211+#define STBI_MAX_DIMENSIONS (1 << 24)
212+#endif
213+
214 ///////////////////////////////////////////////
215 //
216 //  stbi__context struct and start_xxx functions
217@@ -751,6 +810,7 @@ typedef struct
218    int read_from_callbacks;
219    int buflen;
220    stbi_uc buffer_start[128];
221+   int callback_already_read;
222
223    stbi_uc *img_buffer, *img_buffer_end;
224    stbi_uc *img_buffer_original, *img_buffer_original_end;
225@@ -764,6 +824,7 @@ static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
226 {
227    s->io.read = NULL;
228    s->read_from_callbacks = 0;
229+   s->callback_already_read = 0;
230    s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
231    s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
232 }
233@@ -775,7 +836,8 @@ static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *
234    s->io_user_data = user;
235    s->buflen = sizeof(s->buffer_start);
236    s->read_from_callbacks = 1;
237-   s->img_buffer_original = s->buffer_start;
238+   s->callback_already_read = 0;
239+   s->img_buffer = s->img_buffer_original = s->buffer_start;
240    stbi__refill_buffer(s);
241    s->img_buffer_original_end = s->img_buffer_end;
242 }
243@@ -789,12 +851,17 @@ static int stbi__stdio_read(void *user, char *data, int size)
244
245 static void stbi__stdio_skip(void *user, int n)
246 {
247+   int ch;
248    fseek((FILE*) user, n, SEEK_CUR);
249+   ch = fgetc((FILE*) user);  /* have to read a byte to reset feof()'s flag */
250+   if (ch != EOF) {
251+      ungetc(ch, (FILE *) user);  /* push byte back onto stream if valid. */
252+   }
253 }
254
255 static int stbi__stdio_eof(void *user)
256 {
257-   return feof((FILE*) user);
258+   return feof((FILE*) user) || ferror((FILE *) user);
259 }
260
261 static stbi_io_callbacks stbi__stdio_callbacks =
262@@ -890,6 +957,7 @@ static int      stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
263 static int      stbi__pnm_test(stbi__context *s);
264 static void    *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
265 static int      stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
266+static int      stbi__pnm_is16(stbi__context *s);
267 #endif
268
269 static
270@@ -964,7 +1032,7 @@ static int stbi__mad3sizes_valid(int a, int b, int c, int add)
271 }
272
273 // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow
274-#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
275+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
276 static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
277 {
278    return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
279@@ -987,7 +1055,7 @@ static void *stbi__malloc_mad3(int a, int b, int c, int add)
280    return stbi__malloc(a*b*c + add);
281 }
282
283-#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
284+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
285 static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)
286 {
287    if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;
288@@ -1053,9 +1121,8 @@ static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int re
289    ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
290    ri->num_channels = 0;
291
292-   #ifndef STBI_NO_JPEG
293-   if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);
294-   #endif
295+   // test the formats with a very explicit header first (at least a FOURCC
296+   // or distinctive magic number first)
297    #ifndef STBI_NO_PNG
298    if (stbi__png_test(s))  return stbi__png_load(s,x,y,comp,req_comp, ri);
299    #endif
300@@ -1073,6 +1140,13 @@ static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int re
301    #ifndef STBI_NO_PIC
302    if (stbi__pic_test(s))  return stbi__pic_load(s,x,y,comp,req_comp, ri);
303    #endif
304+
305+   // then the formats that can end up attempting to load with just 1 or 2
306+   // bytes matching expectations; these are prone to false positives, so
307+   // try them later
308+   #ifndef STBI_NO_JPEG
309+   if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);
310+   #endif
311    #ifndef STBI_NO_PNM
312    if (stbi__pnm_test(s))  return stbi__pnm_load(s,x,y,comp,req_comp, ri);
313    #endif
314@@ -1171,8 +1245,10 @@ static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x,
315    if (result == NULL)
316       return NULL;
317
318+   // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
319+   STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
320+
321    if (ri.bits_per_channel != 8) {
322-      STBI_ASSERT(ri.bits_per_channel == 16);
323       result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
324       ri.bits_per_channel = 8;
325    }
326@@ -1195,8 +1271,10 @@ static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x,
327    if (result == NULL)
328       return NULL;
329
330+   // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
331+   STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
332+
333    if (ri.bits_per_channel != 16) {
334-      STBI_ASSERT(ri.bits_per_channel == 8);
335       result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
336       ri.bits_per_channel = 16;
337    }
338@@ -1224,12 +1302,12 @@ static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, in
339
340 #ifndef STBI_NO_STDIO
341
342-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)
343+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
344 STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
345 STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
346 #endif
347
348-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)
349+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
350 STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
351 {
352 	return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
353@@ -1239,16 +1317,16 @@ STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wch
354 static FILE *stbi__fopen(char const *filename, char const *mode)
355 {
356    FILE *f;
357-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)
358+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
359    wchar_t wMode[64];
360    wchar_t wFilename[1024];
361-	if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)))
362+	if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
363       return 0;
364
365-	if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)))
366+	if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
367       return 0;
368
369-#if _MSC_VER >= 1400
370+#if defined(_MSC_VER) && _MSC_VER >= 1400
371 	if (0 != _wfopen_s(&f, wFilename, wMode))
372 		f = 0;
373 #else
374@@ -1499,6 +1577,7 @@ enum
375 static void stbi__refill_buffer(stbi__context *s)
376 {
377    int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
378+   s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);
379    if (n == 0) {
380       // at end of file, treat same as if from memory, but need to handle case
381       // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
382@@ -1544,6 +1623,7 @@ stbi_inline static int stbi__at_eof(stbi__context *s)
383 #else
384 static void stbi__skip(stbi__context *s, int n)
385 {
386+   if (n == 0) return;  // already there!
387    if (n < 0) {
388       s->img_buffer = s->img_buffer_end;
389       return;
390@@ -1622,7 +1702,8 @@ static int stbi__get16le(stbi__context *s)
391 static stbi__uint32 stbi__get32le(stbi__context *s)
392 {
393    stbi__uint32 z = stbi__get16le(s);
394-   return z + (stbi__get16le(s) << 16);
395+   z += (stbi__uint32)stbi__get16le(s) << 16;
396+   return z;
397 }
398 #endif
399
400@@ -1690,7 +1771,7 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r
401          STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]);                   } break;
402          STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;
403          STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];                    } break;
404-         default: STBI_ASSERT(0);
405+         default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion");
406       }
407       #undef STBI__CASE
408    }
409@@ -1747,7 +1828,7 @@ static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int r
410          STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]);                   } break;
411          STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;
412          STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];                       } break;
413-         default: STBI_ASSERT(0);
414+         default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion");
415       }
416       #undef STBI__CASE
417    }
418@@ -2054,13 +2135,12 @@ stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
419    int sgn;
420    if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
421
422-   sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB
423+   sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)
424    k = stbi_lrot(j->code_buffer, n);
425-   STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask)));
426    j->code_buffer = k & ~stbi__bmask[n];
427    k &= stbi__bmask[n];
428    j->code_bits -= n;
429-   return k + (stbi__jbias[n] & ~sgn);
430+   return k + (stbi__jbias[n] & (sgn - 1));
431 }
432
433 // get some unsigned bits
434@@ -2110,7 +2190,7 @@ static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman
435
436    if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
437    t = stbi__jpeg_huff_decode(j, hdc);
438-   if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");
439+   if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG");
440
441    // 0 all the ac values now so we can do it 32-bits at a time
442    memset(data,0,64*sizeof(data[0]));
443@@ -2167,11 +2247,12 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__
444       // first scan for DC coefficient, must be first
445       memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
446       t = stbi__jpeg_huff_decode(j, hdc);
447+      if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
448       diff = t ? stbi__extend_receive(j, t) : 0;
449
450       dc = j->img_comp[b].dc_pred + diff;
451       j->img_comp[b].dc_pred = dc;
452-      data[0] = (short) (dc << j->succ_low);
453+      data[0] = (short) (dc * (1 << j->succ_low));
454    } else {
455       // refinement scan for DC coefficient
456       if (stbi__jpeg_get_bit(j))
457@@ -2208,7 +2289,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__
458             j->code_buffer <<= s;
459             j->code_bits -= s;
460             zig = stbi__jpeg_dezigzag[k++];
461-            data[zig] = (short) ((r >> 8) << shift);
462+            data[zig] = (short) ((r >> 8) * (1 << shift));
463          } else {
464             int rs = stbi__jpeg_huff_decode(j, hac);
465             if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
466@@ -2226,7 +2307,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__
467             } else {
468                k += r;
469                zig = stbi__jpeg_dezigzag[k++];
470-               data[zig] = (short) (stbi__extend_receive(j,s) << shift);
471+               data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));
472             }
473          }
474       } while (k <= j->spec_end);
475@@ -3157,6 +3238,8 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan)
476    p  = stbi__get8(s);            if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
477    s->img_y = stbi__get16be(s);   if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
478    s->img_x = stbi__get16be(s);   if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
479+   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
480+   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
481    c = stbi__get8(s);
482    if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG");
483    s->img_n = c;
484@@ -3188,6 +3271,13 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan)
485       if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
486    }
487
488+   // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
489+   // and I've never seen a non-corrupted JPEG file actually use them
490+   for (i=0; i < s->img_n; ++i) {
491+      if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG");
492+      if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG");
493+   }
494+
495    // compute interleaved mcu info
496    z->img_h_max = h_max;
497    z->img_v_max = v_max;
498@@ -3743,6 +3833,10 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp
499    else
500       decode_n = z->s->img_n;
501
502+   // nothing to do if no components requested; check this now to avoid
503+   // accessing uninitialized coutput[0] later
504+   if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }
505+
506    // resample and color-convert
507    {
508       int k;
509@@ -3885,6 +3979,7 @@ static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int re
510 {
511    unsigned char* result;
512    stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));
513+   if (!j) return stbi__errpuc("outofmem", "Out of memory");
514    STBI_NOTUSED(ri);
515    j->s = s;
516    stbi__setup_jpeg(j);
517@@ -3897,6 +3992,7 @@ static int stbi__jpeg_test(stbi__context *s)
518 {
519    int r;
520    stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
521+   if (!j) return stbi__err("outofmem", "Out of memory");
522    j->s = s;
523    stbi__setup_jpeg(j);
524    r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
525@@ -3921,6 +4017,7 @@ static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
526 {
527    int result;
528    stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));
529+   if (!j) return stbi__err("outofmem", "Out of memory");
530    j->s = s;
531    result = stbi__jpeg_info_raw(j, x, y, comp);
532    STBI_FREE(j);
533@@ -3940,6 +4037,7 @@ static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
534 // fast-way is faster to check than jpeg huffman, but slow way is slower
535 #define STBI__ZFAST_BITS  9 // accelerate all cases in default tables
536 #define STBI__ZFAST_MASK  ((1 << STBI__ZFAST_BITS) - 1)
537+#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet
538
539 // zlib-style huffman encoding
540 // (jpegs packs from left, zlib from right, so can't share code)
541@@ -3949,8 +4047,8 @@ typedef struct
542    stbi__uint16 firstcode[16];
543    int maxcode[17];
544    stbi__uint16 firstsymbol[16];
545-   stbi_uc  size[288];
546-   stbi__uint16 value[288];
547+   stbi_uc  size[STBI__ZNSYMS];
548+   stbi__uint16 value[STBI__ZNSYMS];
549 } stbi__zhuffman;
550
551 stbi_inline static int stbi__bitreverse16(int n)
552@@ -4037,16 +4135,23 @@ typedef struct
553    stbi__zhuffman z_length, z_distance;
554 } stbi__zbuf;
555
556+stbi_inline static int stbi__zeof(stbi__zbuf *z)
557+{
558+   return (z->zbuffer >= z->zbuffer_end);
559+}
560+
561 stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
562 {
563-   if (z->zbuffer >= z->zbuffer_end) return 0;
564-   return *z->zbuffer++;
565+   return stbi__zeof(z) ? 0 : *z->zbuffer++;
566 }
567
568 static void stbi__fill_bits(stbi__zbuf *z)
569 {
570    do {
571-      STBI_ASSERT(z->code_buffer < (1U << z->num_bits));
572+      if (z->code_buffer >= (1U << z->num_bits)) {
573+        z->zbuffer = z->zbuffer_end;  /* treat this as EOF so we fail. */
574+        return;
575+      }
576       z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
577       z->num_bits += 8;
578    } while (z->num_bits <= 24);
579@@ -4071,10 +4176,11 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
580    for (s=STBI__ZFAST_BITS+1; ; ++s)
581       if (k < z->maxcode[s])
582          break;
583-   if (s == 16) return -1; // invalid code!
584+   if (s >= 16) return -1; // invalid code!
585    // code size is s, so:
586    b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
587-   STBI_ASSERT(z->size[b] == s);
588+   if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!
589+   if (z->size[b] != s) return -1;  // was originally an assert, but report failure instead.
590    a->code_buffer >>= s;
591    a->num_bits -= s;
592    return z->value[b];
593@@ -4083,7 +4189,12 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
594 stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
595 {
596    int b,s;
597-   if (a->num_bits < 16) stbi__fill_bits(a);
598+   if (a->num_bits < 16) {
599+      if (stbi__zeof(a)) {
600+         return -1;   /* report error for unexpected end of data. */
601+      }
602+      stbi__fill_bits(a);
603+   }
604    b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
605    if (b) {
606       s = b >> 9;
607@@ -4097,13 +4208,16 @@ stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
608 static int stbi__zexpand(stbi__zbuf *z, char *zout, int n)  // need to make room for n bytes
609 {
610    char *q;
611-   int cur, limit, old_limit;
612+   unsigned int cur, limit, old_limit;
613    z->zout = zout;
614    if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
615-   cur   = (int) (z->zout     - z->zout_start);
616-   limit = old_limit = (int) (z->zout_end - z->zout_start);
617-   while (cur + n > limit)
618+   cur   = (unsigned int) (z->zout - z->zout_start);
619+   limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
620+   if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
621+   while (cur + n > limit) {
622+      if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
623       limit *= 2;
624+   }
625    q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
626    STBI_NOTUSED(old_limit);
627    if (q == NULL) return stbi__err("outofmem", "Out of memory");
628@@ -4201,11 +4315,12 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a)
629             c = stbi__zreceive(a,2)+3;
630             if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
631             fill = lencodes[n-1];
632-         } else if (c == 17)
633+         } else if (c == 17) {
634             c = stbi__zreceive(a,3)+3;
635-         else {
636-            STBI_ASSERT(c == 18);
637+         } else if (c == 18) {
638             c = stbi__zreceive(a,7)+11;
639+         } else {
640+            return stbi__err("bad codelengths", "Corrupt PNG");
641          }
642          if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
643          memset(lencodes+n, fill, c);
644@@ -4231,7 +4346,7 @@ static int stbi__parse_uncompressed_block(stbi__zbuf *a)
645       a->code_buffer >>= 8;
646       a->num_bits -= 8;
647    }
648-   STBI_ASSERT(a->num_bits == 0);
649+   if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG");
650    // now fill header the normal way
651    while (k < 4)
652       header[k++] = stbi__zget8(a);
653@@ -4253,6 +4368,7 @@ static int stbi__parse_zlib_header(stbi__zbuf *a)
654    int cm    = cmf & 15;
655    /* int cinfo = cmf >> 4; */
656    int flg   = stbi__zget8(a);
657+   if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
658    if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
659    if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
660    if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
661@@ -4260,7 +4376,7 @@ static int stbi__parse_zlib_header(stbi__zbuf *a)
662    return 1;
663 }
664
665-static const stbi_uc stbi__zdefault_length[288] =
666+static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =
667 {
668    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
669    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
670@@ -4306,7 +4422,7 @@ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
671       } else {
672          if (type == 1) {
673             // use fixed code lengths
674-            if (!stbi__zbuild_huffman(&a->z_length  , stbi__zdefault_length  , 288)) return 0;
675+            if (!stbi__zbuild_huffman(&a->z_length  , stbi__zdefault_length  , STBI__ZNSYMS)) return 0;
676             if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance,  32)) return 0;
677          } else {
678             if (!stbi__compute_huffman_codes(a)) return 0;
679@@ -4514,7 +4630,7 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r
680          return stbi__err("invalid filter","Corrupt PNG");
681
682       if (depth < 8) {
683-         STBI_ASSERT(img_width_bytes <= x);
684+         if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG");
685          cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place
686          filter_bytes = 1;
687          width = img_width_bytes;
688@@ -4702,6 +4818,7 @@ static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint3
689
690    // de-interlacing
691    final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
692+   if (!final) return stbi__err("outofmem", "Out of memory");
693    for (p=0; p < 7; ++p) {
694       int xorig[] = { 0,4,0,2,0,1,0 };
695       int yorig[] = { 0,0,4,0,2,0,1 };
696@@ -4822,19 +4939,46 @@ static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int
697    return 1;
698 }
699
700-static int stbi__unpremultiply_on_load = 0;
701-static int stbi__de_iphone_flag = 0;
702+static int stbi__unpremultiply_on_load_global = 0;
703+static int stbi__de_iphone_flag_global = 0;
704
705 STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
706 {
707-   stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
708+   stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
709 }
710
711 STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
712 {
713-   stbi__de_iphone_flag = flag_true_if_should_convert;
714+   stbi__de_iphone_flag_global = flag_true_if_should_convert;
715+}
716+
717+#ifndef STBI_THREAD_LOCAL
718+#define stbi__unpremultiply_on_load  stbi__unpremultiply_on_load_global
719+#define stbi__de_iphone_flag  stbi__de_iphone_flag_global
720+#else
721+static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
722+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
723+
724+STBIDEF void stbi__unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
725+{
726+   stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
727+   stbi__unpremultiply_on_load_set = 1;
728 }
729
730+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
731+{
732+   stbi__de_iphone_flag_local = flag_true_if_should_convert;
733+   stbi__de_iphone_flag_set = 1;
734+}
735+
736+#define stbi__unpremultiply_on_load  (stbi__unpremultiply_on_load_set           \
737+                                       ? stbi__unpremultiply_on_load_local      \
738+                                       : stbi__unpremultiply_on_load_global)
739+#define stbi__de_iphone_flag  (stbi__de_iphone_flag_set                         \
740+                                ? stbi__de_iphone_flag_local                    \
741+                                : stbi__de_iphone_flag_global)
742+#endif // STBI_THREAD_LOCAL
743+
744 static void stbi__de_iphone(stbi__png *z)
745 {
746    stbi__context *s = z->s;
747@@ -4909,8 +5053,10 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
748             if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
749             first = 0;
750             if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
751-            s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
752-            s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
753+            s->img_x = stbi__get32be(s);
754+            s->img_y = stbi__get32be(s);
755+            if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
756+            if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
757             z->depth = stbi__get8(s);  if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16)  return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
758             color = stbi__get8(s);  if (color > 6)         return stbi__err("bad ctype","Corrupt PNG");
759             if (color == 3 && z->depth == 16)                  return stbi__err("bad ctype","Corrupt PNG");
760@@ -5059,10 +5205,12 @@ static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, st
761    void *result=NULL;
762    if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
763    if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
764-      if (p->depth < 8)
765+      if (p->depth <= 8)
766          ri->bits_per_channel = 8;
767+      else if (p->depth == 16)
768+         ri->bits_per_channel = 16;
769       else
770-         ri->bits_per_channel = p->depth;
771+         return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
772       result = p->out;
773       p->out = NULL;
774       if (req_comp && req_comp != p->s->img_out_n) {
775@@ -5211,6 +5359,32 @@ typedef struct
776    int extra_read;
777 } stbi__bmp_data;
778
779+static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)
780+{
781+   // BI_BITFIELDS specifies masks explicitly, don't override
782+   if (compress == 3)
783+      return 1;
784+
785+   if (compress == 0) {
786+      if (info->bpp == 16) {
787+         info->mr = 31u << 10;
788+         info->mg = 31u <<  5;
789+         info->mb = 31u <<  0;
790+      } else if (info->bpp == 32) {
791+         info->mr = 0xffu << 16;
792+         info->mg = 0xffu <<  8;
793+         info->mb = 0xffu <<  0;
794+         info->ma = 0xffu << 24;
795+         info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
796+      } else {
797+         // otherwise, use defaults, which is all-0
798+         info->mr = info->mg = info->mb = info->ma = 0;
799+      }
800+      return 1;
801+   }
802+   return 0; // error
803+}
804+
805 static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
806 {
807    int hsz;
808@@ -5223,6 +5397,8 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
809    info->mr = info->mg = info->mb = info->ma = 0;
810    info->extra_read = 14;
811
812+   if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP");
813+
814    if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
815    if (hsz == 12) {
816       s->img_x = stbi__get16le(s);
817@@ -5236,6 +5412,8 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
818    if (hsz != 12) {
819       int compress = stbi__get32le(s);
820       if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
821+      if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes
822+      if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
823       stbi__get32le(s); // discard sizeof
824       stbi__get32le(s); // discard hres
825       stbi__get32le(s); // discard vres
826@@ -5250,17 +5428,7 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
827          }
828          if (info->bpp == 16 || info->bpp == 32) {
829             if (compress == 0) {
830-               if (info->bpp == 32) {
831-                  info->mr = 0xffu << 16;
832-                  info->mg = 0xffu <<  8;
833-                  info->mb = 0xffu <<  0;
834-                  info->ma = 0xffu << 24;
835-                  info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
836-               } else {
837-                  info->mr = 31u << 10;
838-                  info->mg = 31u <<  5;
839-                  info->mb = 31u <<  0;
840-               }
841+               stbi__bmp_set_mask_defaults(info, compress);
842             } else if (compress == 3) {
843                info->mr = stbi__get32le(s);
844                info->mg = stbi__get32le(s);
845@@ -5275,6 +5443,7 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
846                return stbi__errpuc("bad BMP", "bad BMP");
847          }
848       } else {
849+         // V4/V5 header
850          int i;
851          if (hsz != 108 && hsz != 124)
852             return stbi__errpuc("bad BMP", "bad BMP");
853@@ -5282,6 +5451,8 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
854          info->mg = stbi__get32le(s);
855          info->mb = stbi__get32le(s);
856          info->ma = stbi__get32le(s);
857+         if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
858+            stbi__bmp_set_mask_defaults(info, compress);
859          stbi__get32le(s); // discard color space
860          for (i=0; i < 12; ++i)
861             stbi__get32le(s); // discard color space parameters
862@@ -5314,6 +5485,9 @@ static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req
863    flip_vertically = ((int) s->img_y) > 0;
864    s->img_y = abs((int) s->img_y);
865
866+   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
867+   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
868+
869    mr = info.mr;
870    mg = info.mg;
871    mb = info.mb;
872@@ -5328,7 +5502,9 @@ static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req
873          psize = (info.offset - info.extra_read - info.hsz) >> 2;
874    }
875    if (psize == 0) {
876-      STBI_ASSERT(info.offset == (s->img_buffer - s->buffer_start));
877+      if (info.offset != s->callback_already_read + (s->img_buffer - s->img_buffer_original)) {
878+        return stbi__errpuc("bad offset", "Corrupt BMP");
879+      }
880    }
881
882    if (info.bpp == 24 && ma == 0xff000000)
883@@ -5423,6 +5599,7 @@ static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req
884          gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
885          bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
886          ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
887+         if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
888       }
889       for (j=0; j < (int) s->img_y; ++j) {
890          if (easy) {
891@@ -5647,6 +5824,9 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req
892    STBI_NOTUSED(tga_x_origin); // @TODO
893    STBI_NOTUSED(tga_y_origin); // @TODO
894
895+   if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
896+   if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
897+
898    //   do a tiny bit of precessing
899    if ( tga_image_type >= 8 )
900    {
901@@ -5686,6 +5866,11 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req
902       //   do I need to load a palette?
903       if ( tga_indexed)
904       {
905+         if (tga_palette_len == 0) {  /* you have to have at least one entry! */
906+            STBI_FREE(tga_data);
907+            return stbi__errpuc("bad palette", "Corrupt TGA");
908+         }
909+
910          //   any data to skip? (offset usually = 0)
911          stbi__skip(s, tga_palette_start );
912          //   load the palette
913@@ -5894,6 +6079,9 @@ static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req
914    h = stbi__get32be(s);
915    w = stbi__get32be(s);
916
917+   if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
918+   if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
919+
920    // Make sure the depth is 8 bits.
921    bitdepth = stbi__get16be(s);
922    if (bitdepth != 8 && bitdepth != 16)
923@@ -6248,6 +6436,10 @@ static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_c
924
925    x = stbi__get16be(s);
926    y = stbi__get16be(s);
927+
928+   if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
929+   if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
930+
931    if (stbi__at_eof(s))  return stbi__errpuc("bad file","file too short (pic header)");
932    if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode");
933
934@@ -6257,6 +6449,7 @@ static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_c
935
936    // intermediate buffer is RGBA
937    result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);
938+   if (!result) return stbi__errpuc("outofmem", "Out of memory");
939    memset(result, 0xff, x*y*4);
940
941    if (!stbi__pic_load_core(s,x,y,comp, result)) {
942@@ -6356,6 +6549,9 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in
943    g->ratio = stbi__get8(s);
944    g->transparent = -1;
945
946+   if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
947+   if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
948+
949    if (comp != 0) *comp = 4;  // can't actually tell whether it's 3 or 4 until we parse the comments
950
951    if (is_info) return 1;
952@@ -6369,6 +6565,7 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in
953 static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
954 {
955    stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
956+   if (!g) return stbi__err("outofmem", "Out of memory");
957    if (!stbi__gif_header(s, g, comp, 1)) {
958       STBI_FREE(g);
959       stbi__rewind( s );
960@@ -6533,7 +6730,7 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i
961       memset(g->history, 0x00, pcount);        // pixels that were affected previous frame
962       first_frame = 1;
963    } else {
964-      // second frame - how do we dispoase of the previous one?
965+      // second frame - how do we dispose of the previous one?
966       dispose = (g->eflags & 0x1C) >> 2;
967       pcount = g->w * g->h;
968
969@@ -6678,6 +6875,17 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i
970    }
971 }
972
973+static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)
974+{
975+   STBI_FREE(g->out);
976+   STBI_FREE(g->history);
977+   STBI_FREE(g->background);
978+
979+   if (out) STBI_FREE(out);
980+   if (delays && *delays) STBI_FREE(*delays);
981+   return stbi__errpuc("outofmem", "Out of memory");
982+}
983+
984 static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
985 {
986    if (stbi__gif_test(s)) {
987@@ -6687,6 +6895,12 @@ static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y,
988       stbi_uc *two_back = 0;
989       stbi__gif g;
990       int stride;
991+      int out_size = 0;
992+      int delays_size = 0;
993+
994+      STBI_NOTUSED(out_size);
995+      STBI_NOTUSED(delays_size);
996+
997       memset(&g, 0, sizeof(g));
998       if (delays) {
999          *delays = 0;
1000@@ -6703,22 +6917,31 @@ static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y,
1001             stride = g.w * g.h * 4;
1002
1003             if (out) {
1004-               void *tmp = (stbi_uc*) STBI_REALLOC( out, layers * stride );
1005-               if (NULL == tmp) {
1006-                  STBI_FREE(g.out);
1007-                  STBI_FREE(g.history);
1008-                  STBI_FREE(g.background);
1009-                  return stbi__errpuc("outofmem", "Out of memory");
1010+               void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );
1011+               if (!tmp)
1012+                  return stbi__load_gif_main_outofmem(&g, out, delays);
1013+               else {
1014+                   out = (stbi_uc*) tmp;
1015+                   out_size = layers * stride;
1016                }
1017-               else
1018-                  out = (stbi_uc*) tmp;
1019+
1020                if (delays) {
1021-                  *delays = (int*) STBI_REALLOC( *delays, sizeof(int) * layers );
1022+                  int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );
1023+                  if (!new_delays)
1024+                     return stbi__load_gif_main_outofmem(&g, out, delays);
1025+                  *delays = new_delays;
1026+                  delays_size = layers * sizeof(int);
1027                }
1028             } else {
1029                out = (stbi_uc*)stbi__malloc( layers * stride );
1030+               if (!out)
1031+                  return stbi__load_gif_main_outofmem(&g, out, delays);
1032+               out_size = layers * stride;
1033                if (delays) {
1034                   *delays = (int*) stbi__malloc( layers * sizeof(int) );
1035+                  if (!*delays)
1036+                     return stbi__load_gif_main_outofmem(&g, out, delays);
1037+                  delays_size = layers * sizeof(int);
1038                }
1039             }
1040             memcpy( out + ((layers - 1) * stride), u, stride );
1041@@ -6897,6 +7120,9 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re
1042    token += 3;
1043    width = (int) strtol(token, NULL, 10);
1044
1045+   if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
1046+   if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
1047+
1048    *x = width;
1049    *y = height;
1050
1051@@ -7039,9 +7265,10 @@ static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
1052
1053    info.all_a = 255;
1054    p = stbi__bmp_parse_header(s, &info);
1055-   stbi__rewind( s );
1056-   if (p == NULL)
1057+   if (p == NULL) {
1058+      stbi__rewind( s );
1059       return 0;
1060+   }
1061    if (x) *x = s->img_x;
1062    if (y) *y = s->img_y;
1063    if (comp) {
1064@@ -7107,8 +7334,8 @@ static int stbi__psd_is16(stbi__context *s)
1065        stbi__rewind( s );
1066        return 0;
1067    }
1068-   (void) stbi__get32be(s);
1069-   (void) stbi__get32be(s);
1070+   STBI_NOTUSED(stbi__get32be(s));
1071+   STBI_NOTUSED(stbi__get32be(s));
1072    depth = stbi__get16be(s);
1073    if (depth != 16) {
1074        stbi__rewind( s );
1075@@ -7187,7 +7414,6 @@ static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
1076 // Known limitations:
1077 //    Does not support comments in the header section
1078 //    Does not support ASCII image data (formats P2 and P3)
1079-//    Does not support 16-bit-per-channel
1080
1081 #ifndef STBI_NO_PNM
1082
1083@@ -7208,19 +7434,23 @@ static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req
1084    stbi_uc *out;
1085    STBI_NOTUSED(ri);
1086
1087-   if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n))
1088+   ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);
1089+   if (ri->bits_per_channel == 0)
1090       return 0;
1091
1092+   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
1093+   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
1094+
1095    *x = s->img_x;
1096    *y = s->img_y;
1097    if (comp) *comp = s->img_n;
1098
1099-   if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0))
1100+   if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
1101       return stbi__errpuc("too large", "PNM too large");
1102
1103-   out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0);
1104+   out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);
1105    if (!out) return stbi__errpuc("outofmem", "Out of memory");
1106-   stbi__getn(s, out, s->img_n * s->img_x * s->img_y);
1107+   stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8));
1108
1109    if (req_comp && req_comp != s->img_n) {
1110       out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
1111@@ -7296,11 +7526,19 @@ static int      stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
1112    stbi__pnm_skip_whitespace(s, &c);
1113
1114    maxv = stbi__pnm_getinteger(s, &c);  // read max value
1115-
1116-   if (maxv > 255)
1117-      return stbi__err("max value > 255", "PPM image not 8-bit");
1118+   if (maxv > 65535)
1119+      return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");
1120+   else if (maxv > 255)
1121+      return 16;
1122    else
1123-      return 1;
1124+      return 8;
1125+}
1126+
1127+static int stbi__pnm_is16(stbi__context *s)
1128+{
1129+   if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)
1130+	   return 1;
1131+   return 0;
1132 }
1133 #endif
1134
1135@@ -7356,6 +7594,9 @@ static int stbi__is_16_main(stbi__context *s)
1136    if (stbi__psd_is16(s))  return 1;
1137    #endif
1138
1139+   #ifndef STBI_NO_PNM
1140+   if (stbi__pnm_is16(s))  return 1;
1141+   #endif
1142    return 0;
1143 }
1144
1145diff --git a/thirdparty/stb/stb_image.patch b/thirdparty/stb/stb_image.patch
1146index 5153728..f1fee52 100644
1147--- a/thirdparty/stb/stb_image.patch
1148+++ b/thirdparty/stb/stb_image.patch
1149@@ -1,7 +1,7 @@
1150 diff -Naur upstream/stb_image.h zxing/stb_image.h
1151---- upstream/stb_image.h	2021-12-08 18:11:28.170529096 -0500
1152-+++ zxing/stb_image.h	2021-12-08 18:06:42.706717697 -0500
1153-@@ -1644,7 +1644,11 @@
1154+--- upstream/stb_image.h	2021-12-08 18:18:07.485461782 -0500
1155++++ zxing/stb_image.h	2021-12-08 18:18:29.596689004 -0500
1156+@@ -1725,7 +1725,11 @@
1157
1158  static stbi_uc stbi__compute_y(int r, int g, int b)
1159  {
1160--
11612.33.1
1162
1163