From 7260909ef40dc24e97e4af34a0538206af260499 Mon Sep 17 00:00:00 2001
From: Lasse Collin <lasse.collin@tukaani.org>
Date: Wed, 25 Mar 2026 19:03:00 +0200
Subject: [PATCH] xz: Prevent an integer overflow in --files and --files0

This requires a filename (or something that pretends to be a filename)
of at least 2 GiB on a 32-bit platform, and that realloc() to
SIZE_MAX / 2 + 1 bytes has succeeded.

Fixes: https://github.com/tukaani-project/xz/pull/218
(cherry picked from commit 0ac3b93387c0191919ffa38de5f49f6b28164b35)
---
 src/xz/main.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/src/xz/main.c b/src/xz/main.c
index e761bf8e2..6974dc471 100644
--- a/src/xz/main.c
+++ b/src/xz/main.c
@@ -130,6 +130,16 @@ read_name(const args_info *args)
 		// at least for one character to allow terminating the string
 		// with '\0'.
 		if (pos == size) {
+			// Prevent an integer overflow. This is only possible
+			// if allocating SIZE_MAX / 2 + 1 bytes has already
+			// succeeded.
+			//
+			// Use ENOMEM to for the error message to avoid adding
+			// a translatable string that will (almost) never be
+			// displayed in practice.
+			if (size > SIZE_MAX / 2)
+				message_fatal("%s", strerror(ENOMEM));
+
 			size *= 2;
 			name = xrealloc(name, size);
 		}
