From 760c816161fdf75dca4427da55021f314f407965 Mon Sep 17 00:00:00 2001 From: Justin Israel Date: Thu, 4 Apr 2024 09:07:59 +1300 Subject: [PATCH] Check last error after query to FontMetrics to prevent panic (fixes #309) --- imagick/magick_wand.go | 6 ++++++ imagick/magick_wand_test.go | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/imagick/magick_wand.go b/imagick/magick_wand.go index 68cc8b3..3bb0d16 100644 --- a/imagick/magick_wand.go +++ b/imagick/magick_wand.go @@ -129,6 +129,9 @@ func (mw *MagickWand) QueryFontMetrics(dw *DrawingWand, textLine string) *FontMe cstext := C.CString(textLine) defer C.free(unsafe.Pointer(cstext)) cdoubles := C.MagickQueryFontMetrics(mw.mw, dw.dw, cstext) + if err := mw.GetLastError(); err != nil { + return nil + } runtime.KeepAlive(mw) runtime.KeepAlive(dw) defer relinquishMemory(unsafe.Pointer(cdoubles)) @@ -141,6 +144,9 @@ func (mw *MagickWand) QueryMultilineFontMetrics(dw *DrawingWand, textParagraph s cstext := C.CString(textParagraph) defer C.free(unsafe.Pointer(cstext)) cdoubles := C.MagickQueryMultilineFontMetrics(mw.mw, dw.dw, cstext) + if err := mw.GetLastError(); err != nil { + return nil + } runtime.KeepAlive(mw) runtime.KeepAlive(dw) defer relinquishMemory(unsafe.Pointer(cdoubles)) diff --git a/imagick/magick_wand_test.go b/imagick/magick_wand_test.go index 13eadb0..1e80846 100644 --- a/imagick/magick_wand_test.go +++ b/imagick/magick_wand_test.go @@ -101,6 +101,24 @@ func TestQueryFonts(t *testing.T) { } } +func TestQueryFontMetrics(t *testing.T) { + Initialize() + defer func(t *testing.T) { + checkGC(t) + }(t) + defer Terminate() + + mw := NewMagickWand() + // Create an empty wand. Don't ready anything. + //if err := mw.ReadImage("xc:black"); err != nil { + // panic(err) + //} + fonts := mw.QueryFontMetrics(NewDrawingWand(), "") + if fonts != nil { + t.Fatal("Expected a nil FontMetrics when passing a bad MagickWand") + } +} + func TestQueryFormats(t *testing.T) { Initialize() defer func(t *testing.T) {