From 1426772dcbafd15389e0cb99dc53c3099d3c3dc3 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Wed, 10 Jul 2024 19:42:54 +0200 Subject: [PATCH] Deal with invalid UTF-8 from `gai_strerror` When the system is using a non-UTF-8 locale, the value will indeed not be UTF-8. That sucks for everyone involved, but is no reason for panic. We can "handle" this gracefully by just using from lossy, replacing the invalid UTF-8 with the ? and keeping the accidentally valid UTF-8. Good luck when debugging, but at least it's not a crash. We already do this for `strerror_r`. --- library/std/src/sys/pal/unix/net.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/pal/unix/net.rs b/library/std/src/sys/pal/unix/net.rs index b8dc1538a6378..c56628ab448b5 100644 --- a/library/std/src/sys/pal/unix/net.rs +++ b/library/std/src/sys/pal/unix/net.rs @@ -47,7 +47,9 @@ pub fn cvt_gai(err: c_int) -> io::Result<()> { #[cfg(not(target_os = "espidf"))] let detail = unsafe { - str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned() + // We can't always expect a UTF-8 environment. When we don't get that luxury, + // it's better to give a low-quality error message than none at all. + String::from_utf8_lossy(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()) }; #[cfg(target_os = "espidf")]