From dc17ab3fe8cd43eeaf3f2da9bcaa30a2be69e57b Mon Sep 17 00:00:00 2001
From: Zdenek Hutyra <zhutyra@centrum.cz>
Date: Mon, 13 Jan 2025 09:15:01 +0000
Subject: Bug 708241: Fix potential Buffer overflow with DollarBlend

During serializing a multiple master font for passing to Freetype.

Use CVE-2025-27830
---
 base/write_t1.c | 9 +++++----
 psi/zfapi.c     | 9 +++++++--
 2 files changed, 12 insertions(+), 6 deletions(-)

diff --git a/base/write_t1.c b/base/write_t1.c
index 50af7ea..1b17aae 100644
--- a/base/write_t1.c
+++ b/base/write_t1.c
@@ -628,6 +628,7 @@ write_main_dictionary(gs_fapi_font * a_fapi_font, WRF_output * a_output, int Wri
     WRF_wbyte(a_fapi_font->memory, a_output, '\n');
     if (is_MM_font(a_fapi_font)) {
         short x, x2;
+        unsigned short ux;
         float x1;
         uint i, j, entries;
         char Buffer[255];
@@ -759,16 +760,16 @@ write_main_dictionary(gs_fapi_font * a_fapi_font, WRF_output * a_output, int Wri
          */
         code = a_fapi_font->get_word(a_fapi_font,
                                    gs_fapi_font_feature_DollarBlend_length,
-                                   0, (unsigned short *)&x);
+                                   0, &ux);
         if (code < 0)
             return code;
 
-        if (x > 0) {
+        if (ux > 0) {
             int len;
             WRF_wstring(a_fapi_font->memory, a_output, "/$Blend {");
 
             if (a_output->m_count)
-                a_output->m_count += x;
+                a_output->m_count += ux;
             len = a_fapi_font->get_proc(a_fapi_font,
                                       gs_fapi_font_feature_DollarBlend, 0,
                                       (char *)a_output->m_pos);
diff --git a/psi/zfapi.c b/psi/zfapi.c
index 6927e60..05bf9dc 100644
--- a/psi/zfapi.c
+++ b/psi/zfapi.c
@@ -683,7 +683,7 @@ FAPI_FF_get_word(gs_fapi_font *ff, gs_fapi_font_feature var_id, int index, unsig
                 }
                 for (i = 0; i < r_size(DBlend); i++) {
                     if (array_get(ff->memory, DBlend, i, &Element) < 0) {
-                        *ret = 0;
+                        length = 0;
                         break;
                     }
                     switch (r_btype(&Element)) {
@@ -710,7 +710,12 @@ FAPI_FF_get_word(gs_fapi_font *ff, gs_fapi_font_feature var_id, int index, unsig
                         default:
                             break;
                     }
-                }
+
+                    if (length > max_ushort) {
+                        length = 0;
+                        break;
+                    }
+                 }
                 *ret = length;
                 break;
             }
