Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion llamafile/chatbot_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,14 @@ void on_upload(const std::vector<std::string> &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)) {
Expand Down
69 changes: 60 additions & 9 deletions llamafile/image.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions llamafile/image.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
28 changes: 28 additions & 0 deletions tests/BUILD.mk
Original file line number Diff line number Diff line change
Expand Up @@ -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)
# ==============================================================================
Expand Down Expand Up @@ -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
Loading