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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"os/exec"
"path/filepath"
"strconv"
"strings"
"text/template"
"time"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/packages"
)
func goAppleBind(gobind string, pkgs []*packages.Package, targets []targetInfo) error {
var name string
var title string
if buildO == "" {
name = pkgs[0].Name
title = strings.Title(name)
buildO = title + ".xcframework"
} else {
if !strings.HasSuffix(buildO, ".xcframework") {
return fmt.Errorf("static framework name %q missing .xcframework suffix", buildO)
}
base := filepath.Base(buildO)
name = base[:len(base)-len(".xcframework")]
title = strings.Title(name)
}
if err := removeAll(buildO); err != nil {
return err
}
outDirsForPlatform := map[string]string{}
for _, t := range targets {
outDirsForPlatform[t.platform] = filepath.Join(tmpdir, t.platform)
}
// Run the gobind command for each platform
var gobindWG errgroup.Group
for platform, outDir := range outDirsForPlatform {
platform := platform
outDir := outDir
gobindWG.Go(func() error {
// Catalyst support requires iOS 13+
v, _ := strconv.ParseFloat(buildIOSVersion, 64)
if platform == "maccatalyst" && v < 13.0 {
return errors.New("catalyst requires -iosversion=13 or higher")
}
// Run gobind once per platform to generate the bindings
cmd := exec.Command(
gobind,
"-lang=go,objc",
"-outdir="+outDir,
)
cmd.Env = append(cmd.Env, "GOOS="+platformOS(platform))
cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
tags := append(buildTags[:], platformTags(platform)...)
cmd.Args = append(cmd.Args, "-tags="+strings.Join(tags, ","))
if bindPrefix != "" {
cmd.Args = append(cmd.Args, "-prefix="+bindPrefix)
}
for _, p := range pkgs {
cmd.Args = append(cmd.Args, p.PkgPath)
}
if err := runCmd(cmd); err != nil {
return err
}
return nil
})
}
if err := gobindWG.Wait(); err != nil {
return err
}
modulesUsed, err := areGoModulesUsed()
if err != nil {
return err
}
// Build archive files.
var buildWG errgroup.Group
for _, t := range targets {
t := t
buildWG.Go(func() error {
outDir := outDirsForPlatform[t.platform]
outSrcDir := filepath.Join(outDir, "src")
if modulesUsed {
// Copy the source directory for each architecture for concurrent building.
newOutSrcDir := filepath.Join(outDir, "src-"+t.arch)
if !buildN {
if err := doCopyAll(newOutSrcDir, outSrcDir); err != nil {
return err
}
}
outSrcDir = newOutSrcDir
}
// Copy the environment variables to make this function concurrent-safe.
env := make([]string, len(appleEnv[t.String()]))
copy(env, appleEnv[t.String()])
// Add the generated packages to GOPATH for reverse bindings.
gopath := fmt.Sprintf("GOPATH=%s%c%s", outDir, filepath.ListSeparator, goEnv("GOPATH"))
env = append(env, gopath)
// Run `go mod tidy` to force to create go.sum.
// Without go.sum, `go build` fails as of Go 1.16.
if modulesUsed {
if err := writeGoMod(outSrcDir, t.platform, t.arch); err != nil {
return err
}
if err := goModTidyAt(outSrcDir, env); err != nil {
return err
}
}
if err := goAppleBindArchive(appleArchiveFilepath(name, t), env, outSrcDir); err != nil {
return fmt.Errorf("%s/%s: %v", t.platform, t.arch, err)
}
return nil
})
}
if err := buildWG.Wait(); err != nil {
return err
}
var frameworkDirs []string
frameworkArchCount := map[string]int{}
for _, t := range targets {
outDir := outDirsForPlatform[t.platform]
gobindDir := filepath.Join(outDir, "src", "gobind")
env := appleEnv[t.String()][:]
sdk := getenv(env, "DARWIN_SDK")
frameworkDir := filepath.Join(tmpdir, t.platform, sdk, title+".framework")
frameworkDirs = append(frameworkDirs, frameworkDir)
frameworkArchCount[frameworkDir] = frameworkArchCount[frameworkDir] + 1
frameworkLayout, err := frameworkLayoutForTarget(t, title)
if err != nil {
return err
}
titlePath := filepath.Join(frameworkDir, frameworkLayout.binaryPath, title)
if frameworkArchCount[frameworkDir] > 1 {
// Not the first static lib, attach to a fat library and skip create headers
fatCmd := exec.Command(
"xcrun",
"lipo", appleArchiveFilepath(name, t), titlePath, "-create", "-output", titlePath,
)
if err := runCmd(fatCmd); err != nil {
return err
}
continue
}
headersDir := filepath.Join(frameworkDir, frameworkLayout.headerPath)
if err := mkdir(headersDir); err != nil {
return err
}
lipoCmd := exec.Command(
"xcrun",
"lipo", appleArchiveFilepath(name, t), "-create", "-o", titlePath,
)
if err := runCmd(lipoCmd); err != nil {
return err
}
fileBases := make([]string, len(pkgs)+1)
for i, pkg := range pkgs {
fileBases[i] = bindPrefix + strings.Title(pkg.Name)
}
fileBases[len(fileBases)-1] = "Universe"
// Copy header file next to output archive.
var headerFiles []string
if len(fileBases) == 1 {
headerFiles = append(headerFiles, title+".h")
err := copyFile(
filepath.Join(headersDir, title+".h"),
filepath.Join(gobindDir, bindPrefix+title+".objc.h"),
)
if err != nil {
return err
}
} else {
for _, fileBase := range fileBases {
headerFiles = append(headerFiles, fileBase+".objc.h")
err := copyFile(
filepath.Join(headersDir, fileBase+".objc.h"),
filepath.Join(gobindDir, fileBase+".objc.h"),
)
if err != nil {
return err
}
}
err := copyFile(
filepath.Join(headersDir, "ref.h"),
filepath.Join(gobindDir, "ref.h"),
)
if err != nil {
return err
}
headerFiles = append(headerFiles, title+".h")
err = writeFile(filepath.Join(headersDir, title+".h"), func(w io.Writer) error {
return appleBindHeaderTmpl.Execute(w, map[string]interface{}{
"pkgs": pkgs, "title": title, "bases": fileBases,
})
})
if err != nil {
return err
}
}
frameworkInfoPlistDir := filepath.Join(frameworkDir, frameworkLayout.infoPlistPath)
if err := mkdir(frameworkInfoPlistDir); err != nil {
return err
}
err = writeFile(filepath.Join(frameworkInfoPlistDir, "Info.plist"), func(w io.Writer) error {
fmVersion := fmt.Sprintf("0.0.%d", time.Now().Unix())
infoFrameworkPlistlData := infoFrameworkPlistlData{
BundleID: escapePlistValue(rfc1034Label(title)),
ExecutableName: escapePlistValue(title),
Version: escapePlistValue(fmVersion),
}
infoplist := new(bytes.Buffer)
if err := infoFrameworkPlistTmpl.Execute(infoplist, infoFrameworkPlistlData); err != nil {
return err
}
_, err := w.Write(infoplist.Bytes())
return err
})
if err != nil {
return err
}
var mmVals = struct {
Module string
Headers []string
}{
Module: title,
Headers: headerFiles,
}
modulesDir := filepath.Join(frameworkDir, frameworkLayout.modulePath)
err = writeFile(filepath.Join(modulesDir, "module.modulemap"), func(w io.Writer) error {
return appleModuleMapTmpl.Execute(w, mmVals)
})
if err != nil {
return err
}
for src, dst := range frameworkLayout.symlinks {
if err := symlink(src, filepath.Join(frameworkDir, dst)); err != nil {
return err
}
}
}
// Finally combine all frameworks to an XCFramework
xcframeworkArgs := []string{"-create-xcframework"}
for _, dir := range frameworkDirs {
// On macOS, a temporary directory starts with /var, which is a symbolic link to /private/var.
// And in gomobile, a temporary directory is usually used as a working directly.
// Unfortunately, xcodebuild in Xcode 15 seems to have a bug and might not be able to understand fullpaths with symbolic links.
// As a workaround, resolve the path with symbolic links by filepath.EvalSymlinks.
dir, err := filepath.EvalSymlinks(dir)
if err != nil {
return err
}
xcframeworkArgs = append(xcframeworkArgs, "-framework", dir)
}
xcframeworkArgs = append(xcframeworkArgs, "-output", buildO)
cmd := exec.Command("xcodebuild", xcframeworkArgs...)
err = runCmd(cmd)
return err
}
type frameworkLayout struct {
headerPath string
binaryPath string
modulePath string
infoPlistPath string
// symlinks to create in the framework. Maps src (relative to dst) -> dst (relative to framework bundle root)
symlinks map[string]string
}
// frameworkLayoutForTarget generates the filestructure for a framework for the given target platform (macos, ios, etc),
// according to Apple's spec https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle
func frameworkLayoutForTarget(t targetInfo, title string) (*frameworkLayout, error) {
switch t.platform {
case "macos", "maccatalyst":
return &frameworkLayout{
headerPath: "Versions/A/Headers",
binaryPath: "Versions/A",
modulePath: "Versions/A/Modules",
infoPlistPath: "Versions/A/Resources",
symlinks: map[string]string{
"A": "Versions/Current",
"Versions/Current/Resources": "Resources",
"Versions/Current/Headers": "Headers",
"Versions/Current/Modules": "Modules",
filepath.Join("Versions/Current", title): title,
},
}, nil
case "ios", "iossimulator":
return &frameworkLayout{
headerPath: "Headers",
binaryPath: ".",
modulePath: "Modules",
infoPlistPath: ".",
}, nil
}
return nil, fmt.Errorf("unsupported platform %q", t.platform)
}
type infoFrameworkPlistlData struct {
BundleID string
ExecutableName string
Version string
}
// infoFrameworkPlistTmpl is a template for the Info.plist file in a framework.
// Minimum OS version == 100.0 is a workaround for SPM issue
// https://github.com/firebase/firebase-ios-sdk/pull/12439/files#diff-f4eb4ff5ec89af999cbe8fa3ffe5647d7853ffbc9c1515b337ca043c684b6bb4R679
var infoFrameworkPlistTmpl = template.Must(template.New("infoFrameworkPlist").Parse(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>{{.ExecutableName}}</string>
<key>CFBundleIdentifier</key>
<string>{{.BundleID}}</string>
<key>MinimumOSVersion</key>
<string>100.0</string>
<key>CFBundleShortVersionString</key>
<string>{{.Version}}</string>
<key>CFBundleVersion</key>
<string>{{.Version}}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
</dict>
</plist>
`))
func escapePlistValue(value string) string {
var b bytes.Buffer
xml.EscapeText(&b, []byte(value))
return b.String()
}
var appleModuleMapTmpl = template.Must(template.New("iosmmap").Parse(`framework module "{{.Module}}" {
header "ref.h"
{{range .Headers}} header "{{.}}"
{{end}}
export *
}`))
func appleArchiveFilepath(name string, t targetInfo) string {
return filepath.Join(tmpdir, name+"-"+t.platform+"-"+t.arch+".a")
}
func goAppleBindArchive(out string, env []string, gosrc string) error {
return goBuildAt(gosrc, "./gobind", env, "-buildmode=c-archive", "-o", out)
}
var appleBindHeaderTmpl = template.Must(template.New("apple.h").Parse(`
// Objective-C API for talking to the following Go packages
//
{{range .pkgs}}// {{.PkgPath}}
{{end}}//
// File is generated by gomobile bind. Do not edit.
#ifndef __{{.title}}_FRAMEWORK_H__
#define __{{.title}}_FRAMEWORK_H__
{{range .bases}}#include "{{.}}.objc.h"
{{end}}
#endif
`))
|