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