From f17d397771164c1b0f77fea8fb0abdc99cf4a3e1 Mon Sep 17 00:00:00 2001
From: ChuanGang Jiang <jiangchuanganghw@outlook.com>
Date: Mon, 27 Feb 2023 11:46:12 +0000
Subject: [PATCH] fts: fail gracefully when out of memory

* lib/fts.c (fts_read): Set errno==ENOMEM and return NULL
when setup_dir() fails, rather than hitting an assertion later.

Refernece:https://github.com/coreutils/gnulib/commit/f17d397771164c1b0f77fea8fb0abdc99cf4a3e1
Conflict:ChangeLog context adaptation

---
 ChangeLog | 6 ++++++
 lib/fts.c | 6 +++++-
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/ChangeLog b/ChangeLog
index 1785234..43b0afa 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,9 @@
+2023-02-27  ChuanGang Jiang  <jiangchuanganghw@outlook.com>
+
+       fts: fail gracefully when out of memory
+       * lib/fts.c (fts_read): Set errno==ENOMEM and return NULL
+       when setup_dir() fails, rather than hitting an assertion later.
+
 2022-12-06  Paul Eggert  <eggert@cs.ucla.edu>

        fts: fix race + mishandling of fstatat failure
diff --git a/lib/fts.c b/lib/fts.c
index 78584b2902..794a4f75d7 100644
--- a/lib/fts.c
+++ b/lib/fts.c
@@ -979,7 +979,11 @@ next:   tmp = p;
                         }
                         free_dir(sp);
                         fts_load(sp, p);
-                        setup_dir(sp);
+                        if (! setup_dir(sp)) {
+                                free_dir(sp);
+                                __set_errno (ENOMEM);
+                                return (NULL);
+                        }
                         goto check_for_dir;
                 }
 
-- 
2.27.0

