github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/misc/ios/go_darwin_arm_exec.go (about) 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 // This program can be used as go_darwin_arm_exec by the Go tool. 6 // It executes binaries on an iOS device using the XCode toolchain 7 // and the ios-deploy program: https://github.com/phonegap/ios-deploy 8 // 9 // This script supports an extra flag, -lldb, that pauses execution 10 // just before the main program begins and allows the user to control 11 // the remote lldb session. This flag is appended to the end of the 12 // script's arguments and is not passed through to the underlying 13 // binary. 14 // 15 // This script requires that three environment variables be set: 16 // GOIOS_DEV_ID: The codesigning developer id or certificate identifier 17 // GOIOS_APP_ID: The provisioning app id prefix. Must support wildcard app ids. 18 // GOIOS_TEAM_ID: The team id that owns the app id prefix. 19 // $GOROOT/misc/ios contains a script, detect.go, that attempts to autodetect these. 20 package main 21 22 import ( 23 "bytes" 24 "errors" 25 "flag" 26 "fmt" 27 "go/build" 28 "io" 29 "io/ioutil" 30 "log" 31 "os" 32 "os/exec" 33 "path/filepath" 34 "runtime" 35 "strings" 36 "sync" 37 "syscall" 38 "time" 39 ) 40 41 const debug = false 42 43 var errRetry = errors.New("failed to start test harness (retry attempted)") 44 45 var tmpdir string 46 47 var ( 48 devID string 49 appID string 50 teamID string 51 bundleID string 52 deviceID string 53 ) 54 55 // lock is a file lock to serialize iOS runs. It is global to avoid the 56 // garbage collector finalizing it, closing the file and releasing the 57 // lock prematurely. 58 var lock *os.File 59 60 func main() { 61 log.SetFlags(0) 62 log.SetPrefix("go_darwin_arm_exec: ") 63 if debug { 64 log.Println(strings.Join(os.Args, " ")) 65 } 66 if len(os.Args) < 2 { 67 log.Fatal("usage: go_darwin_arm_exec a.out") 68 } 69 70 // e.g. B393DDEB490947F5A463FD074299B6C0AXXXXXXX 71 devID = getenv("GOIOS_DEV_ID") 72 73 // e.g. Z8B3JBXXXX.org.golang.sample, Z8B3JBXXXX prefix is available at 74 // https://developer.apple.com/membercenter/index.action#accountSummary as Team ID. 75 appID = getenv("GOIOS_APP_ID") 76 77 // e.g. Z8B3JBXXXX, available at 78 // https://developer.apple.com/membercenter/index.action#accountSummary as Team ID. 79 teamID = getenv("GOIOS_TEAM_ID") 80 81 // Device IDs as listed with ios-deploy -c. 82 deviceID = os.Getenv("GOIOS_DEVICE_ID") 83 84 parts := strings.SplitN(appID, ".", 2) 85 // For compatibility with the old builders, use a fallback bundle ID 86 bundleID = "golang.gotest" 87 if len(parts) == 2 { 88 bundleID = parts[1] 89 } 90 91 var err error 92 tmpdir, err = ioutil.TempDir("", "go_darwin_arm_exec_") 93 if err != nil { 94 log.Fatal(err) 95 } 96 97 // This wrapper uses complicated machinery to run iOS binaries. It 98 // works, but only when running one binary at a time. 99 // Use a file lock to make sure only one wrapper is running at a time. 100 // 101 // The lock file is never deleted, to avoid concurrent locks on distinct 102 // files with the same path. 103 lockName := filepath.Join(os.TempDir(), "go_darwin_arm_exec-"+deviceID+".lock") 104 lock, err = os.OpenFile(lockName, os.O_CREATE|os.O_RDONLY, 0666) 105 if err != nil { 106 log.Fatal(err) 107 } 108 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil { 109 log.Fatal(err) 110 } 111 // Approximately 1 in a 100 binaries fail to start. If it happens, 112 // try again. These failures happen for several reasons beyond 113 // our control, but all of them are safe to retry as they happen 114 // before lldb encounters the initial getwd breakpoint. As we 115 // know the tests haven't started, we are not hiding flaky tests 116 // with this retry. 117 for i := 0; i < 5; i++ { 118 if i > 0 { 119 fmt.Fprintln(os.Stderr, "start timeout, trying again") 120 } 121 err = run(os.Args[1], os.Args[2:]) 122 if err == nil || err != errRetry { 123 break 124 } 125 } 126 if !debug { 127 os.RemoveAll(tmpdir) 128 } 129 if err != nil { 130 fmt.Fprintf(os.Stderr, "go_darwin_arm_exec: %v\n", err) 131 os.Exit(1) 132 } 133 } 134 135 func getenv(envvar string) string { 136 s := os.Getenv(envvar) 137 if s == "" { 138 log.Fatalf("%s not set\nrun $GOROOT/misc/ios/detect.go to attempt to autodetect", envvar) 139 } 140 return s 141 } 142 143 func run(bin string, args []string) (err error) { 144 appdir := filepath.Join(tmpdir, "gotest.app") 145 os.RemoveAll(appdir) 146 if err := os.MkdirAll(appdir, 0755); err != nil { 147 return err 148 } 149 150 if err := cp(filepath.Join(appdir, "gotest"), bin); err != nil { 151 return err 152 } 153 154 pkgpath, err := copyLocalData(appdir) 155 if err != nil { 156 return err 157 } 158 159 entitlementsPath := filepath.Join(tmpdir, "Entitlements.plist") 160 if err := ioutil.WriteFile(entitlementsPath, []byte(entitlementsPlist()), 0744); err != nil { 161 return err 162 } 163 if err := ioutil.WriteFile(filepath.Join(appdir, "Info.plist"), []byte(infoPlist(pkgpath)), 0744); err != nil { 164 return err 165 } 166 if err := ioutil.WriteFile(filepath.Join(appdir, "ResourceRules.plist"), []byte(resourceRules), 0744); err != nil { 167 return err 168 } 169 170 cmd := exec.Command( 171 "codesign", 172 "-f", 173 "-s", devID, 174 "--entitlements", entitlementsPath, 175 appdir, 176 ) 177 if debug { 178 log.Println(strings.Join(cmd.Args, " ")) 179 } 180 cmd.Stdout = os.Stdout 181 cmd.Stderr = os.Stderr 182 if err := cmd.Run(); err != nil { 183 return fmt.Errorf("codesign: %v", err) 184 } 185 186 oldwd, err := os.Getwd() 187 if err != nil { 188 return err 189 } 190 if err := os.Chdir(filepath.Join(appdir, "..")); err != nil { 191 return err 192 } 193 defer os.Chdir(oldwd) 194 195 // Setting up lldb is flaky. The test binary itself runs when 196 // started is set to true. Everything before that is considered 197 // part of the setup and is retried. 198 started := false 199 defer func() { 200 if r := recover(); r != nil { 201 if w, ok := r.(waitPanic); ok { 202 err = w.err 203 if !started { 204 fmt.Printf("lldb setup error: %v\n", err) 205 err = errRetry 206 } 207 return 208 } 209 panic(r) 210 } 211 }() 212 213 defer exec.Command("killall", "ios-deploy").Run() // cleanup 214 exec.Command("killall", "ios-deploy").Run() 215 216 var opts options 217 opts, args = parseArgs(args) 218 219 // ios-deploy invokes lldb to give us a shell session with the app. 220 s, err := newSession(appdir, args, opts) 221 if err != nil { 222 return err 223 } 224 defer func() { 225 b := s.out.Bytes() 226 if err == nil && !debug { 227 i := bytes.Index(b, []byte("(lldb) process continue")) 228 if i > 0 { 229 b = b[i:] 230 } 231 } 232 os.Stdout.Write(b) 233 }() 234 235 // Script LLDB. Oh dear. 236 s.do(`process handle SIGHUP --stop false --pass true --notify false`) 237 s.do(`process handle SIGPIPE --stop false --pass true --notify false`) 238 s.do(`process handle SIGUSR1 --stop false --pass true --notify false`) 239 s.do(`process handle SIGCONT --stop false --pass true --notify false`) 240 s.do(`process handle SIGSEGV --stop false --pass true --notify false`) // does not work 241 s.do(`process handle SIGBUS --stop false --pass true --notify false`) // does not work 242 243 if opts.lldb { 244 _, err := io.Copy(s.in, os.Stdin) 245 if err != io.EOF { 246 return err 247 } 248 return nil 249 } 250 251 started = true 252 253 s.doCmd("run", "stop reason = signal SIGINT", 20*time.Second) 254 255 startTestsLen := s.out.Len() 256 fmt.Fprintln(s.in, `process continue`) 257 258 passed := func(out *buf) bool { 259 // Just to make things fun, lldb sometimes translates \n into \r\n. 260 return s.out.LastIndex([]byte("\nPASS\n")) > startTestsLen || 261 s.out.LastIndex([]byte("\nPASS\r")) > startTestsLen || 262 s.out.LastIndex([]byte("\n(lldb) PASS\n")) > startTestsLen || 263 s.out.LastIndex([]byte("\n(lldb) PASS\r")) > startTestsLen || 264 s.out.LastIndex([]byte("exited with status = 0 (0x00000000) \n")) > startTestsLen || 265 s.out.LastIndex([]byte("exited with status = 0 (0x00000000) \r")) > startTestsLen 266 } 267 err = s.wait("test completion", passed, opts.timeout) 268 if passed(s.out) { 269 // The returned lldb error code is usually non-zero. 270 // We check for test success by scanning for the final 271 // PASS returned by the test harness, assuming the worst 272 // in its absence. 273 return nil 274 } 275 return err 276 } 277 278 type lldbSession struct { 279 cmd *exec.Cmd 280 in *os.File 281 out *buf 282 timedout chan struct{} 283 exited chan error 284 } 285 286 func newSession(appdir string, args []string, opts options) (*lldbSession, error) { 287 lldbr, in, err := os.Pipe() 288 if err != nil { 289 return nil, err 290 } 291 s := &lldbSession{ 292 in: in, 293 out: new(buf), 294 exited: make(chan error), 295 } 296 297 iosdPath, err := exec.LookPath("ios-deploy") 298 if err != nil { 299 return nil, err 300 } 301 cmdArgs := []string{ 302 // lldb tries to be clever with terminals. 303 // So we wrap it in script(1) and be clever 304 // right back at it. 305 "script", 306 "-q", "-t", "0", 307 "/dev/null", 308 309 iosdPath, 310 "--debug", 311 "-u", 312 "-r", 313 "-n", 314 `--args=` + strings.Join(args, " ") + ``, 315 "--bundle", appdir, 316 } 317 if deviceID != "" { 318 cmdArgs = append(cmdArgs, "--id", deviceID) 319 } 320 s.cmd = exec.Command(cmdArgs[0], cmdArgs[1:]...) 321 if debug { 322 log.Println(strings.Join(s.cmd.Args, " ")) 323 } 324 325 var out io.Writer = s.out 326 if opts.lldb { 327 out = io.MultiWriter(out, os.Stderr) 328 } 329 s.cmd.Stdout = out 330 s.cmd.Stderr = out // everything of interest is on stderr 331 s.cmd.Stdin = lldbr 332 333 if err := s.cmd.Start(); err != nil { 334 return nil, fmt.Errorf("ios-deploy failed to start: %v", err) 335 } 336 337 // Manage the -test.timeout here, outside of the test. There is a lot 338 // of moving parts in an iOS test harness (notably lldb) that can 339 // swallow useful stdio or cause its own ruckus. 340 if opts.timeout > 1*time.Second { 341 s.timedout = make(chan struct{}) 342 time.AfterFunc(opts.timeout-1*time.Second, func() { 343 close(s.timedout) 344 }) 345 } 346 347 go func() { 348 s.exited <- s.cmd.Wait() 349 }() 350 351 cond := func(out *buf) bool { 352 i0 := s.out.LastIndex([]byte("(lldb)")) 353 i1 := s.out.LastIndex([]byte("fruitstrap")) 354 i2 := s.out.LastIndex([]byte(" connect")) 355 return i0 > 0 && i1 > 0 && i2 > 0 356 } 357 if err := s.wait("lldb start", cond, 15*time.Second); err != nil { 358 panic(waitPanic{err}) 359 } 360 return s, nil 361 } 362 363 func (s *lldbSession) do(cmd string) { s.doCmd(cmd, "(lldb)", 0) } 364 365 func (s *lldbSession) doCmd(cmd string, waitFor string, extraTimeout time.Duration) { 366 startLen := s.out.Len() 367 fmt.Fprintln(s.in, cmd) 368 cond := func(out *buf) bool { 369 i := s.out.LastIndex([]byte(waitFor)) 370 return i > startLen 371 } 372 if err := s.wait(fmt.Sprintf("running cmd %q", cmd), cond, extraTimeout); err != nil { 373 panic(waitPanic{err}) 374 } 375 } 376 377 func (s *lldbSession) wait(reason string, cond func(out *buf) bool, extraTimeout time.Duration) error { 378 doTimeout := 2*time.Second + extraTimeout 379 doTimedout := time.After(doTimeout) 380 for { 381 select { 382 case <-s.timedout: 383 if p := s.cmd.Process; p != nil { 384 p.Kill() 385 } 386 return fmt.Errorf("test timeout (%s)", reason) 387 case <-doTimedout: 388 return fmt.Errorf("command timeout (%s for %v)", reason, doTimeout) 389 case err := <-s.exited: 390 return fmt.Errorf("exited (%s: %v)", reason, err) 391 default: 392 if cond(s.out) { 393 return nil 394 } 395 time.Sleep(20 * time.Millisecond) 396 } 397 } 398 } 399 400 type buf struct { 401 mu sync.Mutex 402 buf []byte 403 } 404 405 func (w *buf) Write(in []byte) (n int, err error) { 406 w.mu.Lock() 407 defer w.mu.Unlock() 408 w.buf = append(w.buf, in...) 409 return len(in), nil 410 } 411 412 func (w *buf) LastIndex(sep []byte) int { 413 w.mu.Lock() 414 defer w.mu.Unlock() 415 return bytes.LastIndex(w.buf, sep) 416 } 417 418 func (w *buf) Bytes() []byte { 419 w.mu.Lock() 420 defer w.mu.Unlock() 421 422 b := make([]byte, len(w.buf)) 423 copy(b, w.buf) 424 return b 425 } 426 427 func (w *buf) Len() int { 428 w.mu.Lock() 429 defer w.mu.Unlock() 430 return len(w.buf) 431 } 432 433 type waitPanic struct { 434 err error 435 } 436 437 type options struct { 438 timeout time.Duration 439 lldb bool 440 } 441 442 func parseArgs(binArgs []string) (opts options, remainingArgs []string) { 443 var flagArgs []string 444 for _, arg := range binArgs { 445 if strings.Contains(arg, "-test.timeout") { 446 flagArgs = append(flagArgs, arg) 447 } 448 if strings.Contains(arg, "-lldb") { 449 flagArgs = append(flagArgs, arg) 450 continue 451 } 452 remainingArgs = append(remainingArgs, arg) 453 } 454 f := flag.NewFlagSet("", flag.ContinueOnError) 455 f.DurationVar(&opts.timeout, "test.timeout", 10*time.Minute, "") 456 f.BoolVar(&opts.lldb, "lldb", false, "") 457 f.Parse(flagArgs) 458 return opts, remainingArgs 459 460 } 461 462 func copyLocalDir(dst, src string) error { 463 if err := os.Mkdir(dst, 0755); err != nil { 464 return err 465 } 466 467 d, err := os.Open(src) 468 if err != nil { 469 return err 470 } 471 defer d.Close() 472 fi, err := d.Readdir(-1) 473 if err != nil { 474 return err 475 } 476 477 for _, f := range fi { 478 if f.IsDir() { 479 if f.Name() == "testdata" { 480 if err := cp(dst, filepath.Join(src, f.Name())); err != nil { 481 return err 482 } 483 } 484 continue 485 } 486 if err := cp(dst, filepath.Join(src, f.Name())); err != nil { 487 return err 488 } 489 } 490 return nil 491 } 492 493 func cp(dst, src string) error { 494 out, err := exec.Command("cp", "-a", src, dst).CombinedOutput() 495 if err != nil { 496 os.Stderr.Write(out) 497 } 498 return err 499 } 500 501 func copyLocalData(dstbase string) (pkgpath string, err error) { 502 cwd, err := os.Getwd() 503 if err != nil { 504 return "", err 505 } 506 507 finalPkgpath, underGoRoot, err := subdir() 508 if err != nil { 509 return "", err 510 } 511 cwd = strings.TrimSuffix(cwd, finalPkgpath) 512 513 // Copy all immediate files and testdata directories between 514 // the package being tested and the source root. 515 pkgpath = "" 516 for _, element := range strings.Split(finalPkgpath, string(filepath.Separator)) { 517 if debug { 518 log.Printf("copying %s", pkgpath) 519 } 520 pkgpath = filepath.Join(pkgpath, element) 521 dst := filepath.Join(dstbase, pkgpath) 522 src := filepath.Join(cwd, pkgpath) 523 if err := copyLocalDir(dst, src); err != nil { 524 return "", err 525 } 526 } 527 528 if underGoRoot { 529 // Copy timezone file. 530 // 531 // Typical apps have the zoneinfo.zip in the root of their app bundle, 532 // read by the time package as the working directory at initialization. 533 // As we move the working directory to the GOROOT pkg directory, we 534 // install the zoneinfo.zip file in the pkgpath. 535 err := cp( 536 filepath.Join(dstbase, pkgpath), 537 filepath.Join(cwd, "lib", "time", "zoneinfo.zip"), 538 ) 539 if err != nil { 540 return "", err 541 } 542 // Copy src/runtime/textflag.h for (at least) Test386EndToEnd in 543 // cmd/asm/internal/asm. 544 runtimePath := filepath.Join(dstbase, "src", "runtime") 545 if err := os.MkdirAll(runtimePath, 0755); err != nil { 546 return "", err 547 } 548 err = cp( 549 filepath.Join(runtimePath, "textflag.h"), 550 filepath.Join(cwd, "src", "runtime", "textflag.h"), 551 ) 552 if err != nil { 553 return "", err 554 } 555 } 556 557 return finalPkgpath, nil 558 } 559 560 // subdir determines the package based on the current working directory, 561 // and returns the path to the package source relative to $GOROOT (or $GOPATH). 562 func subdir() (pkgpath string, underGoRoot bool, err error) { 563 cwd, err := os.Getwd() 564 if err != nil { 565 return "", false, err 566 } 567 if root := runtime.GOROOT(); strings.HasPrefix(cwd, root) { 568 subdir, err := filepath.Rel(root, cwd) 569 if err != nil { 570 return "", false, err 571 } 572 return subdir, true, nil 573 } 574 575 for _, p := range filepath.SplitList(build.Default.GOPATH) { 576 if !strings.HasPrefix(cwd, p) { 577 continue 578 } 579 subdir, err := filepath.Rel(p, cwd) 580 if err == nil { 581 return subdir, false, nil 582 } 583 } 584 return "", false, fmt.Errorf( 585 "working directory %q is not in either GOROOT(%q) or GOPATH(%q)", 586 cwd, 587 runtime.GOROOT(), 588 build.Default.GOPATH, 589 ) 590 } 591 592 func infoPlist(pkgpath string) string { 593 return `<?xml version="1.0" encoding="UTF-8"?> 594 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 595 <plist version="1.0"> 596 <dict> 597 <key>CFBundleName</key><string>golang.gotest</string> 598 <key>CFBundleSupportedPlatforms</key><array><string>iPhoneOS</string></array> 599 <key>CFBundleExecutable</key><string>gotest</string> 600 <key>CFBundleVersion</key><string>1.0</string> 601 <key>CFBundleIdentifier</key><string>` + bundleID + `</string> 602 <key>CFBundleResourceSpecification</key><string>ResourceRules.plist</string> 603 <key>LSRequiresIPhoneOS</key><true/> 604 <key>CFBundleDisplayName</key><string>gotest</string> 605 <key>GoExecWrapperWorkingDirectory</key><string>` + pkgpath + `</string> 606 </dict> 607 </plist> 608 ` 609 } 610 611 func entitlementsPlist() string { 612 return `<?xml version="1.0" encoding="UTF-8"?> 613 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 614 <plist version="1.0"> 615 <dict> 616 <key>keychain-access-groups</key> 617 <array><string>` + appID + `</string></array> 618 <key>get-task-allow</key> 619 <true/> 620 <key>application-identifier</key> 621 <string>` + appID + `</string> 622 <key>com.apple.developer.team-identifier</key> 623 <string>` + teamID + `</string> 624 </dict> 625 </plist> 626 ` 627 } 628 629 const resourceRules = `<?xml version="1.0" encoding="UTF-8"?> 630 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 631 <plist version="1.0"> 632 <dict> 633 <key>rules</key> 634 <dict> 635 <key>.*</key> 636 <true/> 637 <key>Info.plist</key> 638 <dict> 639 <key>omit</key> 640 <true/> 641 <key>weight</key> 642 <integer>10</integer> 643 </dict> 644 <key>ResourceRules.plist</key> 645 <dict> 646 <key>omit</key> 647 <true/> 648 <key>weight</key> 649 <integer>100</integer> 650 </dict> 651 </dict> 652 </dict> 653 </plist> 654 `