From 3eac590ef9784a30f4a2aade08668b537fec9ebf Mon Sep 17 00:00:00 2001
From: Kirill Shcherbatov <kshcherbatov@tarantool.org>
Date: Tue, 23 Apr 2019 11:11:52 +0300
Subject: [PATCH] box: fix empty tuple invalid update

The tuple:update() used to work incorrectly in case of empty
tuple produced with box.tuple.new{} because update_create_rope
unconditionally initialized a new rope with [tuple_data,
mp_next(tuple_data)] field that might not exists.

Closes #4041
---
 src/box/tuple_update.c  |  2 ++
 test/box/tuple.result   | 21 +++++++++++++++++++++
 test/box/tuple.test.lua | 10 ++++++++++
 3 files changed, 33 insertions(+)

diff --git a/src/box/tuple_update.c b/src/box/tuple_update.c
index 01c55fb1a7..8490732588 100644
--- a/src/box/tuple_update.c
+++ b/src/box/tuple_update.c
@@ -834,6 +834,8 @@ update_create_rope(struct tuple_update *update, const char *tuple_data,
 		return -1;
 	const char *field = tuple_data;
 	const char *end = tuple_data_end;
+	if (field == end)
+		return 0;
 
 	/* Add first field to rope */
 	mp_next(&tuple_data);
diff --git a/test/box/tuple.result b/test/box/tuple.result
index 82ad8404d2..2561ebc35c 100644
--- a/test/box/tuple.result
+++ b/test/box/tuple.result
@@ -859,6 +859,27 @@ t
 t = nil
 ---
 ...
+--
+-- gh-4041: Invalid field on empty tuple update.
+--
+t = box.tuple.new{}
+---
+...
+t:update({{'=', 1, 1}})
+---
+- [1]
+...
+t:upsert({{'=', 1, 1}})
+---
+- [1]
+...
+t:update({{'+', 1, 1}})
+---
+- error: Field 1 was not found in the tuple
+...
+t = nil
+---
+...
 --------------------------------------------------------------------------------
 -- test msgpack.encode + tuple
 --------------------------------------------------------------------------------
diff --git a/test/box/tuple.test.lua b/test/box/tuple.test.lua
index 8030b08843..b0a4ab173c 100644
--- a/test/box/tuple.test.lua
+++ b/test/box/tuple.test.lua
@@ -270,6 +270,16 @@ t = box.tuple.new(require('yaml').decode("[17711728, {1000: 'xxx'}]"))
 t:update({{'=', 2, t[2]}})
 t
 t = nil
+
+--
+-- gh-4041: Invalid field on empty tuple update.
+--
+t = box.tuple.new{}
+t:update({{'=', 1, 1}})
+t:upsert({{'=', 1, 1}})
+t:update({{'+', 1, 1}})
+t = nil
+
 --------------------------------------------------------------------------------
 -- test msgpack.encode + tuple
 --------------------------------------------------------------------------------
-- 
GitLab