1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public import SWBUtil
public import SWBCore
import SWBMacro
import Foundation
@PluginExtensionSystemActor public func initializePlugin(_ manager: PluginManager) {
let plugin = AndroidPlugin()
manager.register(AndroidPlatformSpecsExtension(), type: SpecificationsExtensionPoint.self)
manager.register(AndroidEnvironmentExtension(plugin: plugin), type: EnvironmentExtensionPoint.self)
manager.register(AndroidPlatformExtension(), type: PlatformInfoExtensionPoint.self)
manager.register(AndroidSDKRegistryExtension(plugin: plugin), type: SDKRegistryExtensionPoint.self)
manager.register(AndroidToolchainRegistryExtension(plugin: plugin), type: ToolchainRegistryExtensionPoint.self)
}
@_spi(Testing) public final class AndroidPlugin: Sendable {
private let androidSDKInstallations = AsyncCache<OperatingSystem, [AndroidSDK]>()
func cachedAndroidSDKInstallations(host: OperatingSystem) async throws -> [AndroidSDK] {
try await androidSDKInstallations.value(forKey: host) {
// Always pass localFS because this will be cached, and executes a process on the host system so there's no reason to pass in any proxy.
try await AndroidSDK.findInstallations(host: host, fs: localFS)
}
}
@_spi(Testing) public func effectiveInstallation(host: OperatingSystem) async throws -> (sdk: AndroidSDK, ndk: AndroidSDK.NDK)? {
guard let androidSdk = try? await cachedAndroidSDKInstallations(host: host).first else {
return nil
}
guard let androidNdk = androidSdk.preferredNDK else {
return nil
}
return (androidSdk, androidNdk)
}
}
struct AndroidPlatformSpecsExtension: SpecificationsExtension {
func specificationFiles(resourceSearchPaths: [Path]) -> Bundle? {
findResourceBundle(nameWhenInstalledInToolchain: "SwiftBuild_SWBAndroidPlatform", resourceSearchPaths: resourceSearchPaths, defaultBundle: Bundle.module)
}
func specificationDomains() -> [String : [String]] {
["android": ["linux"]]
}
}
struct AndroidEnvironmentExtension: EnvironmentExtension {
let plugin: AndroidPlugin
func additionalEnvironmentVariables(context: any EnvironmentExtensionAdditionalEnvironmentVariablesContext) async throws -> [String: String] {
switch context.hostOperatingSystem {
case .windows, .macOS, .linux:
if let latest = try? await plugin.cachedAndroidSDKInstallations(host: context.hostOperatingSystem).first {
let sdkPath = latest.path.path.str
let ndkPath = latest.preferredNDK?.path.path.str
return [
"ANDROID_HOME": sdkPath,
"ANDROID_SDK_ROOT": sdkPath,
"ANDROID_NDK_ROOT": ndkPath,
"ANDROID_NDK_HOME": ndkPath,
].compactMapValues { $0 }
}
default:
break
}
return [:]
}
}
struct AndroidPlatformExtension: PlatformInfoExtension {
func additionalPlatforms(context: any PlatformInfoExtensionAdditionalPlatformsContext) throws -> [(path: Path, data: [String: PropertyListItem])] {
[
(.root, [
"Type": .plString("Platform"),
"Name": .plString("android"),
"Identifier": .plString("android"),
"Description": .plString("android"),
"FamilyName": .plString("Android"),
"FamilyIdentifier": .plString("android"),
"IsDeploymentPlatform": .plString("YES"),
])
]
}
}
@_spi(Testing) public struct AndroidSDKRegistryExtension: SDKRegistryExtension {
@_spi(Testing) public let plugin: AndroidPlugin
public func additionalSDKs(context: any SDKRegistryExtensionAdditionalSDKsContext) async throws -> [(path: Path, platform: SWBCore.Platform?, data: [String: PropertyListItem])] {
let host = context.hostOperatingSystem
guard let androidPlatform = context.platformRegistry.lookup(name: "android") else {
return []
}
let defaultProperties: [String: PropertyListItem] = [
"SDK_STAT_CACHE_ENABLE": "NO",
// Workaround to avoid `-dependency_info` on Linux.
"LD_DEPENDENCY_INFO_FILE": .plString(""),
// Android uses lld, not the Apple linker
// FIXME: Make this option conditional on use of the Apple linker (or perhaps when targeting an Apple triple?)
"LD_DETERMINISTIC_MODE": "NO",
"GENERATE_TEXT_BASED_STUBS": "NO",
"GENERATE_INTERMEDIATE_TEXT_BASED_STUBS": "NO",
"CHOWN": "/usr/bin/chown",
"LIBTOOL": .plString(host.imageFormat.executableName(basename: "llvm-lib")),
"AR": .plString(host.imageFormat.executableName(basename: "llvm-ar")),
]
guard let (_, androidNdk) = try await plugin.effectiveInstallation(host: host) else {
return []
}
let abis = androidNdk.abis
let deploymentTargetRange = androidNdk.deploymentTargetRange
let allPossibleTriples = try abis.values.flatMap { abi in
try (max(deploymentTargetRange.min, abi.min_os_version)...deploymentTargetRange.max).map { deploymentTarget in
var triple = abi.llvm_triple
triple.vendor = "unknown" // Android NDK uses "none", Swift SDKs use "unknown"
guard let env = triple.environment else {
throw StubError.error("Android triples must have an environment")
}
triple.environment = "\(env)\(deploymentTarget)"
return triple
}
}.map(\.description)
let androidSwiftSDKs = (try? SwiftSDK.findSDKs(
targetTriples: allPossibleTriples,
fs: context.fs,
hostOperatingSystem: context.hostOperatingSystem
)) ?? []
let swiftSettings: [String: PropertyListItem]
// FIXME: We need a way to narrow down the list, possibly by passing down a Swift SDK identifier from SwiftPM
// The resource path should be the same for all triples in an Android Swift SDK
if let androidSwiftSDK = androidSwiftSDKs.only, let swiftResourceDir = Set(androidSwiftSDK.targetTriples.values.map { tripleProperties in androidSwiftSDK.path.join(tripleProperties.swiftResourcesPath) }).only {
swiftSettings = [
"SWIFT_LIBRARY_PATH": .plString(swiftResourceDir.join("android").str),
"SWIFT_RESOURCE_DIR": .plString(swiftResourceDir.str),
"SWIFT_TARGET_TRIPLE": .plString("$(CURRENT_ARCH)-unknown-$(SWIFT_PLATFORM_TARGET_PREFIX)$(LLVM_TARGET_TRIPLE_SUFFIX)"),
"LIBRARY_SEARCH_PATHS": "$(inherited) $(SWIFT_RESOURCE_DIR)/../$(__ANDROID_TRIPLE_$(CURRENT_ARCH))",
].merging(abis.map {
("__ANDROID_TRIPLE_\($0.value.llvm_triple.arch)", .plString($0.value.triple))
}, uniquingKeysWith: { _, new in new })
} else {
swiftSettings = [:]
}
return [(androidNdk.sysroot.path, androidPlatform, [
"Type": .plString("SDK"),
"Version": .plString("0.0.0"),
"CanonicalName": .plString("android"),
"IsBaseSDK": .plBool(true),
"DefaultProperties": .plDict([
"PLATFORM_NAME": .plString("android"),
].merging(defaultProperties, uniquingKeysWith: { _, new in new })),
"CustomProperties": .plDict([
// Unlike most platforms, the Android version goes on the environment field rather than the system field
// FIXME: Make this configurable in a better way so we don't need to push build settings at the SDK definition level
"LLVM_TARGET_TRIPLE_OS_VERSION": .plString("$(SWIFT_PLATFORM_TARGET_PREFIX)"),
"LLVM_TARGET_TRIPLE_SUFFIX": .plString("-android$($(DEPLOYMENT_TARGET_SETTING_NAME))"),
].merging(swiftSettings, uniquingKeysWith: { _, new in new })),
"SupportedTargets": .plDict([
"android": .plDict([
"Archs": .plArray(abis.map { .plString($0.value.llvm_triple.arch) }),
"DeploymentTargetSettingName": .plString("ANDROID_DEPLOYMENT_TARGET"),
"DefaultDeploymentTarget": .plString("\(deploymentTargetRange.min)"),
"MinimumDeploymentTarget": .plString("\(deploymentTargetRange.min)"),
"MaximumDeploymentTarget": .plString("\(deploymentTargetRange.max)"),
"LLVMTargetTripleEnvironment": .plString("android"), // FIXME: androideabi for armv7!
"LLVMTargetTripleSys": .plString("linux"),
"LLVMTargetTripleVendor": .plString("none"),
])
]),
"Toolchains": .plArray([
.plString("android")
])
])]
}
}
struct AndroidToolchainRegistryExtension: ToolchainRegistryExtension {
let plugin: AndroidPlugin
func additionalToolchains(context: any ToolchainRegistryExtensionAdditionalToolchainsContext) async throws -> [Toolchain] {
guard let toolchainPath = try? await plugin.cachedAndroidSDKInstallations(host: context.hostOperatingSystem).first?.preferredNDK?.toolchainPath else {
return []
}
return [
Toolchain(
identifier: "android",
displayName: "Android",
version: Version(0, 0, 0),
aliases: [],
path: toolchainPath.path,
frameworkPaths: [],
libraryPaths: [],
defaultSettings: [:],
overrideSettings: [:],
defaultSettingsWhenPrimary: [:],
executableSearchPaths: [toolchainPath.path.join("bin")],
testingLibraryPlatformNames: [],
fs: context.fs)
]
}
}
|