| 1 |
// Copyright 2015 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package main |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"encoding/xml" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"os/exec" |
| 14 |
"path/filepath" |
| 15 |
"strconv" |
| 16 |
"strings" |
| 17 |
"text/template" |
| 18 |
"time" |
| 19 |
|
| 20 |
"golang.org/x/sync/errgroup" |
| 21 |
"golang.org/x/tools/go/packages" |
| 22 |
) |
| 23 |
|
| 24 |
func goAppleBind(gobind string, pkgs []*packages.Package, targets []targetInfo) error { |
| 25 |
var name string |
| 26 |
var title string |
| 27 |
|
| 28 |
if buildO == "" { |
| 29 |
name = pkgs[0].Name |
| 30 |
title = strings.Title(name) |
| 31 |
buildO = title + ".xcframework" |
| 32 |
} else { |
| 33 |
if !strings.HasSuffix(buildO, ".xcframework") { |
| 34 |
return fmt.Errorf("static framework name %q missing .xcframework suffix", buildO) |
| 35 |
} |
| 36 |
base := filepath.Base(buildO) |
| 37 |
name = base[:len(base)-len(".xcframework")] |
| 38 |
title = strings.Title(name) |
| 39 |
} |
| 40 |
|
| 41 |
if err := removeAll(buildO); err != nil { |
| 42 |
return err |
| 43 |
} |
| 44 |
|
| 45 |
outDirsForPlatform := map[string]string{} |
| 46 |
for _, t := range targets { |
| 47 |
outDirsForPlatform[t.platform] = filepath.Join(tmpdir, t.platform) |
| 48 |
} |
| 49 |
|
| 50 |
// Run the gobind command for each platform |
| 51 |
var gobindWG errgroup.Group |
| 52 |
for platform, outDir := range outDirsForPlatform { |
| 53 |
platform := platform |
| 54 |
outDir := outDir |
| 55 |
gobindWG.Go(func() error { |
| 56 |
// Catalyst support requires iOS 13+ |
| 57 |
v, _ := strconv.ParseFloat(buildIOSVersion, 64) |
| 58 |
if platform == "maccatalyst" && v < 13.0 { |
| 59 |
return errors.New("catalyst requires -iosversion=13 or higher") |
| 60 |
} |
| 61 |
|
| 62 |
// Run gobind once per platform to generate the bindings |
| 63 |
cmd := exec.Command( |
| 64 |
gobind, |
| 65 |
"-lang=go,objc", |
| 66 |
"-outdir="+outDir, |
| 67 |
) |
| 68 |
cmd.Env = append(cmd.Env, "GOOS="+platformOS(platform)) |
| 69 |
cmd.Env = append(cmd.Env, "CGO_ENABLED=1") |
| 70 |
tags := append(buildTags[:], platformTags(platform)...) |
| 71 |
cmd.Args = append(cmd.Args, "-tags="+strings.Join(tags, ",")) |
| 72 |
if bindPrefix != "" { |
| 73 |
cmd.Args = append(cmd.Args, "-prefix="+bindPrefix) |
| 74 |
} |
| 75 |
for _, p := range pkgs { |
| 76 |
cmd.Args = append(cmd.Args, p.PkgPath) |
| 77 |
} |
| 78 |
if err := runCmd(cmd); err != nil { |
| 79 |
return err |
| 80 |
} |
| 81 |
return nil |
| 82 |
}) |
| 83 |
} |
| 84 |
if err := gobindWG.Wait(); err != nil { |
| 85 |
return err |
| 86 |
} |
| 87 |
|
| 88 |
modulesUsed, err := areGoModulesUsed() |
| 89 |
if err != nil { |
| 90 |
return err |
| 91 |
} |
| 92 |
|
| 93 |
// Build archive files. |
| 94 |
var buildWG errgroup.Group |
| 95 |
for _, t := range targets { |
| 96 |
t := t |
| 97 |
buildWG.Go(func() error { |
| 98 |
outDir := outDirsForPlatform[t.platform] |
| 99 |
outSrcDir := filepath.Join(outDir, "src") |
| 100 |
|
| 101 |
if modulesUsed { |
| 102 |
// Copy the source directory for each architecture for concurrent building. |
| 103 |
newOutSrcDir := filepath.Join(outDir, "src-"+t.arch) |
| 104 |
if !buildN { |
| 105 |
if err := doCopyAll(newOutSrcDir, outSrcDir); err != nil { |
| 106 |
return err |
| 107 |
} |
| 108 |
} |
| 109 |
outSrcDir = newOutSrcDir |
| 110 |
} |
| 111 |
|
| 112 |
// Copy the environment variables to make this function concurrent-safe. |
| 113 |
env := make([]string, len(appleEnv[t.String()])) |
| 114 |
copy(env, appleEnv[t.String()]) |
| 115 |
|
| 116 |
// Add the generated packages to GOPATH for reverse bindings. |
| 117 |
gopath := fmt.Sprintf("GOPATH=%s%c%s", outDir, filepath.ListSeparator, goEnv("GOPATH")) |
| 118 |
env = append(env, gopath) |
| 119 |
|
| 120 |
// Run `go mod tidy` to force to create go.sum. |
| 121 |
// Without go.sum, `go build` fails as of Go 1.16. |
| 122 |
if modulesUsed { |
| 123 |
if err := writeGoMod(outSrcDir, t.platform, t.arch); err != nil { |
| 124 |
return err |
| 125 |
} |
| 126 |
if err := goModTidyAt(outSrcDir, env); err != nil { |
| 127 |
return err |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
if err := goAppleBindArchive(appleArchiveFilepath(name, t), env, outSrcDir); err != nil { |
| 132 |
return fmt.Errorf("%s/%s: %v", t.platform, t.arch, err) |
| 133 |
} |
| 134 |
|
| 135 |
return nil |
| 136 |
}) |
| 137 |
} |
| 138 |
if err := buildWG.Wait(); err != nil { |
| 139 |
return err |
| 140 |
} |
| 141 |
|
| 142 |
var frameworkDirs []string |
| 143 |
frameworkArchCount := map[string]int{} |
| 144 |
for _, t := range targets { |
| 145 |
outDir := outDirsForPlatform[t.platform] |
| 146 |
gobindDir := filepath.Join(outDir, "src", "gobind") |
| 147 |
|
| 148 |
env := appleEnv[t.String()][:] |
| 149 |
sdk := getenv(env, "DARWIN_SDK") |
| 150 |
|
| 151 |
frameworkDir := filepath.Join(tmpdir, t.platform, sdk, title+".framework") |
| 152 |
frameworkDirs = append(frameworkDirs, frameworkDir) |
| 153 |
frameworkArchCount[frameworkDir] = frameworkArchCount[frameworkDir] + 1 |
| 154 |
|
| 155 |
frameworkLayout, err := frameworkLayoutForTarget(t, title) |
| 156 |
if err != nil { |
| 157 |
return err |
| 158 |
} |
| 159 |
|
| 160 |
titlePath := filepath.Join(frameworkDir, frameworkLayout.binaryPath, title) |
| 161 |
if frameworkArchCount[frameworkDir] > 1 { |
| 162 |
// Not the first static lib, attach to a fat library and skip create headers |
| 163 |
fatCmd := exec.Command( |
| 164 |
"xcrun", |
| 165 |
"lipo", appleArchiveFilepath(name, t), titlePath, "-create", "-output", titlePath, |
| 166 |
) |
| 167 |
if err := runCmd(fatCmd); err != nil { |
| 168 |
return err |
| 169 |
} |
| 170 |
continue |
| 171 |
} |
| 172 |
|
| 173 |
headersDir := filepath.Join(frameworkDir, frameworkLayout.headerPath) |
| 174 |
if err := mkdir(headersDir); err != nil { |
| 175 |
return err |
| 176 |
} |
| 177 |
|
| 178 |
lipoCmd := exec.Command( |
| 179 |
"xcrun", |
| 180 |
"lipo", appleArchiveFilepath(name, t), "-create", "-o", titlePath, |
| 181 |
) |
| 182 |
if err := runCmd(lipoCmd); err != nil { |
| 183 |
return err |
| 184 |
} |
| 185 |
|
| 186 |
fileBases := make([]string, len(pkgs)+1) |
| 187 |
for i, pkg := range pkgs { |
| 188 |
fileBases[i] = bindPrefix + strings.Title(pkg.Name) |
| 189 |
} |
| 190 |
fileBases[len(fileBases)-1] = "Universe" |
| 191 |
|
| 192 |
// Copy header file next to output archive. |
| 193 |
var headerFiles []string |
| 194 |
if len(fileBases) == 1 { |
| 195 |
headerFiles = append(headerFiles, title+".h") |
| 196 |
err := copyFile( |
| 197 |
filepath.Join(headersDir, title+".h"), |
| 198 |
filepath.Join(gobindDir, bindPrefix+title+".objc.h"), |
| 199 |
) |
| 200 |
if err != nil { |
| 201 |
return err |
| 202 |
} |
| 203 |
} else { |
| 204 |
for _, fileBase := range fileBases { |
| 205 |
headerFiles = append(headerFiles, fileBase+".objc.h") |
| 206 |
err := copyFile( |
| 207 |
filepath.Join(headersDir, fileBase+".objc.h"), |
| 208 |
filepath.Join(gobindDir, fileBase+".objc.h"), |
| 209 |
) |
| 210 |
if err != nil { |
| 211 |
return err |
| 212 |
} |
| 213 |
} |
| 214 |
err := copyFile( |
| 215 |
filepath.Join(headersDir, "ref.h"), |
| 216 |
filepath.Join(gobindDir, "ref.h"), |
| 217 |
) |
| 218 |
if err != nil { |
| 219 |
return err |
| 220 |
} |
| 221 |
headerFiles = append(headerFiles, title+".h") |
| 222 |
err = writeFile(filepath.Join(headersDir, title+".h"), func(w io.Writer) error { |
| 223 |
return appleBindHeaderTmpl.Execute(w, map[string]interface{}{ |
| 224 |
"pkgs": pkgs, "title": title, "bases": fileBases, |
| 225 |
}) |
| 226 |
}) |
| 227 |
if err != nil { |
| 228 |
return err |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
frameworkInfoPlistDir := filepath.Join(frameworkDir, frameworkLayout.infoPlistPath) |
| 233 |
if err := mkdir(frameworkInfoPlistDir); err != nil { |
| 234 |
return err |
| 235 |
} |
| 236 |
err = writeFile(filepath.Join(frameworkInfoPlistDir, "Info.plist"), func(w io.Writer) error { |
| 237 |
fmVersion := fmt.Sprintf("0.0.%d", time.Now().Unix()) |
| 238 |
infoFrameworkPlistlData := infoFrameworkPlistlData{ |
| 239 |
BundleID: escapePlistValue(rfc1034Label(title)), |
| 240 |
ExecutableName: escapePlistValue(title), |
| 241 |
Version: escapePlistValue(fmVersion), |
| 242 |
} |
| 243 |
infoplist := new(bytes.Buffer) |
| 244 |
if err := infoFrameworkPlistTmpl.Execute(infoplist, infoFrameworkPlistlData); err != nil { |
| 245 |
return err |
| 246 |
} |
| 247 |
_, err := w.Write(infoplist.Bytes()) |
| 248 |
return err |
| 249 |
}) |
| 250 |
if err != nil { |
| 251 |
return err |
| 252 |
} |
| 253 |
|
| 254 |
var mmVals = struct { |
| 255 |
Module string |
| 256 |
Headers []string |
| 257 |
}{ |
| 258 |
Module: title, |
| 259 |
Headers: headerFiles, |
| 260 |
} |
| 261 |
modulesDir := filepath.Join(frameworkDir, frameworkLayout.modulePath) |
| 262 |
err = writeFile(filepath.Join(modulesDir, "module.modulemap"), func(w io.Writer) error { |
| 263 |
return appleModuleMapTmpl.Execute(w, mmVals) |
| 264 |
}) |
| 265 |
if err != nil { |
| 266 |
return err |
| 267 |
} |
| 268 |
|
| 269 |
for src, dst := range frameworkLayout.symlinks { |
| 270 |
if err := symlink(src, filepath.Join(frameworkDir, dst)); err != nil { |
| 271 |
return err |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
// Finally combine all frameworks to an XCFramework |
| 277 |
xcframeworkArgs := []string{"-create-xcframework"} |
| 278 |
|
| 279 |
for _, dir := range frameworkDirs { |
| 280 |
// On macOS, a temporary directory starts with /var, which is a symbolic link to /private/var. |
| 281 |
// And in gomobile, a temporary directory is usually used as a working directly. |
| 282 |
// Unfortunately, xcodebuild in Xcode 15 seems to have a bug and might not be able to understand fullpaths with symbolic links. |
| 283 |
// As a workaround, resolve the path with symbolic links by filepath.EvalSymlinks. |
| 284 |
dir, err := filepath.EvalSymlinks(dir) |
| 285 |
if err != nil { |
| 286 |
return err |
| 287 |
} |
| 288 |
xcframeworkArgs = append(xcframeworkArgs, "-framework", dir) |
| 289 |
} |
| 290 |
|
| 291 |
xcframeworkArgs = append(xcframeworkArgs, "-output", buildO) |
| 292 |
cmd := exec.Command("xcodebuild", xcframeworkArgs...) |
| 293 |
err = runCmd(cmd) |
| 294 |
return err |
| 295 |
} |
| 296 |
|
| 297 |
type frameworkLayout struct { |
| 298 |
headerPath string |
| 299 |
binaryPath string |
| 300 |
modulePath string |
| 301 |
infoPlistPath string |
| 302 |
// symlinks to create in the framework. Maps src (relative to dst) -> dst (relative to framework bundle root) |
| 303 |
symlinks map[string]string |
| 304 |
} |
| 305 |
|
| 306 |
// frameworkLayoutForTarget generates the filestructure for a framework for the given target platform (macos, ios, etc), |
| 307 |
// according to Apple's spec https://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle |
| 308 |
func frameworkLayoutForTarget(t targetInfo, title string) (*frameworkLayout, error) { |
| 309 |
switch t.platform { |
| 310 |
case "macos", "maccatalyst": |
| 311 |
return &frameworkLayout{ |
| 312 |
headerPath: "Versions/A/Headers", |
| 313 |
binaryPath: "Versions/A", |
| 314 |
modulePath: "Versions/A/Modules", |
| 315 |
infoPlistPath: "Versions/A/Resources", |
| 316 |
symlinks: map[string]string{ |
| 317 |
"A": "Versions/Current", |
| 318 |
"Versions/Current/Resources": "Resources", |
| 319 |
"Versions/Current/Headers": "Headers", |
| 320 |
"Versions/Current/Modules": "Modules", |
| 321 |
filepath.Join("Versions/Current", title): title, |
| 322 |
}, |
| 323 |
}, nil |
| 324 |
case "ios", "iossimulator": |
| 325 |
return &frameworkLayout{ |
| 326 |
headerPath: "Headers", |
| 327 |
binaryPath: ".", |
| 328 |
modulePath: "Modules", |
| 329 |
infoPlistPath: ".", |
| 330 |
}, nil |
| 331 |
} |
| 332 |
|
| 333 |
return nil, fmt.Errorf("unsupported platform %q", t.platform) |
| 334 |
} |
| 335 |
|
| 336 |
type infoFrameworkPlistlData struct { |
| 337 |
BundleID string |
| 338 |
ExecutableName string |
| 339 |
Version string |
| 340 |
} |
| 341 |
|
| 342 |
// infoFrameworkPlistTmpl is a template for the Info.plist file in a framework. |
| 343 |
// Minimum OS version == 100.0 is a workaround for SPM issue |
| 344 |
// https://github.com/firebase/firebase-ios-sdk/pull/12439/files#diff-f4eb4ff5ec89af999cbe8fa3ffe5647d7853ffbc9c1515b337ca043c684b6bb4R679 |
| 345 |
var infoFrameworkPlistTmpl = template.Must(template.New("infoFrameworkPlist").Parse(`<?xml version="1.0" encoding="UTF-8"?> |
| 346 |
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 347 |
<plist version="1.0"> |
| 348 |
<dict> |
| 349 |
<key>CFBundleExecutable</key> |
| 350 |
<string>{{.ExecutableName}}</string> |
| 351 |
<key>CFBundleIdentifier</key> |
| 352 |
<string>{{.BundleID}}</string> |
| 353 |
<key>MinimumOSVersion</key> |
| 354 |
<string>100.0</string> |
| 355 |
<key>CFBundleShortVersionString</key> |
| 356 |
<string>{{.Version}}</string> |
| 357 |
<key>CFBundleVersion</key> |
| 358 |
<string>{{.Version}}</string> |
| 359 |
<key>CFBundlePackageType</key> |
| 360 |
<string>FMWK</string> |
| 361 |
</dict> |
| 362 |
</plist> |
| 363 |
`)) |
| 364 |
|
| 365 |
func escapePlistValue(value string) string { |
| 366 |
var b bytes.Buffer |
| 367 |
xml.EscapeText(&b, []byte(value)) |
| 368 |
return b.String() |
| 369 |
} |
| 370 |
|
| 371 |
var appleModuleMapTmpl = template.Must(template.New("iosmmap").Parse(`framework module "{{.Module}}" { |
| 372 |
header "ref.h" |
| 373 |
{{range .Headers}} header "{{.}}" |
| 374 |
{{end}} |
| 375 |
export * |
| 376 |
}`)) |
| 377 |
|
| 378 |
func appleArchiveFilepath(name string, t targetInfo) string { |
| 379 |
return filepath.Join(tmpdir, name+"-"+t.platform+"-"+t.arch+".a") |
| 380 |
} |
| 381 |
|
| 382 |
func goAppleBindArchive(out string, env []string, gosrc string) error { |
| 383 |
return goBuildAt(gosrc, "./gobind", env, "-buildmode=c-archive", "-o", out) |
| 384 |
} |
| 385 |
|
| 386 |
var appleBindHeaderTmpl = template.Must(template.New("apple.h").Parse(` |
| 387 |
// Objective-C API for talking to the following Go packages |
| 388 |
// |
| 389 |
{{range .pkgs}}// {{.PkgPath}} |
| 390 |
{{end}}// |
| 391 |
// File is generated by gomobile bind. Do not edit. |
| 392 |
#ifndef __{{.title}}_FRAMEWORK_H__ |
| 393 |
#define __{{.title}}_FRAMEWORK_H__ |
| 394 |
|
| 395 |
{{range .bases}}#include "{{.}}.objc.h" |
| 396 |
{{end}} |
| 397 |
#endif |
| 398 |
`)) |