From 94d0a6238e9573473d2cfdc74135305b2f6741f2 Mon Sep 17 00:00:00 2001
From: Sergey Poznyakoff <gray@gnu.org>
Date: Thu, 9 Jun 2022 22:44:26 +0300
Subject: [PATCH 05/14] Fix binary dump format for key and/or data of zero
 size.

Fixes https://puszcza.gnu.org.ua/bugs/?565

* src/gdbmexp.c (gdbm_export_to_file): Check for positive size before
attempting to write.
* src/gdbmimp.c (gdbm_import_from_file): Check for positive size before
attempting to read.
---
 src/gdbmexp.c | 4 ++--
 src/gdbmimp.c | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/gdbmexp.c b/src/gdbmexp.c
index 6646bba..6f20fe6 100644
--- a/src/gdbmexp.c
+++ b/src/gdbmexp.c
@@ -65,13 +65,13 @@ gdbm_export_to_file (GDBM_FILE dbf, FILE *fp)
 	  size = htonl (key.dsize);
 	  if (fwrite (&size, sizeof (size), 1, fp) != 1)
 	    goto write_fail;
-	  if (fwrite (key.dptr, key.dsize, 1, fp) != 1)
+	  if (key.dsize > 0 && fwrite (key.dptr, key.dsize, 1, fp) != 1)
 	    goto write_fail;
 
 	  size = htonl (data.dsize);
 	  if (fwrite (&size, sizeof (size), 1, fp) != 1)
 	    goto write_fail;
-	  if (fwrite (data.dptr, data.dsize, 1, fp) != 1)
+	  if (data.dsize > 0 && fwrite (data.dptr, data.dsize, 1, fp) != 1)
 	    goto write_fail;
  	}
       
diff --git a/src/gdbmimp.c b/src/gdbmimp.c
index be98ed7..73c0b74 100644
--- a/src/gdbmimp.c
+++ b/src/gdbmimp.c
@@ -113,7 +113,7 @@ gdbm_import_from_file (GDBM_FILE dbf, FILE *fp, int flag)
       key.dsize = (int) size;
 
       /* Read the data. */
-      if (fread (&rsize, sizeof (rsize), 1, fp) != 1)
+      if (size > 0 && fread (&rsize, sizeof (rsize), 1, fp) != 1)
 	{
 	  ec = GDBM_FILE_READ_ERROR;
 	  break;
@@ -135,7 +135,7 @@ gdbm_import_from_file (GDBM_FILE dbf, FILE *fp, int flag)
 	      break;
 	    }
 	}
-      if (fread (dbuffer, size, 1, fp) != 1)
+      if (size > 0 && fread (dbuffer, size, 1, fp) != 1)
 	{
 	  ec = GDBM_FILE_READ_ERROR;
 	  break;
-- 
2.33.0

