There is an issue where ReadDiceFile() enters an infinite loop if the
dice file does not contain a single valid dice roll (1 to 6).

In the current implementation, when EOF is reached, the file rewinds to
the beginning to read again. However, for empty files or files
containing no values from 1 to 6, it reaches EOF again and repeatedly
loops the rewind process.

This has been fixed so that a maximum of one rewind is allowed per
ReadDiceFile() call. If a valid roll is still not obtained after the
rewind and EOF is reached again, (unsigned int)-1 is returned.

The normal cyclic usage of dice files remains unchanged. Even if there
are no valid values from the current position to EOF, if a valid value
is found after the rewind, that value is returned.

Since the handling for when ReadDiceFile() returns a failure is already
implemented in RollDice(), no new fallback processing or error messages
have been added this time.

The same issue occurs with empty files, so it can be confirmed that even
with a 0-byte dice file, it does not result in an infinite loop and
proceeds to the existing fallback processing.

Best regards,
-- 
TAKAHASHI Kaoru
>From 8ee75bbf6f6d94563971a259b864adb8544c22cb Mon Sep 17 00:00:00 2001
From: TAKAHASHI Kaoru <[email protected]>
Date: Sun, 23 Aug 2026 23:19:38 +0900
Subject: [PATCH] ReadDiceFile(): Fix infinite loop on invalid dice files

---
 dice.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/dice.c b/dice.c
index 872e90ea..b68c0670 100644
--- a/dice.c
+++ b/dice.c
@@ -854,6 +854,7 @@ ReadDiceFile(rngcontext * rngctx)
 
     unsigned char uch;
     size_t n;
+    int fRewound = FALSE;
 
     if (rngctx->fDice == NULL)
         return (unsigned int) (-1);
@@ -865,9 +866,13 @@ ReadDiceFile(rngcontext * rngctx)
 
         if (feof(rngctx->fDice)) {
             /* end of file */
+            if (fRewound)
+                return (unsigned int) (-1);
+
             g_print(_("Rewinding dice file (%s)"), rngctx->szDiceFilename);
             g_printf("\n");
             fseek(rngctx->fDice, 0, SEEK_SET);
+            fRewound = TRUE;
         } else if (n != 1) {
             g_printerr("%s", rngctx->szDiceFilename);
             return (unsigned int) (-1);
-- 
2.47.3

Reply via email to