swiftwasm / swift

WebAssembly support for the Swift programming language

Home Page:https://swiftwasm.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

XMLParser use requires shim to include libxml2.a

mstokercricut opened this issue · comments

When building a codebase with the SwiftWasm toolchain that uses the XMLParser type, at one point one had to:

import Foundation
#if canImport(FoundationXML)
import FoundationXML
#endif

I've been doing this to build a library that uses XMLParser to parse SVG files. I'm not sure this is strictly necessary to import FoundationXML anymore (and just importing Foundation might be enough). It appears to have been required around Swift 5.1 or so, then the commentary around it fizzles out.

Regardless, when I try to depend on the library that uses XMLParser to build a Wasm binary, the linker complains:

wasm-ld: error: unable to find library -lxml2
clang-13: error: linker command failed with exit code 1 (use -v to see invocation)
<unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)
[9/10] Linking WasmMainShim.wasm
Error: command "/Library/Developer/Toolchains/swift-wasm-5.9.1-RELEASE.xctoolchain/usr/bin/swift-build" failed with exit code 1

It appears that libxml2 is being included with the Swift runtime in the toolchain, as seen here:

https://github.com/swiftwasm/swiftwasm-build/blob/20d712073b78672380a5882e3ea85f87ca0e34f6/tools/build/install-build-sdk.sh#L13

However, it appears that somewhere along the way libxml2.a gets lost. It also seems that a needed symbol, getcwd(), does not have an implementation.

I've been able to resolve this issue by building a shim library for libxml2, adding a definition for getcwd() that just returns nil, then depending on the built target with a linker directive that uses unsafe flags to add a directory to the library search path. I've included a few screenshots to give context.

It would be great if libxml2 ended out in the toolchain in a way that makes its use transparent. I'd be happy to help resolve this, but am unsure where to start to actually submit a PR to the toolchain.

Screenshot 2024-03-26 at 4 45 54 PM Screenshot 2024-03-26 at 4 46 33 PM Screenshot 2024-03-26 at 4 45 35 PM

Thank you for reporting! I've fixed it by including libxml2.a in the toolchain. Could you try the tomorrow's toolchain snapshot and reopen this if it didn't solve the issue?

Absolutely! Thank you! I'll post the result.

That absolutely did the trick! the getcwd() symbol issue also was resolved with this. Thank you again!

For anyone that may encounter this in a search: it is still necessary to import FoundationXML to get XMLParser on non-macOS platforms. To build code that works with macOS, Linux, Windows, Wasm, and other platforms, perform your import like this:

import Foundation
#if canImport(FoundationXML)
import FoundationXML
#endif