Debian Codegraph @

cmd/gomobile/build_apple.go

raw
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 "crypto/x509"
10 "encoding/pem"
11 "fmt"
12 "os"
13 "os/exec"
14 "path"
15 "path/filepath"
16 "strings"
17 "text/template"
18
19 "golang.org/x/tools/go/packages"
20 )
21
22 func goAppleBuild(pkg *packages.Package, bundleID string, targets []targetInfo) (map[string]bool, error) {
23 src := pkg.PkgPath
24 if buildO != "" && !strings.HasSuffix(buildO, ".app") {
25 return nil, fmt.Errorf("-o must have an .app for -target=ios")
26 }
27
28 productName := rfc1034Label(path.Base(pkg.PkgPath))
29 if productName == "" {
30 productName = "ProductName" // like xcode.
31 }
32
33 infoplist := new(bytes.Buffer)
34 if err := infoplistTmpl.Execute(infoplist, infoplistTmplData{
35 BundleID: bundleID + "." + productName,
36 Name: strings.Title(path.Base(pkg.PkgPath)),
37 }); err != nil {
38 return nil, err
39 }
40
41 // Detect the team ID
42 teamID, err := detectTeamID()
43 if err != nil {
44 return nil, err
45 }
46
47 projPbxproj := new(bytes.Buffer)
48 if err := projPbxprojTmpl.Execute(projPbxproj, projPbxprojTmplData{
49 TeamID: teamID,
50 }); err != nil {
51 return nil, err
52 }
53
54 files := []struct {
55 name string
56 contents []byte
57 }{
58 {tmpdir + "/main.xcodeproj/project.pbxproj", projPbxproj.Bytes()},
59 {tmpdir + "/main/Info.plist", infoplist.Bytes()},
60 {tmpdir + "/main/Images.xcassets/AppIcon.appiconset/Contents.json", []byte(contentsJSON)},
61 }
62
63 for _, file := range files {
64 if err := mkdir(filepath.Dir(file.name)); err != nil {
65 return nil, err
66 }
67 if buildX {
68 printcmd("echo \"%s\" > %s", file.contents, file.name)
69 }
70 if !buildN {
71 if err := os.WriteFile(file.name, file.contents, 0644); err != nil {
72 return nil, err
73 }
74 }
75 }
76
77 // We are using lipo tool to build multiarchitecture binaries.
78 cmd := exec.Command(
79 "xcrun", "lipo",
80 "-o", filepath.Join(tmpdir, "main/main"),
81 "-create",
82 )
83
84 var nmpkgs map[string]bool
85 builtArch := map[string]bool{}
86 for _, t := range targets {
87 // Only one binary per arch allowed
88 // e.g. ios/arm64 + iossimulator/amd64
89 if builtArch[t.arch] {
90 continue
91 }
92 builtArch[t.arch] = true
93
94 path := filepath.Join(tmpdir, t.platform, t.arch)
95
96 // Disable DWARF; see golang.org/issues/25148.
97 if err := goBuild(src, appleEnv[t.String()], "-ldflags=-w", "-o="+path); err != nil {
98 return nil, err
99 }
100 if nmpkgs == nil {
101 var err error
102 nmpkgs, err = extractPkgs(appleNM, path)
103 if err != nil {
104 return nil, err
105 }
106 }
107 cmd.Args = append(cmd.Args, path)
108
109 }
110
111 if err := runCmd(cmd); err != nil {
112 return nil, err
113 }
114
115 // TODO(jbd): Set the launcher icon.
116 if err := appleCopyAssets(pkg, tmpdir); err != nil {
117 return nil, err
118 }
119
120 // Build and move the release build to the output directory.
121 cmdStrings := []string{
122 "xcodebuild",
123 "-configuration", "Release",
124 "-project", tmpdir + "/main.xcodeproj",
125 "-allowProvisioningUpdates",
126 "DEVELOPMENT_TEAM=" + teamID,
127 }
128
129 cmd = exec.Command("xcrun", cmdStrings...)
130 if err := runCmd(cmd); err != nil {
131 return nil, err
132 }
133
134 // TODO(jbd): Fallback to copying if renaming fails.
135 if buildO == "" {
136 n := pkg.PkgPath
137 if n == "." {
138 // use cwd name
139 cwd, err := os.Getwd()
140 if err != nil {
141 return nil, fmt.Errorf("cannot create .app; cannot get the current working dir: %v", err)
142 }
143 n = cwd
144 }
145 n = path.Base(n)
146 buildO = n + ".app"
147 }
148 if buildX {
149 printcmd("mv %s %s", tmpdir+"/build/Release-iphoneos/main.app", buildO)
150 }
151 if !buildN {
152 // if output already exists, remove.
153 if err := os.RemoveAll(buildO); err != nil {
154 return nil, err
155 }
156 if err := os.Rename(tmpdir+"/build/Release-iphoneos/main.app", buildO); err != nil {
157 return nil, err
158 }
159 }
160 return nmpkgs, nil
161 }
162
163 func detectTeamID() (string, error) {
164 // Grabs the first certificate for "Apple Development"; will not work if there
165 // are multiple certificates and the first is not desired.
166 cmd := exec.Command(
167 "security", "find-certificate",
168 "-c", "Apple Development", "-p",
169 )
170 pemString, err := cmd.Output()
171 if err != nil {
172 err = fmt.Errorf("failed to pull the signing certificate to determine your team ID: %v", err)
173 return "", err
174 }
175
176 block, _ := pem.Decode(pemString)
177 if block == nil {
178 err = fmt.Errorf("failed to decode the PEM to determine your team ID: %s", pemString)
179 return "", err
180 }
181
182 cert, err := x509.ParseCertificate(block.Bytes)
183 if err != nil {
184 err = fmt.Errorf("failed to parse your signing certificate to determine your team ID: %v", err)
185 return "", err
186 }
187
188 if len(cert.Subject.OrganizationalUnit) == 0 {
189 err = fmt.Errorf("the signing certificate has no organizational unit (team ID)")
190 return "", err
191 }
192
193 return cert.Subject.OrganizationalUnit[0], nil
194 }
195
196 func appleCopyAssets(pkg *packages.Package, xcodeProjDir string) error {
197 dstAssets := xcodeProjDir + "/main/assets"
198 if err := mkdir(dstAssets); err != nil {
199 return err
200 }
201
202 // TODO(hajimehoshi): This works only with Go tools that assume all source files are in one directory.
203 // Fix this to work with other Go tools.
204 srcAssets := filepath.Join(filepath.Dir(pkg.GoFiles[0]), "assets")
205 fi, err := os.Stat(srcAssets)
206 if err != nil {
207 if os.IsNotExist(err) {
208 // skip walking through the directory to deep copy.
209 return nil
210 }
211 return err
212 }
213 if !fi.IsDir() {
214 // skip walking through to deep copy.
215 return nil
216 }
217 // if assets is a symlink, follow the symlink.
218 srcAssets, err = filepath.EvalSymlinks(srcAssets)
219 if err != nil {
220 return err
221 }
222 return filepath.Walk(srcAssets, func(path string, info os.FileInfo, err error) error {
223 if err != nil {
224 return err
225 }
226 if name := filepath.Base(path); strings.HasPrefix(name, ".") {
227 // Do not include the hidden files.
228 return nil
229 }
230 if info.IsDir() {
231 return nil
232 }
233 dst := dstAssets + "/" + path[len(srcAssets)+1:]
234 return copyFile(dst, path)
235 })
236 }
237
238 type infoplistTmplData struct {
239 BundleID string
240 Name string
241 }
242
243 var infoplistTmpl = template.Must(template.New("infoplist").Parse(`<?xml version="1.0" encoding="UTF-8"?>
244 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
245 <plist version="1.0">
246 <dict>
247 <key>CFBundleDevelopmentRegion</key>
248 <string>en</string>
249 <key>CFBundleExecutable</key>
250 <string>main</string>
251 <key>CFBundleIdentifier</key>
252 <string>{{.BundleID}}</string>
253 <key>CFBundleInfoDictionaryVersion</key>
254 <string>6.0</string>
255 <key>CFBundleName</key>
256 <string>{{.Name}}</string>
257 <key>CFBundlePackageType</key>
258 <string>APPL</string>
259 <key>CFBundleShortVersionString</key>
260 <string>1.0</string>
261 <key>CFBundleSignature</key>
262 <string>????</string>
263 <key>CFBundleVersion</key>
264 <string>1</string>
265 <key>LSRequiresIPhoneOS</key>
266 <true/>
267 <key>UILaunchStoryboardName</key>
268 <string>LaunchScreen</string>
269 <key>UIRequiredDeviceCapabilities</key>
270 <array>
271 <string>armv7</string>
272 </array>
273 <key>UISupportedInterfaceOrientations</key>
274 <array>
275 <string>UIInterfaceOrientationPortrait</string>
276 <string>UIInterfaceOrientationLandscapeLeft</string>
277 <string>UIInterfaceOrientationLandscapeRight</string>
278 </array>
279 <key>UISupportedInterfaceOrientations~ipad</key>
280 <array>
281 <string>UIInterfaceOrientationPortrait</string>
282 <string>UIInterfaceOrientationPortraitUpsideDown</string>
283 <string>UIInterfaceOrientationLandscapeLeft</string>
284 <string>UIInterfaceOrientationLandscapeRight</string>
285 </array>
286 </dict>
287 </plist>
288 `))
289
290 type projPbxprojTmplData struct {
291 TeamID string
292 }
293
294 var projPbxprojTmpl = template.Must(template.New("projPbxproj").Parse(`// !$*UTF8*$!
295 {
296 archiveVersion = 1;
297 classes = {
298 };
299 objectVersion = 46;
300 objects = {
301
302 /* Begin PBXBuildFile section */
303 254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 254BB84E1B1FD08900C56DE9 /* Images.xcassets */; };
304 254BB8681B1FD16500C56DE9 /* main in Resources */ = {isa = PBXBuildFile; fileRef = 254BB8671B1FD16500C56DE9 /* main */; };
305 25FB30331B30FDEE0005924C /* assets in Resources */ = {isa = PBXBuildFile; fileRef = 25FB30321B30FDEE0005924C /* assets */; };
306 /* End PBXBuildFile section */
307
308 /* Begin PBXFileReference section */
309 254BB83E1B1FD08900C56DE9 /* main.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = main.app; sourceTree = BUILT_PRODUCTS_DIR; };
310 254BB8421B1FD08900C56DE9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
311 254BB84E1B1FD08900C56DE9 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
312 254BB8671B1FD16500C56DE9 /* main */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.executable"; path = main; sourceTree = "<group>"; };
313 25FB30321B30FDEE0005924C /* assets */ = {isa = PBXFileReference; lastKnownFileType = folder; name = assets; path = main/assets; sourceTree = "<group>"; };
314 /* End PBXFileReference section */
315
316 /* Begin PBXGroup section */
317 254BB8351B1FD08900C56DE9 = {
318 isa = PBXGroup;
319 children = (
320 25FB30321B30FDEE0005924C /* assets */,
321 254BB8401B1FD08900C56DE9 /* main */,
322 254BB83F1B1FD08900C56DE9 /* Products */,
323 );
324 sourceTree = "<group>";
325 usesTabs = 0;
326 };
327 254BB83F1B1FD08900C56DE9 /* Products */ = {
328 isa = PBXGroup;
329 children = (
330 254BB83E1B1FD08900C56DE9 /* main.app */,
331 );
332 name = Products;
333 sourceTree = "<group>";
334 };
335 254BB8401B1FD08900C56DE9 /* main */ = {
336 isa = PBXGroup;
337 children = (
338 254BB8671B1FD16500C56DE9 /* main */,
339 254BB84E1B1FD08900C56DE9 /* Images.xcassets */,
340 254BB8411B1FD08900C56DE9 /* Supporting Files */,
341 );
342 path = main;
343 sourceTree = "<group>";
344 };
345 254BB8411B1FD08900C56DE9 /* Supporting Files */ = {
346 isa = PBXGroup;
347 children = (
348 254BB8421B1FD08900C56DE9 /* Info.plist */,
349 );
350 name = "Supporting Files";
351 sourceTree = "<group>";
352 };
353 /* End PBXGroup section */
354
355 /* Begin PBXNativeTarget section */
356 254BB83D1B1FD08900C56DE9 /* main */ = {
357 isa = PBXNativeTarget;
358 buildConfigurationList = 254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */;
359 buildPhases = (
360 254BB83C1B1FD08900C56DE9 /* Resources */,
361 );
362 buildRules = (
363 );
364 dependencies = (
365 );
366 name = main;
367 productName = main;
368 productReference = 254BB83E1B1FD08900C56DE9 /* main.app */;
369 productType = "com.apple.product-type.application";
370 };
371 /* End PBXNativeTarget section */
372
373 /* Begin PBXProject section */
374 254BB8361B1FD08900C56DE9 /* Project object */ = {
375 isa = PBXProject;
376 attributes = {
377 LastUpgradeCheck = 0630;
378 ORGANIZATIONNAME = Developer;
379 TargetAttributes = {
380 254BB83D1B1FD08900C56DE9 = {
381 CreatedOnToolsVersion = 6.3.1;
382 DevelopmentTeam = {{.TeamID}};
383 };
384 };
385 };
386 buildConfigurationList = 254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */;
387 compatibilityVersion = "Xcode 3.2";
388 developmentRegion = English;
389 hasScannedForEncodings = 0;
390 knownRegions = (
391 en,
392 Base,
393 );
394 mainGroup = 254BB8351B1FD08900C56DE9;
395 productRefGroup = 254BB83F1B1FD08900C56DE9 /* Products */;
396 projectDirPath = "";
397 projectRoot = "";
398 targets = (
399 254BB83D1B1FD08900C56DE9 /* main */,
400 );
401 };
402 /* End PBXProject section */
403
404 /* Begin PBXResourcesBuildPhase section */
405 254BB83C1B1FD08900C56DE9 /* Resources */ = {
406 isa = PBXResourcesBuildPhase;
407 buildActionMask = 2147483647;
408 files = (
409 25FB30331B30FDEE0005924C /* assets in Resources */,
410 254BB8681B1FD16500C56DE9 /* main in Resources */,
411 254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */,
412 );
413 runOnlyForDeploymentPostprocessing = 0;
414 };
415 /* End PBXResourcesBuildPhase section */
416
417 /* Begin XCBuildConfiguration section */
418 254BB8601B1FD08900C56DE9 /* Release */ = {
419 isa = XCBuildConfiguration;
420 buildSettings = {
421 ALWAYS_SEARCH_USER_PATHS = NO;
422 CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
423 CLANG_CXX_LIBRARY = "libc++";
424 CLANG_ENABLE_MODULES = YES;
425 CLANG_ENABLE_OBJC_ARC = YES;
426 CLANG_WARN_BOOL_CONVERSION = YES;
427 CLANG_WARN_CONSTANT_CONVERSION = YES;
428 CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
429 CLANG_WARN_EMPTY_BODY = YES;
430 CLANG_WARN_ENUM_CONVERSION = YES;
431 CLANG_WARN_INT_CONVERSION = YES;
432 CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
433 CLANG_WARN_UNREACHABLE_CODE = YES;
434 CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
435 "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development";
436 COPY_PHASE_STRIP = NO;
437 DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
438 ENABLE_NS_ASSERTIONS = NO;
439 ENABLE_STRICT_OBJC_MSGSEND = YES;
440 GCC_C_LANGUAGE_STANDARD = gnu99;
441 GCC_NO_COMMON_BLOCKS = YES;
442 GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
443 GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
444 GCC_WARN_UNDECLARED_SELECTOR = YES;
445 GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
446 GCC_WARN_UNUSED_FUNCTION = YES;
447 GCC_WARN_UNUSED_VARIABLE = YES;
448 MTL_ENABLE_DEBUG_INFO = NO;
449 SDKROOT = iphoneos;
450 TARGETED_DEVICE_FAMILY = "1,2";
451 VALIDATE_PRODUCT = YES;
452 ENABLE_BITCODE = YES;
453 };
454 name = Release;
455 };
456 254BB8631B1FD08900C56DE9 /* Release */ = {
457 isa = XCBuildConfiguration;
458 buildSettings = {
459 ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
460 INFOPLIST_FILE = main/Info.plist;
461 LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
462 PRODUCT_NAME = "$(TARGET_NAME)";
463 };
464 name = Release;
465 };
466 /* End XCBuildConfiguration section */
467
468 /* Begin XCConfigurationList section */
469 254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */ = {
470 isa = XCConfigurationList;
471 buildConfigurations = (
472 254BB8601B1FD08900C56DE9 /* Release */,
473 );
474 defaultConfigurationIsVisible = 0;
475 defaultConfigurationName = Release;
476 };
477 254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */ = {
478 isa = XCConfigurationList;
479 buildConfigurations = (
480 254BB8631B1FD08900C56DE9 /* Release */,
481 );
482 defaultConfigurationIsVisible = 0;
483 defaultConfigurationName = Release;
484 };
485 /* End XCConfigurationList section */
486 };
487 rootObject = 254BB8361B1FD08900C56DE9 /* Project object */;
488 }
489 `))
490
491 const contentsJSON = `{
492 "images" : [
493 {
494 "idiom" : "iphone",
495 "size" : "29x29",
496 "scale" : "2x"
497 },
498 {
499 "idiom" : "iphone",
500 "size" : "29x29",
501 "scale" : "3x"
502 },
503 {
504 "idiom" : "iphone",
505 "size" : "40x40",
506 "scale" : "2x"
507 },
508 {
509 "idiom" : "iphone",
510 "size" : "40x40",
511 "scale" : "3x"
512 },
513 {
514 "idiom" : "iphone",
515 "size" : "60x60",
516 "scale" : "2x"
517 },
518 {
519 "idiom" : "iphone",
520 "size" : "60x60",
521 "scale" : "3x"
522 },
523 {
524 "idiom" : "ipad",
525 "size" : "29x29",
526 "scale" : "1x"
527 },
528 {
529 "idiom" : "ipad",
530 "size" : "29x29",
531 "scale" : "2x"
532 },
533 {
534 "idiom" : "ipad",
535 "size" : "40x40",
536 "scale" : "1x"
537 },
538 {
539 "idiom" : "ipad",
540 "size" : "40x40",
541 "scale" : "2x"
542 },
543 {
544 "idiom" : "ipad",
545 "size" : "76x76",
546 "scale" : "1x"
547 },
548 {
549 "idiom" : "ipad",
550 "size" : "76x76",
551 "scale" : "2x"
552 }
553 ],
554 "info" : {
555 "version" : 1,
556 "author" : "xcode"
557 }
558 }
559 `
560
561 // rfc1034Label sanitizes the name to be usable in a uniform type identifier.
562 // The sanitization is similar to xcode's rfc1034identifier macro that
563 // replaces illegal characters (not conforming the rfc1034 label rule) with '-'.
564 func rfc1034Label(name string) string {
565 // * Uniform type identifier:
566 //
567 // According to
568 // https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html
569 //
570 // A uniform type identifier is a Unicode string that usually contains characters
571 // in the ASCII character set. However, only a subset of the ASCII characters are
572 // permitted. You may use the Roman alphabet in upper and lower case (A–Z, a–z),
573 // the digits 0 through 9, the dot (“.”), and the hyphen (“-”). This restriction
574 // is based on DNS name restrictions, set forth in RFC 1035.
575 //
576 // Uniform type identifiers may also contain any of the Unicode characters greater
577 // than U+007F.
578 //
579 // Note: the actual implementation of xcode does not allow some unicode characters
580 // greater than U+007f. In this implementation, we just replace everything non
581 // alphanumeric with "-" like the rfc1034identifier macro.
582 //
583 // * RFC1034 Label
584 //
585 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
586 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
587 // <let-dig-hyp> ::= <let-dig> | "-"
588 // <let-dig> ::= <letter> | <digit>
589 const surrSelf = 0x10000
590 begin := false
591
592 var res []rune
593 for i, r := range name {
594 if r == '.' && !begin {
595 continue
596 }
597 begin = true
598
599 switch {
600 case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z':
601 res = append(res, r)
602 case '0' <= r && r <= '9':
603 if i == 0 {
604 res = append(res, '-')
605 } else {
606 res = append(res, r)
607 }
608 default:
609 if r < surrSelf {
610 res = append(res, '-')
611 } else {
612 res = append(res, '-', '-')
613 }
614 }
615 }
616 return string(res)
617 }