diff --git a/llamafile/chatbot_file.cpp b/llamafile/chatbot_file.cpp index 0e35297997..0623581b68 100644 --- a/llamafile/chatbot_file.cpp +++ b/llamafile/chatbot_file.cpp @@ -71,7 +71,14 @@ void on_upload(const std::vector &args) { err("%s: need --mmproj model to process images", path); return; } - print_image(1, content, 80); + // Only a preview is drawn; the original bytes are what get sent to + // the model below. print_image() won't draw an image whose aspect + // ratio is too extreme to fit the terminal, and it reports that the + // same way as a failed resize or write, so the cause is a guess. + if (print_image(1, content, 80) < 0) + err("%s: no preview drawn (the image may be too tall or narrow for" + " this terminal), it will still be sent to the model", + path); convert_image_to_uri(&markdown, content); } else { if (has_binary(content)) { diff --git a/llamafile/image.cpp b/llamafile/image.cpp index d846c0aee8..6df8dedd21 100644 --- a/llamafile/image.cpp +++ b/llamafile/image.cpp @@ -213,8 +213,48 @@ const char *get_image_mime(ImageType type) { } } +/** + * Scales image dimensions to fit the terminal, preserving aspect ratio. + * + * Returns false if the image can't be drawn at all, either because its + * dimensions are nonsensical or because its aspect ratio is so extreme that + * fitting it in the box would leave nothing to draw. On success the width is + * at most @p max_width columns and the height is an even number between 2 and + * @p max_rows * 2 image rows, since half blocks draw two image rows per line + * of text. The floor of two means an image too wide to fill even one line of + * text still gets one, at the full width, rather than scaling down to nothing. + * The upper bound is what keeps print_image()'s buffer bounded, so all the + * arithmetic here is done in 64-bit: an image's dimensions are whatever the + * file says they are, and one-pixel-wide images a million pixels tall are both + * valid and decodable by our image library. + */ +bool image_scaled_dims(int width, int height, int max_width, int max_rows, int *xn, int *yn) { + if (width <= 0 || height <= 0 || max_width <= 0 || max_rows <= 0) + return false; + int64_t x = max_width; + int64_t y = ((int64_t)height * x) / width; + int64_t ycap = (int64_t)max_rows * 2; + if (y > ycap) { + // taller than we can draw, so shrink the width too rather than + // squashing the image into a stripe. past that, nothing is left. + y = ycap; + x = ((int64_t)width * y) / height; + if (x < 2) + return false; + } + x = MIN(MAX(x, 1), (int64_t)max_width); + y = MIN(MAX(y, 2), ycap); + *xn = (int)x; + *yn = (int)((y + 1) & ~1LL); // round up to even number + return true; +} + /** * Prints image to terminal. + * + * Only a preview is drawn here, and it's scaled to fit the terminal; the + * original bytes are what get sent to the model. @see image_scaled_dims for + * the bounds that keep this from allocating unbounded memory. */ int print_image(int fd, const std::string_view &image, int max_width) { @@ -230,16 +270,27 @@ int print_image(int fd, const std::string_view &image, int max_width) { struct winsize ws = {24, 80}; tcgetwinsize(fd, &ws); - // calculate new dimensions preserving aspect ratio - int xn = MIN(max_width, ws.ws_col); - int yn = (height * xn) / width; // *2 because we use half blocks - yn = (yn + 1) & -2; // round up to even number + // calculate new dimensions preserving aspect ratio. a terminal can report + // any width, including zero, so it can only ever lower the cap. + int columns = MIN(MAX(max_width, 1), MAX((int)ws.ws_col, 1)); + int xn, yn; + if (!image_scaled_dims(width, height, columns, kImageMaxRows, &xn, &yn)) { + stbi_image_free(img); + return -1; + } - // resize image - unsigned char *resized = new unsigned char[xn * yn * 3]; - stbir_resize_uint8_srgb(img, width, height, 0, // - resized, xn, yn, 0, // - STBIR_RGB); + // resize image. stbir writes xn * yn * 3 bytes into our buffer, which + // image_scaled_dims keeps bounded, and we compute the size in size_t rather + // than int so it can't wrap. stbir returns null if it didn't fill the + // buffer, and we'd otherwise be printing uninitialized memory. + unsigned char *resized = new unsigned char[(size_t)xn * (size_t)yn * 3]; + if (!stbir_resize_uint8_srgb(img, width, height, 0, // + resized, xn, yn, 0, // + STBIR_RGB)) { + stbi_image_free(img); + delete[] resized; + return -1; + } stbi_image_free(img); // convert image to string using half blocks diff --git a/llamafile/image.h b/llamafile/image.h index 3160115df7..df9f301c17 100644 --- a/llamafile/image.h +++ b/llamafile/image.h @@ -50,7 +50,21 @@ enum ImageType { ImageType get_image_type(const std::string_view &); bool is_image(const std::string_view &); const char *get_image_mime(ImageType); + +/** + * Maximum number of lines of terminal print_image() will draw. + * + * Half blocks draw two lines of image pixels per line of text, so this caps + * the height of the scaled image at kImageMaxRows * 2 pixels. Along with the + * width cap of max_width columns, that bounds print_image()'s memory for any + * image an attacker can hand us: images exist whose aspect ratio is so extreme + * that scaling them to the terminal would otherwise need gigabytes, or wrap a + * 32-bit size computation and write far past a small buffer. + */ +inline constexpr int kImageMaxRows = 200; + int print_image(int, const std::string_view &, int); +bool image_scaled_dims(int, int, int, int, int *, int *); void convert_image_to_uri(std::string *, const std::string_view &); } // namespace lf diff --git a/tests/BUILD.mk b/tests/BUILD.mk index b6ce417fe3..af96b3fa9e 100644 --- a/tests/BUILD.mk +++ b/tests/BUILD.mk @@ -49,6 +49,33 @@ o/$(MODE)/tests/extract_data_uris_test: \ @mkdir -p $(@D) $(CXX) $(LDFLAGS) -o $@ $^ $(LDLIBS) +# ============================================================================== +# Test: print_image_test (uploaded image preview memory bounds) +# ============================================================================== +# +# print_image() scaled an uploaded image to the terminal with no cap on the +# height and computed the destination size in int, so a valid PNG one pixel wide +# and 223,697 pixels tall wrapped 80 * 17,895,760 * 3 down to 15,104 bytes and +# the resize library wrote the full 4.29 GB past that buffer. Asserts the +# destination stays bounded for any dimensions an image claims. Links the same +# objects extract_data_uris_test needs for image.o. + +PRINT_IMAGE_TEST_DEPS := \ + o/$(MODE)/llamafile/image.o \ + o/$(MODE)/llamafile/xterm.o \ + o/$(MODE)/llamafile/string.o \ + o/$(MODE)/third_party/stb/stb.a + +o/$(MODE)/tests/print_image_test.o: tests/print_image_test.cpp + @mkdir -p $(@D) + $(CXX) $(CXXFLAGS) $(TESTS_CPPFLAGS) -c -o $@ $< + +o/$(MODE)/tests/print_image_test: \ + o/$(MODE)/tests/print_image_test.o \ + $(PRINT_IMAGE_TEST_DEPS) + @mkdir -p $(@D) + $(CXX) $(LDFLAGS) -o $@ $^ $(LDLIBS) + # ============================================================================== # Test: fa_helpers_test (issue #975 numerical equivalence) # ============================================================================== @@ -205,5 +232,6 @@ o/$(MODE)/tests: \ o/$(MODE)/tests/extract_data_uris_test.runs \ o/$(MODE)/tests/fa_helpers_test.runs \ o/$(MODE)/tests/gpu_backend_test.runs \ + o/$(MODE)/tests/print_image_test.runs \ o/$(MODE)/tests/sandbox_test.runs \ o/$(MODE)/tests/transcribefile_smoke.runs diff --git a/tests/print_image_test.cpp b/tests/print_image_test.cpp new file mode 100644 index 0000000000..7f44822031 --- /dev/null +++ b/tests/print_image_test.cpp @@ -0,0 +1,362 @@ +// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*- +// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi +// +// Copyright 2026 Mozilla Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// print_image() previews an uploaded image in the terminal by scaling it with +// half blocks. It used to compute the destination size in int with no cap on +// the height, so an image one pixel wide and 223,697 pixels tall (a valid PNG +// of under a kilobyte) wrapped +// +// 80 columns * 17,895,760 image rows * 3 channels = 4,294,982,400 +// +// down to 15,104 bytes, and the resize library then wrote the full 4.29 GB +// past the end of that buffer, killing the chat and, in combined mode, the +// built-in server with it. These tests assert the destination print_image() +// asks the resize library to fill stays bounded no matter what dimensions an +// image claims, so its buffer is always big enough. +// +// The dimension math is tested directly, which needs no image files; the last +// test drives print_image() itself on PNG images synthesized in memory. + +#include "image.h" +#include "macros.h" +#include +#include +#include +#include +#include +#include + +using namespace lf; + +static int test_count = 0; +static int fail_count = 0; + +#define TEST(name) \ + static void test_##name(); \ + static struct TestRegister_##name { \ + TestRegister_##name() { test_##name(); } \ + } test_register_##name; \ + static void test_##name() + +#define CHECK(cond, msg) \ + do { \ + test_count++; \ + if (!(cond)) { \ + fprintf(stderr, "FAIL: %s\n expected: %s\n", msg, #cond); \ + fail_count++; \ + } \ + } while (0) + +#define CHECK_EQ(expected, actual, msg) \ + do { \ + test_count++; \ + if ((expected) != (actual)) { \ + fprintf(stderr, "FAIL: %s\n expected: %s = %d\n actual: %d\n", \ + msg, #expected, (int)(expected), (int)(actual)); \ + fail_count++; \ + } \ + } while (0) + +// what print_image() passes to the resize library, in bytes +static size_t dest_bytes(int xn, int yn) { + return (size_t)xn * (size_t)yn * 3; +} + +// the largest destination print_image() may ever ask for: max_width columns of +// half blocks, kImageMaxRows lines tall, and half blocks draw two image rows +static size_t max_dest_bytes(int max_width) { + return (size_t)max_width * 2 * kImageMaxRows * 3; +} + +// print_image() derives its width cap from the terminal, and a terminal can +// report anything as its width, including zero +static int columns(int max_width, int ws_col) { + return MIN(MAX(max_width, 1), MAX(ws_col, 1)); +} + +// Asserts an image is either refused, or drawn within max_dest_bytes() by a +// size computation that could not have wrapped had it been done in int. +static void check_bounded(int width, int height, int max_width, int ws_col, const char *what) { + int cols = columns(max_width, ws_col); + int xn = -1, yn = -1; + test_count++; + if (!image_scaled_dims(width, height, cols, kImageMaxRows, &xn, &yn)) + return; // refused: nothing allocated, nothing drawn, nothing to overflow + bool bad = dest_bytes(xn, yn) > max_dest_bytes(max_width) || + (long long)xn * yn * 3 > INT_MAX || // would wrap if computed in int + xn < 1 || xn > max_width || + yn < 2 || (yn & 1) || yn > 2 * kImageMaxRows; + if (bad) { + fprintf(stderr, "FAIL: %s (%dx%d at %d columns) drew %dx%d = %zu bytes\n", + what, width, height, cols, xn, yn, dest_bytes(xn, yn)); + fail_count++; + } +} + +// heights chosen around the old wrap point: at 80 columns, a 1-pixel-wide image +// wrapped xn * yn * 3 once it passed 111,849 rows tall, and 223,697 is the +// reported proof of concept, whose wrap landed on a small positive size. +static const int kHeights[] = { + 100000, 111849, 111850, 150000, 223697, 447393, 800000, + 1 << 24, // our image library's own height limit + 1 << 28, // past what it decodes at all, but the helper shouldn't care +}; + +// a terminal reports its width; llamafile used to scale with it and could be +// pushed off a cliff at any width, so check the whole range +static const int kCols[] = {0, 1, 10, 40, 80, 200}; + +TEST(heights_that_wrapped_are_refused_or_bounded) { + for (int h : kHeights) + for (int c : kCols) { + check_bounded(1, h, 80, c, "1-pixel-wide image"); + check_bounded(2, h, 80, c, "2-pixel-wide image"); + check_bounded(3, h, 80, c, "3-pixel-wide image"); + } +} + +TEST(arbitrary_dimensions_are_refused_or_bounded) { + static const int dims[] = {1, 2, 3, 7, 64, 800, 4096, 100000, 1 << 20}; + for (int w : dims) + for (int h : dims) + for (int c : kCols) + check_bounded(w, h, 80, c, "arbitrary dimensions"); +} + +TEST(width_caps_are_honored) { + // /upload asks for 80 columns, but print_image() takes the cap as an + // argument, and a caller asking for more shouldn't loosen the bound + static const int caps[] = {1, 2, 8, 80, 1000}; + for (int cap : caps) + for (int w : {1, 2, 64, 1920}) + for (int h : kHeights) + for (int c : kCols) + check_bounded(w, h, cap, c, "arbitrary width cap"); +} + +TEST(refused_images_are_reported) { + int xn, yn; + + // the reported proof of concept, at the 80 columns /upload draws at + CHECK(!image_scaled_dims(1, 223697, 80, kImageMaxRows, &xn, &yn), + "1x223697 must not be drawn"); + CHECK(!image_scaled_dims(1, 223697, columns(80, 40), kImageMaxRows, &xn, &yn), + "1x223697 must not be drawn on a narrow terminal either"); + + // an image is refused once fitting it in kImageMaxRows lines would leave it + // narrower than two columns, i.e. past an aspect ratio of kImageMaxRows:1 + CHECK(image_scaled_dims(400, 80000, 80, kImageMaxRows, &xn, &yn), "200:1 still draws"); + CHECK_EQ(2, xn, "at the ratio limit only two columns survive"); + CHECK_EQ(400, yn, "at the ratio limit the height is capped at kImageMaxRows * 2"); + CHECK(!image_scaled_dims(400, 80001, 80, kImageMaxRows, &xn, &yn), + "past the ratio limit nothing is left to draw"); + + // the terminal only ever lowers the cap, so it can't be the reason an + // image is refused when there's room to draw it + CHECK(image_scaled_dims(640, 480, columns(80, 1), kImageMaxRows, &xn, &yn), + "a one-column terminal still draws"); + CHECK_EQ(1, xn, "one column terminal draws one column"); + CHECK_EQ(2, yn, "two image rows per line of text"); +} + +TEST(ordinary_images_are_unchanged) { + // these are what print_image() drew before the height cap existed, so + // previews of real images don't move + struct { int w, h, xn, yn; } cases[] = { + {1920, 1080, 80, 46}, + {1080, 2400, 80, 178}, + {800, 100, 80, 10}, + {640, 480, 80, 60}, + {320, 240, 80, 60}, + {1, 1, 80, 80}, + {4096, 4096, 80, 80}, + {1024, 512, 80, 40}, + }; + for (const auto &c : cases) { + int xn = 0, yn = 0; + CHECK(image_scaled_dims(c.w, c.h, 80, kImageMaxRows, &xn, &yn), + "ordinary images are still drawn"); + CHECK_EQ(c.xn, xn, "width unchanged for ordinary images"); + CHECK_EQ(c.yn, yn, "height unchanged for ordinary images"); + } +} + +TEST(capped_images_keep_aspect_ratio) { + int xn = 0, yn = 0; + CHECK(image_scaled_dims(1280, 10000, 80, kImageMaxRows, &xn, &yn), + "a tall capture is still drawn"); + CHECK_EQ(51, xn, "width shrinks along with a capped height"); + CHECK_EQ(400, yn, "height capped at kImageMaxRows * 2"); + double want = (double)1280 / 10000, got = (double)xn / yn; + CHECK(std::fabs(got - want) < want * 0.02, "aspect ratio kept to within 2%"); +} + +TEST(very_wide_images_draw_one_line) { + // the mirror image of the tall case is never refused: a scaled height that + // rounds down to zero used to draw nothing at all, and the floor of two + // image rows now gives such an image one line of text at the full width + struct { int w, h; } cases[] = {{1000, 10}, {8000, 99}, {100000, 1}, {1 << 24, 1}}; + for (const auto &c : cases) { + int xn = 0, yn = 0; + CHECK(image_scaled_dims(c.w, c.h, 80, kImageMaxRows, &xn, &yn), + "a very wide image is still drawn"); + CHECK_EQ(80, xn, "a very wide image keeps the full width"); + CHECK_EQ(2, yn, "a very wide image gets one line of text"); + } +} + +TEST(nonsensical_inputs) { + int xn = -1, yn = -1; + CHECK(!image_scaled_dims(0, 100, 80, kImageMaxRows, &xn, &yn), "width 0"); + CHECK(!image_scaled_dims(100, 0, 80, kImageMaxRows, &xn, &yn), "height 0"); + CHECK(!image_scaled_dims(-100, 100, 80, kImageMaxRows, &xn, &yn), "negative width"); + CHECK(!image_scaled_dims(100, -100, 80, kImageMaxRows, &xn, &yn), "negative height"); + CHECK(!image_scaled_dims(100, 100, 0, kImageMaxRows, &xn, &yn), "width cap 0"); + CHECK(!image_scaled_dims(100, 100, 80, 0, &xn, &yn), "row cap 0"); + CHECK_EQ(-1, xn, "no dimensions written when refused"); + CHECK_EQ(-1, yn, "no dimensions written when refused"); +} + +// Our build of the image library has PNM, TGA, BMP and the rest compiled out +// (see third_party/stb/stb_image.c), and GIF caps dimensions at 16 bits, so +// PNG is the format to synthesize: it's what /upload accepts, it's what the +// bug was reported on, and deflate's uncompressed blocks let us build one from +// raw bytes without a compression library. The image is 8-bit grayscale, which +// the library converts to RGB because print_image() asks for three channels. +static unsigned crc32_of(const unsigned char *p, size_t n) { + static unsigned tab[256]; + for (unsigned i = 0; i < 256; ++i) { + unsigned c = i; + for (int k = 0; k < 8; ++k) + c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1); + tab[i] = c; + } + unsigned crc = 0xFFFFFFFFu; + for (size_t i = 0; i < n; ++i) + crc = tab[(crc ^ p[i]) & 0xFF] ^ (crc >> 8); + return crc ^ 0xFFFFFFFFu; +} + +static unsigned adler32_of(const unsigned char *p, size_t n) { + unsigned a = 1, b = 0; + for (size_t i = 0; i < n; ++i) { + a += p[i]; + if (a >= 65521) + a -= 65521; + b += a; + if (b >= 65521) + b -= 65521; + } + return (b << 16) | a; +} + +// a valid zlib stream of uncompressed deflate blocks: no matches, no Huffman +static std::string deflate_uncompressed(const std::string &raw) { + std::string z = "\x78\x01"; // zlib header; CMF=120 and FLG=1 pass its checksum + for (size_t i = 0; i < raw.size(); i += 65535) { + unsigned len = (unsigned)MIN((size_t)65535, raw.size() - i); + bool last = i + len >= raw.size(); + unsigned nlen = len ^ 0xffff; + char blk[5] = { + (char)(last ? 1 : 0), // BFINAL bit, BTYPE=00 + (char)(len & 255), (char)(len >> 8), // little-endian LEN + (char)(nlen & 255), (char)(nlen >> 8), // and its complement + }; + z.append(blk, sizeof(blk)); + z.append(raw.data() + i, len); + } + unsigned ad = adler32_of((const unsigned char *)raw.data(), raw.size()); + char trailer[4] = {(char)(ad >> 24), (char)(ad >> 16), (char)(ad >> 8), (char)ad}; // big-endian + z.append(trailer, sizeof(trailer)); + return z; +} + +static void png_chunk(std::string *png, const char *type, const std::string &data) { + unsigned len = (unsigned)data.size(); + char head[4] = {(char)(len >> 24), (char)(len >> 16), (char)(len >> 8), (char)len}; + std::string payload(type, 4); + payload += data; + unsigned crc = crc32_of((const unsigned char *)payload.data(), payload.size()); + char tail[4] = {(char)(crc >> 24), (char)(crc >> 16), (char)(crc >> 8), (char)crc}; + png->append(head, sizeof(head)); + png->append(payload); + png->append(tail, sizeof(tail)); +} + +static std::string make_image(int w, int h) { + std::string raw; + raw.reserve((size_t)(w + 1) * h); + for (int y = 0; y < h; ++y) { + raw += '\0'; // filter type 0: no filtering + raw.append((size_t)w, '\x40'); + } + std::string idat = deflate_uncompressed(raw); + + std::string ihdr; + unsigned dims[2] = {(unsigned)w, (unsigned)h}; + for (int i = 0; i < 2; ++i) { + ihdr += (char)(dims[i] >> 24); + ihdr += (char)(dims[i] >> 16); + ihdr += (char)(dims[i] >> 8); + ihdr += (char)dims[i]; + } + const char fields[] = {8, 0, 0, 0, 0}; // bit depth, color type, compression, filter, interlace + ihdr.append(fields, sizeof(fields)); + + std::string png = "\x89PNG\r\n\x1a\n"; + png_chunk(&png, "IHDR", ihdr); + png_chunk(&png, "IDAT", idat); + png_chunk(&png, "IEND", std::string()); + return png; +} + +TEST(print_image_end_to_end) { + std::string tall = make_image(1, 223697); + std::string small = make_image(320, 240); + + // is_image() is what /upload checks before drawing, and it accepts the + // tall image: the bound has to hold up all the way through print_image + CHECK(is_image(tall), "is_image accepts a 1x223697 PNG"); + CHECK(is_image(small), "is_image accepts a 320x240 PNG"); + + int fd = open("/dev/null", O_WRONLY); + CHECK(fd >= 0, "opened /dev/null"); + if (fd < 0) + return; + + // print_image() gets the terminal's size from fd; /dev/null has none, so it + // falls back to its 80-column default and these are the 80-column cases + CHECK_EQ(-1, print_image(fd, tall, 80), "print_image refuses 1x223697"); + CHECK(print_image(fd, small, 80) > 0, "print_image draws a 320x240 image"); + CHECK(print_image(fd, make_image(1000, 10), 80) > 0, "print_image draws a 1000x10 image"); + close(fd); +} + +int main(int argc, char *argv[]) { + (void)argc; + (void)argv; + + fprintf(stderr, "Running print_image tests...\n"); + + if (fail_count > 0) { + fprintf(stderr, "\n%d/%d tests FAILED\n", fail_count, test_count); + return 1; + } + + fprintf(stderr, "All %d tests PASSED\n", test_count); + return 0; +}