From 4ae69c493f4cacfa73eed8c32948d3766c7d1f0a Mon Sep 17 00:00:00 2001
From: Yu Watanabe <watanabe.yu+github@gmail.com>
Date: Thu, 23 Nov 2023 00:32:48 +0900
Subject: [PATCH] locale-util: do not call setlocale() when multi-threaded

Fixes #30141.

(cherry picked from commit ca13432d600593b8eda76721118763b63746eb33)
(cherry picked from commit 6b1d188bd5a01dede2146fadd9b01c5690b7c7fc)
(cherry picked from commit 420adce67d5286bedf045d79f14872864268b7de)

Conflict:NA
Reference:https://github.com/systemd/systemd/commit/ca13432d600593b8eda76721118763b63746eb33
---
 src/basic/locale-util.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/basic/locale-util.c b/src/basic/locale-util.c
index d8518ec06a..fb3ec3a424 100644
--- a/src/basic/locale-util.c
+++ b/src/basic/locale-util.c
@@ -17,6 +17,7 @@
 #include "fileio.h"
 #include "hashmap.h"
 #include "locale-util.h"
+#include "missing_syscall.h"
 #include "path-util.h"
 #include "set.h"
 #include "string-table.h"
@@ -295,6 +296,12 @@ bool is_locale_utf8(void) {
         if (cached_answer >= 0)
                 goto out;
 
+        /* This function may be called from libsystemd, and setlocale() is not thread safe. Assuming yes. */
+        if (gettid() != raw_getpid()) {
+                cached_answer = true;
+                goto out;
+        }
+
         if (!setlocale(LC_ALL, "")) {
                 cached_answer = true;
                 goto out;
-- 
2.33.0

