Skip to main content
coreydaley.dev

Why archive_entry_pathname returns NULL for non-ASCII filenames

When I broadened Purrchiver’s engine tests to archives with filenames like café.txt or 日本語.txt, libarchive gave back no name at all. archive_entry_pathname_utf8() returned NULL, and so did the plain archive_entry_pathname(). ASCII names in the same archive were fine. Every name with a character outside ASCII came back empty.

Nothing was wrong with the archive. The problem was the locale.

What libarchive is doing

libarchive can hand you an entry’s name in several forms: multibyte (the current locale’s encoding), wide characters, and UTF-8. It converts between them on demand, through mbstowcs, wcstombs, and iconv, and those conversions depend on the locale’s character set (LC_CTYPE).

A C program starts in the C locale, and stays there until something calls setlocale. Swift’s test runner runs under LC_CTYPE=C, so every conversion happens in a character set that is effectively ASCII. Any name with a byte above 127 fails to convert, and libarchive reports that by returning NULL. The same happens at runtime in any process whose locale was never set to something Unicode-capable. It isn’t only a test-environment quirk.

The first fix, and why I replaced it

The quick fix works:

setlocale(LC_ALL, "en_US.UTF-8")

Put that at module load and the names come back. It’s also the wrong thing for a library to do. setlocale changes the locale for the whole process, which means a framework that only wanted readable filenames has changed how every other piece of C code in the host app parses and formats text. Code that relied on the inherited locale now behaves differently, and nothing tells it why. An architecture review flagged it the same day, and I replaced it.

The fix: a thread-scoped locale

POSIX has a per-thread alternative. newlocale builds a locale object, uselocale installs it on the current thread only, and you put the old one back when you’re done:

import Darwin

func withUTF8Locale<T>(_ body: () throws -> T) rethrows -> T {
    guard let utf8 = newlocale(LC_CTYPE_MASK, "en_US.UTF-8", nil) else {
        return try body()          // couldn't build it; run unscoped
    }
    let previous = uselocale(utf8)
    defer {
        _ = uselocale(previous)
        freelocale(utf8)
    }
    return try body()
}

Then wrap each libarchive call that might convert a name: opening the archive, reading the next header, reading data. Anything else on that thread, and every other thread, keeps the locale it had.

A few details:

  • LC_CTYPE_MASK, not LC_ALL_MASK. Filename conversion only consults the character-type category, so that’s all the wrapper changes. Collation, dates, and numbers are left alone. Conveniently, LC_ALL_MASK isn’t exposed by Swift’s Darwin module on the SDK I was building against.
  • The C++ side needs it too. The RAR reader converts the password with mbstowcs and filenames with wcstombs, so it gets the same treatment as a small RAII type whose constructor calls uselocale and whose destructor restores the previous locale.
  • Fall back through every form. Purrchiver reads the UTF-8 name first, then the wide-character name, then the multibyte one. Depending on the format, not every form is filled in.

Why there’s no async version

The obvious next step would be an async overload of withUTF8Locale, and I left it out on purpose.

uselocale is per thread. A Swift task isn’t tied to a thread: after an await, the rest of the function can resume on a different one. A locale installed before the await would be gone after it, and worse, it would be left behind on a thread that’s now running someone else’s work.

So the rule is to wrap the synchronous C call itself, never a span of code that contains an await. The engine’s async iterator calls into libarchive synchronously, and the locale is set and restored around each of those calls.

The other half: ZIP’s UTF-8 flag

Getting names to come back at all is one problem. Getting the right name is another, and in ZIP files that comes down to one bit.

ZIP filenames are raw bytes. General-purpose flag bit 11 says “these bytes are UTF-8”. Without it, a reader has to guess the encoding. When I built non-ASCII test fixtures, the Info-ZIP zip I was using didn’t set the bit, and in a quick check neither did the zip or ditto that ship with macOS. 7-Zip’s 7z a -tzip does set it, so the fixtures with non-ASCII names are built with 7-Zip. That way the tests exercise the UTF-8 path on purpose and don’t depend on a guess.

ZIPs made by older Windows tools, with names in a code page like CP932 and no flag, are a separate problem. This fix doesn’t address them.

What to take away

  • If a C library returns NULL for non-ASCII text, check the locale first. Swift processes, and test runners especially, often run in the C locale.
  • Libraries shouldn’t call setlocale. Use uselocale with a locale from newlocale, and restore the previous one in a defer.
  • Thread-local state and await don’t mix. Scope it to synchronous calls.
  • Build test fixtures with the encoding flags you mean to test. A fixture that depends on the reader guessing right only tests the guess.

Related posts