Skip to content

Commit

Permalink
Deal with invalid UTF-8 from gai_strerror
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
Noratrieb committed Jul 10, 2024
1 parent 98dcbae commit 1426772
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion library/std/src/sys/pal/unix/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down

0 comments on commit 1426772

Please sign in to comment.