From 63022a01d18c9d6168aa3bf10e00e63e42d3bc88 Mon Sep 17 00:00:00 2001
From: Andrey <amborodin@acm.org>
Date: Mon, 1 Apr 2019 21:34:51 +0500
Subject: [PATCH] Use fast memcpy in pglz decompression

---
 src/common/pg_lzcompress.c | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/src/common/pg_lzcompress.c b/src/common/pg_lzcompress.c
index 97b0e40e40..29e6c29bc9 100644
--- a/src/common/pg_lzcompress.c
+++ b/src/common/pg_lzcompress.c
@@ -731,16 +731,22 @@ pglz_decompress(const char *source, int32 slen, char *dest,
 
 				/*
 				 * Now we copy the bytes specified by the tag from OUTPUT to
-				 * OUTPUT. It is dangerous and platform dependent to use
-				 * memcpy() here, because the copied areas could overlap
-				 * extremely!
+				 * OUTPUT. It is dangerous to use direct memcpy() here, because
+				 * the copied areas could overlap. To handle this overlap
+				 * appropriatley we break copied region into non-overlapping
+				 * regions.
 				 */
 				len = Min(len, destend - dp);
-				while (len--)
+				while (off <= len)
 				{
-					*dp = dp[-off];
-					dp++;
+					memcpy(dp, dp - off, off);
+					len -= off;
+					dp += off;
+					off *= 2;
 				}
+				if (len)
+					memcpy(dp, dp - off, len);
+				dp += len;
 			}
 			else
 			{
-- 
2.20.1

