Skip to content

[DNM] Address Sanitizer for Wasm/WASI #1897

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/SwiftDriver/Driver/Driver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2751,7 +2751,7 @@ extension Driver {
}

// Check that we're one of the known supported targets for sanitizers.
if !(targetTriple.isWindows || targetTriple.isDarwin || targetTriple.os == .linux) {
if !(targetTriple.isWindows || targetTriple.isDarwin || targetTriple.os == .linux || targetTriple.os == .wasi) {
diagnosticEngine.emit(
.error_unsupported_opt_for_target(
arg: "-sanitize=",
Expand Down
7 changes: 1 addition & 6 deletions Sources/SwiftDriver/Jobs/Toolchain+LinkerSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,7 @@ extension Toolchain {
for targetInfo: FrontendTargetInfo,
parsedOptions: inout ParsedOptions
) throws -> VirtualPath {
var platform = targetInfo.target.triple.platformName(conflatingDarwin: true)!
// compiler-rt moved these Android sanitizers into `lib/linux/` a couple
// years ago, llvm/llvm-project@a68ccba, so look for them there instead.
if platform == "android" {
platform = "linux"
}
let platform = targetInfo.target.triple.clangOSLibName

// NOTE(compnerd) Windows uses the per-target runtime directory for the
// Windows runtimes. This should also be done for the other platforms, but
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,12 @@ extension WebAssemblyToolchain {

// Delegate to Clang for sanitizers. It will figure out the correct linker
// options.
guard sanitizers.isEmpty else {
throw Error.sanitizersUnsupportedForTarget(targetTriple.triple)
if linkerOutputType == .executable && !sanitizers.isEmpty {
let sanitizerNames = sanitizers
.map { $0.rawValue }
.sorted() // Sort so we get a stable, testable order
.joined(separator: ",")
commandLine.appendFlag("-fsanitize=\(sanitizerNames)")
}

if parsedOptions.hasArgument(.profileGenerate) {
Expand Down
7 changes: 6 additions & 1 deletion Sources/SwiftDriver/Toolchains/WebAssemblyToolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,12 @@ public final class WebAssemblyToolchain: Toolchain {
targetTriple: Triple,
isShared: Bool
) throws -> String {
throw Error.sanitizersUnsupportedForTarget(targetTriple.triple)
switch sanitizer {
case .address:
return "libclang_rt.\(sanitizer.libraryName)-\(targetTriple.archName).a"
default:
throw Error.sanitizersUnsupportedForTarget(targetTriple.triple)
}
}

public func platformSpecificInterpreterEnvironmentVariables(env: [String : String],
Expand Down
23 changes: 22 additions & 1 deletion Sources/SwiftDriver/Utilities/Triple+Platforms.swift
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,28 @@ extension Triple {
}
}

/// The platform name, i.e. the name clang uses to identify this target in its

/// The "os" component of the Clang compiler resource library directory (`<ResourceDir>/lib/<OSName>`).
/// Must be kept in sync with Clang driver:
/// https://github.com/llvm/llvm-project/blob/llvmorg-20.1.4/clang/lib/Driver/ToolChain.cpp#L690
@_spi(Testing) public var clangOSLibName: String {
guard let os else {
return osName
}
if os.isDarwin {
return "darwin"
}

switch os {
case .freeBSD: return "freebsd"
case .netbsd: return "netbsd"
case .openbsd: return "openbsd"
case .aix: return "aix"
default: return osName
}
}

/// The platform name, i.e. the name Swift uses to identify this target in its
/// resource directory.
///
/// - Parameter conflatingDarwin: If true, all Darwin platforms will be
Expand Down
41 changes: 41 additions & 0 deletions Tests/SwiftDriverTests/SwiftDriverTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2877,6 +2877,47 @@ final class SwiftDriverTests: XCTestCase {
XCTAssertTrue(linkCmd.contains(.flag("-fsanitize=address")))
}
#endif

func checkWASITarget(target: String, clangOSDir: String) throws {
try withTemporaryDirectory { resourceDir in
var env = ProcessEnv.vars
env["SWIFT_DRIVER_SWIFT_AUTOLINK_EXTRACT_EXEC"] = "/garbage/swift-autolink-extract"

let asanRuntimeLibPath = resourceDir.appending(components: [
"clang", "lib", clangOSDir, "libclang_rt.asan-wasm32.a"
])
try localFileSystem.writeFileContents(asanRuntimeLibPath) {
$0.send("garbage")
}
try localFileSystem.writeFileContents(resourceDir.appending(components: "wasi", "static-executable-args.lnk")) {
$0.send("garbage")
}

var driver = try Driver(
args: commonArgs + [
"-target", target, "-sanitize=address",
"-resource-dir", resourceDir.pathString
],
env: env
)
let plannedJobs = try driver.planBuild()

XCTAssertEqual(plannedJobs.count, 4)

let compileJob = plannedJobs[0]
let compileCmd = compileJob.commandLine
XCTAssertTrue(compileCmd.contains(.flag("-sanitize=address")))

let linkJob = plannedJobs[3]
let linkCmd = linkJob.commandLine
XCTAssertTrue(linkCmd.contains(.flag("-fsanitize=address")))
}
}
do {
try checkWASITarget(target: "wasm32-unknown-wasi", clangOSDir: "wasi")
try checkWASITarget(target: "wasm32-unknown-wasip1", clangOSDir: "wasip1")
try checkWASITarget(target: "wasm32-unknown-wasip1-threads", clangOSDir: "wasip1")
}
}

func testSanitizerCoverageArgs() throws {
Expand Down
9 changes: 9 additions & 0 deletions Tests/SwiftDriverTests/TripleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1317,6 +1317,15 @@ final class TripleTests: XCTestCase {
shouldHaveJetPacks: true)
}

func testClangOSLibName() {
XCTAssertEqual("darwin", Triple("x86_64-apple-macosx").clangOSLibName)
XCTAssertEqual("darwin", Triple("arm64-apple-ios13.0").clangOSLibName)
XCTAssertEqual("linux", Triple("aarch64-unknown-linux-android24").clangOSLibName)
XCTAssertEqual("wasi", Triple("wasm32-unknown-wasi").clangOSLibName)
XCTAssertEqual("wasip1", Triple("wasm32-unknown-wasip1-threads").clangOSLibName)
XCTAssertEqual("none", Triple("arm64-unknown-none").clangOSLibName)
}

func testToolchainSelection() {
let diagnostics = DiagnosticsEngine()
struct None { }
Expand Down