From 1634068a27a93898908802f514ae41c1a3aa3bf9 Mon Sep 17 00:00:00 2001
From: Dan Kennedy <danielk1977@gmail.com>
Date: Thu, 17 Jan 2019 19:11:10 +0000
Subject: [PATCH 0787/1009] Fix a buffer overwrite that could occur when
 running an fts5 prefix query against a corrupt database.

https://github.com/mackyle/sqlite/commit/1634068a27a93898908802f514ae41c1a3aa3bf9

---
 ext/fts5/fts5_index.c           |  11 +-
 1 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/ext/fts5/fts5_index.c b/ext/fts5/fts5_index.c
index 426cf61..259ae35 100644
--- a/ext/fts5/fts5_index.c
+++ b/ext/fts5/fts5_index.c
@@ -4959,6 +4959,8 @@ static void fts5MergePrefixLists(
         int iOff2 = 0;
         u8 *a1 = &i1.aPoslist[i1.nSize];
         u8 *a2 = &i2.aPoslist[i2.nSize];
+        int nCopy;
+        u8 *aCopy;
 
         i64 iPrev = 0;
         Fts5PoslistWriter writer;
@@ -5002,11 +5004,16 @@ static void fts5MergePrefixLists(
           if( iPos1!=iPrev ){
             sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
           }
-          fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
+          aCopy = &a1[iOff1];
+          nCopy = i1.nPoslist - iOff1;
         }else{
           assert( iPos2>=0 && iPos2!=iPrev );
           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
-          fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
+          aCopy = &a2[iOff2];
+          nCopy = i2.nPoslist - iOff2;
+        }
+        if( nCopy>0 ){
+          fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
         }
 
         /* WRITEPOSLISTSIZE */
-- 
1.8.3.1

