From 6412131325fb2266c3faf0faea93c1d5a4e479a9 Mon Sep 17 00:00:00 2001
From: Peibao Liu <peibao.liu@windriver.com>
Date: Fri, 29 May 2020 02:04:15 -0400
Subject: [PATCH] Defensive code that tries to prevent a recurrence of
 problems.

port from:
https://www.sqlite.org/src/info/572105de1d44bca4

Signed-off-by: Peibao Liu <peibao.liu@windriver.com>
---
 src/expr.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff -Naur c/src/expr.c d/src/expr.c
--- c/src/expr.c	2020-06-23 03:05:10.871000000 +0000
+++ d/src/expr.c	2020-06-23 03:15:14.426000000 +0000
@@ -3542,7 +3542,10 @@
   switch( op ){
     case TK_AGG_COLUMN: {
       AggInfo *pAggInfo = pExpr->pAggInfo;
-      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
+      struct AggInfo_col *pCol;
+      assert( pAggInfo!=0 );
+      assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
+      pCol = &pAggInfo->aCol[pExpr->iAgg];
       if( !pAggInfo->directMode ){
         assert( pCol->iMem>0 );
         return pCol->iMem;
@@ -3761,7 +3764,10 @@
     }
     case TK_AGG_FUNCTION: {
       AggInfo *pInfo = pExpr->pAggInfo;
-      if( pInfo==0 ){
+      if( pInfo==0
+       || NEVER(pExpr->iAgg<0)
+       || NEVER(pExpr->iAgg>=pInfo->nFunc)
+      ){
         assert( !ExprHasProperty(pExpr, EP_IntValue) );
         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
       }else{
