Debian Codegraph @

cmd/gomobile/env.go

raw symbols SCIP
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 "bufio"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io/fs"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "strings"
18
19 "golang.org/x/mobile/internal/sdkpath"
20 )
21
22 // General mobile build environment. Initialized by envInit.
23 var (
24 gomobilepath string // $GOPATH/pkg/gomobile
25 androidEnv map[string][]string // android arch -> []string
26 appleEnv map[string][]string
27 appleNM string
28 )
29
30 func isAndroidPlatform(platform string) bool {
31 return platform == "android"
32 }
33
34 func isApplePlatform(platform string) bool {
35 return contains(applePlatforms, platform)
36 }
37
38 var applePlatforms = []string{"ios", "iossimulator", "macos", "maccatalyst"}
39
40 func platformArchs(platform string) []string {
41 switch platform {
42 case "ios":
43 return []string{"arm64"}
44 case "iossimulator":
45 return []string{"arm64", "amd64"}
46 case "macos", "maccatalyst":
47 return []string{"arm64", "amd64"}
48 case "android":
49 return []string{"arm", "arm64", "386", "amd64"}
50 default:
51 panic(fmt.Sprintf("unexpected platform: %s", platform))
52 }
53 }
54
55 func isSupportedArch(platform, arch string) bool {
56 return contains(platformArchs(platform), arch)
57 }
58
59 // platformOS returns the correct GOOS value for platform.
60 func platformOS(platform string) string {
61 switch platform {
62 case "android":
63 return "android"
64 case "ios", "iossimulator":
65 return "ios"
66 case "macos", "maccatalyst":
67 // For "maccatalyst", Go packages should be built with GOOS=darwin,
68 // not GOOS=ios, since the underlying OS (and kernel, runtime) is macOS.
69 // But, using GOOS=darwin with build-tag ios leads to corrupt builds: https://go.dev/issue/52299
70 // => So we use GOOS=ios for now.
71 // We also apply a "macos" or "maccatalyst" build tag, respectively.
72 // See below for additional context.
73 return "ios"
74 default:
75 panic(fmt.Sprintf("unexpected platform: %s", platform))
76 }
77 }
78
79 func platformTags(platform string) []string {
80 switch platform {
81 case "android":
82 return []string{"android"}
83 case "ios", "iossimulator":
84 return []string{"ios"}
85 case "macos":
86 return []string{"macos"}
87 case "maccatalyst":
88 // Mac Catalyst is a subset of iOS APIs made available on macOS
89 // designed to ease porting apps developed for iPad to macOS.
90 // See
91 // https://developer.apple.com/mac-catalyst/.
92 // https://stackoverflow.com/questions/12132933/preprocessor-macro-for-os-x-targets/49560690#49560690
93 //
94 // Historically gomobile used GOOS=darwin with build tag ios when
95 // targeting Mac Catalyst. However, this configuration is not officially
96 // supported and leads to corrupt builds after go1.18: https://go.dev/issues/52299
97 // Use GOOS=ios.
98 // To help discriminate between darwin, ios, macos, and maccatalyst
99 // targets, there is also a "maccatalyst" tag.
100 return []string{"macos", "maccatalyst"}
101 default:
102 panic(fmt.Sprintf("unexpected platform: %s", platform))
103 }
104 }
105
106 func contains(haystack []string, needle string) bool {
107 for _, v := range haystack {
108 if v == needle {
109 return true
110 }
111 }
112 return false
113 }
114
115 func buildEnvInit() (cleanup func(), err error) {
116 // Find gomobilepath.
117 gopath := goEnv("GOPATH")
118 for _, p := range filepath.SplitList(gopath) {
119 gomobilepath = filepath.Join(p, "pkg", "gomobile")
120 if _, err := os.Stat(gomobilepath); buildN || err == nil {
121 break
122 }
123 }
124
125 if buildX {
126 fmt.Fprintln(xout, "GOMOBILE="+gomobilepath)
127 }
128
129 // Check the toolchain is in a good state.
130 // Pick a temporary directory for assembling an apk/app.
131 if gomobilepath == "" {
132 return nil, errors.New("toolchain not installed, run `gomobile init`")
133 }
134
135 cleanupFn := func() {
136 if buildWork {
137 fmt.Printf("WORK=%s\n", tmpdir)
138 return
139 }
140 removeAll(tmpdir)
141 }
142 if buildN {
143 tmpdir = "$WORK"
144 cleanupFn = func() {}
145 } else {
146 tmpdir, err = os.MkdirTemp("", "gomobile-work-")
147 if err != nil {
148 return nil, err
149 }
150 }
151 if buildX {
152 fmt.Fprintln(xout, "WORK="+tmpdir)
153 }
154
155 if err := envInit(); err != nil {
156 return nil, err
157 }
158
159 return cleanupFn, nil
160 }
161
162 func envInit() (err error) {
163 // Setup the cross-compiler environments.
164 if ndkRoot, err := ndkRoot(); err == nil {
165 androidEnv = make(map[string][]string)
166 if buildAndroidAPI < minAndroidAPI {
167 return fmt.Errorf("gomobile requires Android API level >= %d", minAndroidAPI)
168 }
169 for arch, toolchain := range ndk {
170 clang := toolchain.Path(ndkRoot, "clang")
171 clangpp := toolchain.Path(ndkRoot, "clang++")
172 if !buildN {
173 tools := []string{clang, clangpp}
174 if runtime.GOOS == "windows" {
175 // Because of https://github.com/android-ndk/ndk/issues/920,
176 // we require r19c, not just r19b. Fortunately, the clang++.cmd
177 // script only exists in r19c.
178 tools = append(tools, clangpp+".cmd")
179 }
180 for _, tool := range tools {
181 _, err = os.Stat(tool)
182 if err != nil {
183 return fmt.Errorf("No compiler for %s was found in the NDK (tried %s). Make sure your NDK version is >= r19c. Use `sdkmanager --update` to update it.", arch, tool)
184 }
185 }
186 }
187 androidEnv[arch] = []string{
188 "GOOS=android",
189 "GOARCH=" + arch,
190 "CC=" + clang,
191 "CXX=" + clangpp,
192 "CGO_ENABLED=1",
193 }
194 if arch == "arm" {
195 androidEnv[arch] = append(androidEnv[arch], "GOARM=7")
196 }
197 }
198 }
199
200 if !xcodeAvailable() {
201 return nil
202 }
203
204 appleNM = "nm"
205 appleEnv = make(map[string][]string)
206 for _, platform := range applePlatforms {
207 for _, arch := range platformArchs(platform) {
208 var env []string
209 var goos, sdk, clang, cflags string
210 var err error
211 switch platform {
212 case "ios":
213 goos = "ios"
214 sdk = "iphoneos"
215 clang, cflags, err = envClang(sdk)
216 cflags += " -miphoneos-version-min=" + buildIOSVersion
217 cflags += " -fembed-bitcode"
218 case "iossimulator":
219 goos = "ios"
220 sdk = "iphonesimulator"
221 clang, cflags, err = envClang(sdk)
222 cflags += " -mios-simulator-version-min=" + buildIOSVersion
223 cflags += " -fembed-bitcode"
224 case "maccatalyst":
225 // See the comment about maccatalyst's GOOS, build tags configuration
226 // in platformOS and platformTags.
227 // Using GOOS=darwin with build-tag ios leads to corrupt builds: https://go.dev/issue/52299
228 // => So we use GOOS=ios for now.
229 goos = "ios"
230 sdk = "macosx"
231 clang, cflags, err = envClang(sdk)
232 // TODO(ydnar): the following 3 lines MAY be needed to compile
233 // packages or apps for maccatalyst. Commenting them out now in case
234 // it turns out they are necessary. Currently none of the example
235 // apps will build for macos or maccatalyst because they have a
236 // GLKit dependency, which is deprecated on all Apple platforms, and
237 // broken on maccatalyst (GLKView isn’t available).
238 // sysroot := strings.SplitN(cflags, " ", 2)[1]
239 // cflags += " -isystem " + sysroot + "/System/iOSSupport/usr/include"
240 // cflags += " -iframework " + sysroot + "/System/iOSSupport/System/Library/Frameworks"
241 switch arch {
242 case "amd64":
243 cflags += " -target x86_64-apple-ios" + buildIOSVersion + "-macabi"
244 case "arm64":
245 cflags += " -target arm64-apple-ios" + buildIOSVersion + "-macabi"
246 cflags += " -fembed-bitcode"
247 }
248 case "macos":
249 goos = "darwin"
250 sdk = "macosx" // Note: the SDK is called "macosx", not "macos"
251 clang, cflags, err = envClang(sdk)
252 if arch == "arm64" {
253 cflags += " -fembed-bitcode"
254 }
255 default:
256 panic(fmt.Errorf("unknown Apple target: %s/%s", platform, arch))
257 }
258
259 if err != nil {
260 return err
261 }
262
263 env = append(env,
264 "GOOS="+goos,
265 "GOARCH="+arch,
266 "GOFLAGS="+"-tags="+strings.Join(platformTags(platform), ","),
267 "CC="+clang,
268 "CXX="+clang+"++",
269 "CGO_CFLAGS="+cflags+" -arch "+archClang(arch),
270 "CGO_CXXFLAGS="+cflags+" -arch "+archClang(arch),
271 "CGO_LDFLAGS="+cflags+" -arch "+archClang(arch),
272 "CGO_ENABLED=1",
273 "DARWIN_SDK="+sdk,
274 )
275 appleEnv[platform+"/"+arch] = env
276 }
277 }
278
279 return nil
280 }
281
282 // abi maps GOARCH values to Android ABI strings.
283 // See https://developer.android.com/ndk/guides/abis
284 func abi(goarch string) string {
285 switch goarch {
286 case "arm":
287 return "armeabi-v7a"
288 case "arm64":
289 return "arm64-v8a"
290 case "386":
291 return "x86"
292 case "amd64":
293 return "x86_64"
294 default:
295 return ""
296 }
297 }
298
299 // checkNDKRoot returns nil if the NDK in `ndkRoot` supports the current configured
300 // API version and all the specified Android targets.
301 func checkNDKRoot(ndkRoot string, targets []targetInfo) error {
302 platformsJson, err := os.Open(filepath.Join(ndkRoot, "meta", "platforms.json"))
303 if err != nil {
304 return err
305 }
306 defer platformsJson.Close()
307 decoder := json.NewDecoder(platformsJson)
308 supportedVersions := struct {
309 Min int
310 Max int
311 }{}
312 if err := decoder.Decode(&supportedVersions); err != nil {
313 return err
314 }
315 if supportedVersions.Min > buildAndroidAPI ||
316 supportedVersions.Max < buildAndroidAPI {
317 return fmt.Errorf("unsupported API version %d (not in %d..%d)", buildAndroidAPI, supportedVersions.Min, supportedVersions.Max)
318 }
319 abisJson, err := os.Open(filepath.Join(ndkRoot, "meta", "abis.json"))
320 if err != nil {
321 return err
322 }
323 defer abisJson.Close()
324 decoder = json.NewDecoder(abisJson)
325 abis := make(map[string]struct{})
326 if err := decoder.Decode(&abis); err != nil {
327 return err
328 }
329 for _, target := range targets {
330 if !isAndroidPlatform(target.platform) {
331 continue
332 }
333 if _, found := abis[abi(target.arch)]; !found {
334 return fmt.Errorf("ndk does not support %s", target.platform)
335 }
336 }
337 return nil
338 }
339
340 // compatibleNDKRoots searches the side-by-side NDK dirs for compatible SDKs.
341 func compatibleNDKRoots(ndkForest string, targets []targetInfo) ([]string, error) {
342 ndkDirs, err := os.ReadDir(ndkForest)
343 if err != nil {
344 return nil, err
345 }
346 compatibleNDKRoots := []string{}
347 var lastErr error
348 for _, dirent := range ndkDirs {
349 ndkRoot := filepath.Join(ndkForest, dirent.Name())
350 lastErr = checkNDKRoot(ndkRoot, targets)
351 if lastErr == nil {
352 compatibleNDKRoots = append(compatibleNDKRoots, ndkRoot)
353 }
354 }
355 if len(compatibleNDKRoots) > 0 {
356 return compatibleNDKRoots, nil
357 }
358 return nil, lastErr
359 }
360
361 // ndkVersion returns the full version number of an installed copy of the NDK,
362 // or "" if it cannot be determined.
363 func ndkVersion(ndkRoot string) string {
364 properties, err := os.Open(filepath.Join(ndkRoot, "source.properties"))
365 if err != nil {
366 return ""
367 }
368 defer properties.Close()
369 // Parse the version number out of the .properties file.
370 // See https://en.wikipedia.org/wiki/.properties
371 scanner := bufio.NewScanner(properties)
372 for scanner.Scan() {
373 line := scanner.Text()
374 tokens := strings.SplitN(line, "=", 2)
375 if len(tokens) != 2 {
376 continue
377 }
378 if strings.TrimSpace(tokens[0]) == "Pkg.Revision" {
379 return strings.TrimSpace(tokens[1])
380 }
381 }
382 return ""
383 }
384
385 // ndkRoot returns the root path of an installed NDK that supports all the
386 // specified Android targets. For details of NDK locations, see
387 // https://github.com/android/ndk-samples/wiki/Configure-NDK-Path
388 func ndkRoot(targets ...targetInfo) (string, error) {
389 if buildN {
390 return "$NDK_PATH", nil
391 }
392
393 // Try the ANDROID_NDK_HOME variable. This approach is deprecated, but it
394 // has the highest priority because it represents an explicit user choice.
395 if ndkRoot := os.Getenv("ANDROID_NDK_HOME"); ndkRoot != "" {
396 if err := checkNDKRoot(ndkRoot, targets); err != nil {
397 return "", fmt.Errorf("ANDROID_NDK_HOME specifies %s, which is unusable: %w", ndkRoot, err)
398 }
399 return ndkRoot, nil
400 }
401
402 androidHome, err := sdkpath.AndroidHome()
403 if err != nil {
404 return "", fmt.Errorf("could not locate Android SDK: %w", err)
405 }
406
407 // Use the newest compatible NDK under the side-by-side path arrangement.
408 ndkForest := filepath.Join(androidHome, "ndk")
409 ndkRoots, sideBySideErr := compatibleNDKRoots(ndkForest, targets)
410 if len(ndkRoots) != 0 {
411 // Choose the latest version that supports the build configuration.
412 // NDKs whose version cannot be determined will be least preferred.
413 // In the event of a tie, the later ndkRoot will win.
414 maxVersion := ""
415 var selected string
416 for _, ndkRoot := range ndkRoots {
417 version := ndkVersion(ndkRoot)
418 if version >= maxVersion {
419 maxVersion = version
420 selected = ndkRoot
421 }
422 }
423 return selected, nil
424 }
425 // Try the deprecated NDK location.
426 ndkRoot := filepath.Join(androidHome, "ndk-bundle")
427 if legacyErr := checkNDKRoot(ndkRoot, targets); legacyErr != nil {
428 return "", fmt.Errorf("no usable NDK in %s: %w, %v", androidHome, sideBySideErr, legacyErr)
429 }
430 return ndkRoot, nil
431 }
432
433 func envClang(sdkName string) (clang, cflags string, err error) {
434 if buildN {
435 return sdkName + "-clang", "-isysroot " + sdkName, nil
436 }
437 cmd := exec.Command("xcrun", "--sdk", sdkName, "--find", "clang")
438 out, err := cmd.Output()
439 if err != nil {
440 if ee := (*exec.ExitError)(nil); errors.As(err, &ee) {
441 out = append(out, ee.Stderr...)
442 }
443 return "", "", fmt.Errorf("xcrun --find: %v\n%s", err, out)
444 }
445 clang = strings.TrimSpace(string(out))
446
447 cmd = exec.Command("xcrun", "--sdk", sdkName, "--show-sdk-path")
448 out, err = cmd.Output()
449 if err != nil {
450 if ee := (*exec.ExitError)(nil); errors.As(err, &ee) {
451 out = append(out, ee.Stderr...)
452 }
453 return "", "", fmt.Errorf("xcrun --show-sdk-path: %v\n%s", err, out)
454 }
455 sdk := strings.TrimSpace(string(out))
456 return clang, "-isysroot " + sdk, nil
457 }
458
459 func archClang(goarch string) string {
460 switch goarch {
461 case "arm":
462 return "armv7"
463 case "arm64":
464 return "arm64"
465 case "386":
466 return "i386"
467 case "amd64":
468 return "x86_64"
469 default:
470 panic(fmt.Sprintf("unknown GOARCH: %q", goarch))
471 }
472 }
473
474 // environ merges os.Environ and the given "key=value" pairs.
475 // If a key is in both os.Environ and kv, kv takes precedence.
476 func environ(kv []string) []string {
477 cur := os.Environ()
478 new := make([]string, 0, len(cur)+len(kv))
479
480 envs := make(map[string]string, len(cur))
481 for _, ev := range cur {
482 elem := strings.SplitN(ev, "=", 2)
483 if len(elem) != 2 || elem[0] == "" {
484 // pass the env var of unusual form untouched.
485 // e.g. Windows may have env var names starting with "=".
486 new = append(new, ev)
487 continue
488 }
489 if goos == "windows" {
490 elem[0] = strings.ToUpper(elem[0])
491 }
492 envs[elem[0]] = elem[1]
493 }
494 for _, ev := range kv {
495 elem := strings.SplitN(ev, "=", 2)
496 if len(elem) != 2 || elem[0] == "" {
497 panic(fmt.Sprintf("malformed env var %q from input", ev))
498 }
499 if goos == "windows" {
500 elem[0] = strings.ToUpper(elem[0])
501 }
502 envs[elem[0]] = elem[1]
503 }
504 for k, v := range envs {
505 new = append(new, k+"="+v)
506 }
507 return new
508 }
509
510 func getenv(env []string, key string) string {
511 prefix := key + "="
512 for _, kv := range env {
513 if strings.HasPrefix(kv, prefix) {
514 return kv[len(prefix):]
515 }
516 }
517 return ""
518 }
519
520 func archNDK() string {
521 if runtime.GOOS == "windows" && runtime.GOARCH == "386" {
522 return "windows"
523 } else {
524 var arch string
525 switch runtime.GOARCH {
526 case "386":
527 arch = "x86"
528 case "amd64":
529 arch = "x86_64"
530 case "arm64":
531 // Android NDK does not contain arm64 toolchains (until and
532 // including NDK 23), use use x86_64 instead. See:
533 // https://github.com/android/ndk/issues/1299
534 if runtime.GOOS == "darwin" {
535 arch = "x86_64"
536 break
537 }
538 fallthrough
539 default:
540 panic("unsupported GOARCH: " + runtime.GOARCH)
541 }
542 return runtime.GOOS + "-" + arch
543 }
544 }
545
546 type ndkToolchain struct {
547 arch string
548 abi string
549 minAPI int
550 toolPrefix string
551 clangPrefix string
552 }
553
554 func (tc *ndkToolchain) ClangPrefix() string {
555 if buildAndroidAPI < tc.minAPI {
556 return fmt.Sprintf("%s%d", tc.clangPrefix, tc.minAPI)
557 }
558 return fmt.Sprintf("%s%d", tc.clangPrefix, buildAndroidAPI)
559 }
560
561 func (tc *ndkToolchain) Path(ndkRoot, toolName string) string {
562 cmdFromPref := func(pref string) string {
563 return filepath.Join(ndkRoot, "toolchains", "llvm", "prebuilt", archNDK(), "bin", pref+"-"+toolName)
564 }
565
566 var cmd string
567 switch toolName {
568 case "clang", "clang++":
569 cmd = cmdFromPref(tc.ClangPrefix())
570 default:
571 cmd = cmdFromPref(tc.toolPrefix)
572 // Starting from NDK 23, GNU binutils are fully migrated to LLVM binutils.
573 // See https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md#ndk-r23
574 if _, err := os.Stat(cmd); errors.Is(err, fs.ErrNotExist) {
575 cmd = cmdFromPref("llvm")
576 }
577 }
578 return cmd
579 }
580
581 type ndkConfig map[string]ndkToolchain // map: GOOS->androidConfig.
582
583 func (nc ndkConfig) Toolchain(arch string) ndkToolchain {
584 tc, ok := nc[arch]
585 if !ok {
586 panic(`unsupported architecture: ` + arch)
587 }
588 return tc
589 }
590
591 var ndk = ndkConfig{
592 "arm": {
593 arch: "arm",
594 abi: "armeabi-v7a",
595 minAPI: 16,
596 toolPrefix: "arm-linux-androideabi",
597 clangPrefix: "armv7a-linux-androideabi",
598 },
599 "arm64": {
600 arch: "arm64",
601 abi: "arm64-v8a",
602 minAPI: 21,
603 toolPrefix: "aarch64-linux-android",
604 clangPrefix: "aarch64-linux-android",
605 },
606
607 "386": {
608 arch: "x86",
609 abi: "x86",
610 minAPI: 16,
611 toolPrefix: "i686-linux-android",
612 clangPrefix: "i686-linux-android",
613 },
614 "amd64": {
615 arch: "x86_64",
616 abi: "x86_64",
617 minAPI: 21,
618 toolPrefix: "x86_64-linux-android",
619 clangPrefix: "x86_64-linux-android",
620 },
621 }
622
623 func xcodeAvailable() bool {
624 err := exec.Command("xcrun", "xcodebuild", "-version").Run()
625 return err == nil
626 }