From 73166b1006827ba520a8f60573cf399e5b1980c2 Mon Sep 17 00:00:00 2001 From: Dianjin Wang Date: Sat, 28 Feb 2026 18:36:03 +0800 Subject: [PATCH] initdb: fix stale errno handling in setup_cdb_schema() setup_cdb_schema() checked errno after a readdir() loop without resetting it beforehand. In some environments (e.g., Ubuntu 24.04), a stale errno value from operations inside the loop (such as pg_realloc or pg_strdup) could persist, causing readdir's normal termination to be misinterpreted as a failure (e.g., "Function not implemented"). This commit fixes the issue by adopting the standard PostgreSQL idiom: - Use "while (errno = 0, (file = readdir(dir)) != NULL)" to ensure errno is cleared strictly before each readdir() call. - Move closedir() after the errno check to prevent it from overwriting the error code from readdir(). - Add defensive error checking for the closedir() call itself. This ensures robust directory scanning and reliable error reporting during cluster initialization. --- src/bin/initdb/initdb.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 708cf77ffdf..8fdae656bc8 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -2024,7 +2024,7 @@ setup_cdb_schema(FILE *cmdfd) /* Collect all files with .sql suffix in array. */ nscripts = 0; - while ((file = readdir(dir)) != NULL) + while (errno = 0, (file = readdir(dir)) != NULL) { int namelen = strlen(file->d_name); @@ -2054,12 +2054,16 @@ setup_cdb_schema(FILE *cmdfd) errno = 0; #endif - closedir(dir); - if (errno != 0) { - /* some kind of I/O error? */ pg_log_error("error while reading cdb_init.d directory: %m"); + closedir(dir); + exit(1); + } + + if (closedir(dir)) + { + pg_log_error("error while closing cdb_init.d directory: %m"); exit(1); }