• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 2016, Google Inc.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15//go:build ignore
16
17package main
18
19import (
20	"bufio"
21	"bytes"
22	"errors"
23	"flag"
24	"fmt"
25	"io"
26	"os"
27	"os/exec"
28	"path/filepath"
29	"runtime"
30	"strconv"
31	"strings"
32
33	"boringssl.googlesource.com/boringssl/util/testconfig"
34)
35
36var (
37	buildDir     = flag.String("build-dir", "build", "Specifies the build directory to push.")
38	adbPath      = flag.String("adb", "adb", "Specifies the adb binary to use. Defaults to looking in PATH.")
39	ndkPath      = flag.String("ndk", "", "Specifies the path to the NDK installation. Defaults to detecting from the build directory.")
40	device       = flag.String("device", "", "Specifies the device or emulator. See adb's -s argument.")
41	abi          = flag.String("abi", "", "Specifies the Android ABI to use when building Go tools. Defaults to detecting from the build directory.")
42	apiLevel     = flag.Int("api-level", 0, "Specifies the Android API level to use when building Go tools. Defaults to detecting from the build directory.")
43	suite        = flag.String("suite", "all", "Specifies the test suites to run (all, unit, or ssl).")
44	allTestsArgs = flag.String("all-tests-args", "", "Specifies space-separated arguments to pass to all_tests.go")
45	runnerArgs   = flag.String("runner-args", "", "Specifies space-separated arguments to pass to ssl/test/runner")
46	jsonOutput   = flag.String("json-output", "", "The file to output JSON results to.")
47)
48
49func enableUnitTests() bool {
50	return *suite == "all" || *suite == "unit"
51}
52
53func enableSSLTests() bool {
54	return *suite == "all" || *suite == "ssl"
55}
56
57func adb(args ...string) error {
58	if len(*device) > 0 {
59		args = append([]string{"-s", *device}, args...)
60	}
61	cmd := exec.Command(*adbPath, args...)
62	cmd.Stdout = os.Stdout
63	cmd.Stderr = os.Stderr
64	return cmd.Run()
65}
66
67func adbShell(shellCmd string) (int, error) {
68	var args []string
69	if len(*device) > 0 {
70		args = append([]string{"-s", *device}, args...)
71	}
72	args = append(args, "shell")
73
74	const delimiter = "___EXIT_CODE___"
75
76	// Older versions of adb and Android do not preserve the exit
77	// code, so work around this.
78	// https://code.google.com/p/android/issues/detail?id=3254
79	shellCmd += "; echo " + delimiter + " $?"
80	args = append(args, shellCmd)
81
82	cmd := exec.Command(*adbPath, args...)
83	stdout, err := cmd.StdoutPipe()
84	if err != nil {
85		return 0, err
86	}
87	cmd.Stderr = os.Stderr
88	if err := cmd.Start(); err != nil {
89		return 0, err
90	}
91
92	var stdoutBytes bytes.Buffer
93	for {
94		var buf [1024]byte
95		n, err := stdout.Read(buf[:])
96		stdoutBytes.Write(buf[:n])
97		os.Stdout.Write(buf[:n])
98		if err != nil {
99			break
100		}
101	}
102
103	if err := cmd.Wait(); err != nil {
104		return 0, err
105	}
106
107	stdoutStr := stdoutBytes.String()
108	idx := strings.LastIndex(stdoutStr, delimiter)
109	if idx < 0 {
110		return 0, fmt.Errorf("Could not find delimiter in output.")
111	}
112
113	return strconv.Atoi(strings.TrimSpace(stdoutStr[idx+len(delimiter):]))
114}
115
116func goTool(args ...string) error {
117	cmd := exec.Command("go", args...)
118	cmd.Stdout = os.Stdout
119	cmd.Stderr = os.Stderr
120
121	cmd.Env = os.Environ()
122
123	// The NDK includes the host platform in the toolchain path.
124	var ndkOS, ndkArch string
125	switch runtime.GOOS {
126	case "linux":
127		ndkOS = "linux"
128	default:
129		return fmt.Errorf("unknown host OS: %q", runtime.GOOS)
130	}
131	switch runtime.GOARCH {
132	case "amd64":
133		ndkArch = "x86_64"
134	default:
135		return fmt.Errorf("unknown host architecture: %q", runtime.GOARCH)
136	}
137	ndkHost := ndkOS + "-" + ndkArch
138
139	// Use the NDK's target-prefixed clang wrappers, so cgo gets the right
140	// flags. See https://developer.android.com/ndk/guides/cmake#android_abi for
141	// Android ABIs.
142	var targetPrefix string
143	switch *abi {
144	case "armeabi-v7a", "armeabi-v7a with NEON":
145		targetPrefix = fmt.Sprintf("armv7a-linux-androideabi%d-", *apiLevel)
146		cmd.Env = append(cmd.Env, "GOARCH=arm")
147		cmd.Env = append(cmd.Env, "GOARM=7")
148	case "arm64-v8a":
149		targetPrefix = fmt.Sprintf("aarch64-linux-android%d-", *apiLevel)
150		cmd.Env = append(cmd.Env, "GOARCH=arm64")
151	default:
152		fmt.Errorf("unknown Android ABI: %q", *abi)
153	}
154
155	// Go's Android support requires cgo and compilers from the NDK. See
156	// https://golang.org/misc/android/README, though note CC_FOR_TARGET only
157	// works when building Go itself. go build only looks at CC.
158	cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
159	cmd.Env = append(cmd.Env, "GOOS=android")
160	toolchainDir := filepath.Join(*ndkPath, "toolchains", "llvm", "prebuilt", ndkHost, "bin")
161	cmd.Env = append(cmd.Env, fmt.Sprintf("CC=%s", filepath.Join(toolchainDir, targetPrefix+"clang")))
162	cmd.Env = append(cmd.Env, fmt.Sprintf("CXX=%s", filepath.Join(toolchainDir, targetPrefix+"clang++")))
163	return cmd.Run()
164}
165
166// setWorkingDirectory walks up directories as needed until the current working
167// directory is the top of a BoringSSL checkout.
168func setWorkingDirectory() {
169	for i := 0; i < 64; i++ {
170		if _, err := os.Stat("BUILDING.md"); err == nil {
171			return
172		}
173		os.Chdir("..")
174	}
175
176	panic("Couldn't find BUILDING.md in a parent directory!")
177}
178
179func detectOptionsFromCMake() error {
180	if len(*ndkPath) != 0 && len(*abi) != 0 && *apiLevel != 0 {
181		// No need to parse options from CMake.
182		return nil
183	}
184
185	cmakeCache, err := os.Open(filepath.Join(*buildDir, "CMakeCache.txt"))
186	if err != nil {
187		return err
188	}
189	defer cmakeCache.Close()
190
191	cmakeVars := make(map[string]string)
192	scanner := bufio.NewScanner(cmakeCache)
193	for scanner.Scan() {
194		line := scanner.Text()
195		if idx := strings.IndexByte(line, '#'); idx >= 0 {
196			line = line[:idx]
197		}
198		if idx := strings.Index(line, "//"); idx >= 0 {
199			line = line[:idx]
200		}
201		// The syntax for each line is KEY:TYPE=VALUE.
202		equals := strings.IndexByte(line, '=')
203		if equals < 0 {
204			continue
205		}
206		name := line[:equals]
207		value := line[equals+1:]
208		if idx := strings.IndexByte(name, ':'); idx >= 0 {
209			name = name[:idx]
210		}
211		cmakeVars[name] = value
212	}
213	if err := scanner.Err(); err != nil {
214		return err
215	}
216
217	if len(*ndkPath) == 0 {
218		if ndk, ok := cmakeVars["ANDROID_NDK"]; ok {
219			*ndkPath = ndk
220		} else if toolchainFile, ok := cmakeVars["CMAKE_TOOLCHAIN_FILE"]; ok {
221			// The toolchain is at build/cmake/android.toolchain.cmake under the NDK.
222			*ndkPath = filepath.Dir(filepath.Dir(filepath.Dir(toolchainFile)))
223		} else {
224			return errors.New("Neither CMAKE_TOOLCHAIN_FILE nor ANDROID_NDK found in CMakeCache.txt")
225		}
226		fmt.Printf("Detected NDK path %q from CMakeCache.txt.\n", *ndkPath)
227	}
228	if len(*abi) == 0 {
229		var ok bool
230		if *abi, ok = cmakeVars["ANDROID_ABI"]; !ok {
231			return errors.New("ANDROID_ABI not found in CMakeCache.txt")
232		}
233		fmt.Printf("Detected ABI %q from CMakeCache.txt.\n", *abi)
234	}
235	if *apiLevel == 0 {
236		apiLevelStr, ok := cmakeVars["ANDROID_PLATFORM"]
237		if !ok {
238			return errors.New("ANDROID_PLATFORM not found in CMakeCache.txt")
239		}
240		apiLevelStr = strings.TrimPrefix(apiLevelStr, "android-")
241		var err error
242		if *apiLevel, err = strconv.Atoi(apiLevelStr); err != nil {
243			return fmt.Errorf("error parsing ANDROID_PLATFORM: %s", err)
244		}
245		fmt.Printf("Detected API level %d from CMakeCache.txt.\n", *apiLevel)
246	}
247	return nil
248}
249
250func copyFile(dst, src string) error {
251	srcFile, err := os.Open(src)
252	if err != nil {
253		return err
254	}
255	defer srcFile.Close()
256
257	srcInfo, err := srcFile.Stat()
258	if err != nil {
259		return err
260	}
261
262	dir := filepath.Dir(dst)
263	if err := os.MkdirAll(dir, 0777); err != nil {
264		return err
265	}
266
267	dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, srcInfo.Mode())
268	if err != nil {
269		return err
270	}
271	defer dstFile.Close()
272
273	_, err = io.Copy(dstFile, srcFile)
274	return err
275}
276
277func main() {
278	flag.Parse()
279
280	if *suite == "all" && *jsonOutput != "" {
281		fmt.Printf("To use -json-output flag, select only one test suite with -suite.\n")
282		os.Exit(1)
283	}
284
285	setWorkingDirectory()
286	if err := detectOptionsFromCMake(); err != nil {
287		fmt.Printf("Error reading options from CMake: %s.\n", err)
288		os.Exit(1)
289	}
290
291	// Clear the target directory.
292	if err := adb("shell", "rm -Rf /data/local/tmp/boringssl-tmp"); err != nil {
293		fmt.Printf("Failed to clear target directory: %s\n", err)
294		os.Exit(1)
295	}
296
297	// Stage everything in a temporary directory.
298	tmpDir, err := os.MkdirTemp("", "boringssl-android")
299	if err != nil {
300		fmt.Printf("Error making temporary directory: %s\n", err)
301		os.Exit(1)
302	}
303	defer os.RemoveAll(tmpDir)
304
305	var binaries, files []string
306
307	if enableUnitTests() {
308		files = append(files,
309			"util/all_tests.json",
310			"BUILDING.md",
311		)
312
313		err := filepath.Walk("pki/testdata/", func(path string, info os.FileInfo, err error) error {
314			if err != nil {
315				return err
316			}
317			if info.Mode().IsRegular() {
318				files = append(files, path)
319			}
320			return nil
321		})
322		if err != nil {
323			fmt.Printf("Can't walk pki/testdata: %s\n", err)
324			os.Exit(1)
325		}
326
327		tests, err := testconfig.ParseTestConfig("util/all_tests.json")
328		if err != nil {
329			fmt.Printf("Failed to parse input: %s\n", err)
330			os.Exit(1)
331		}
332
333		seenBinary := make(map[string]struct{})
334		for _, test := range tests {
335			if _, ok := seenBinary[test.Cmd[0]]; !ok {
336				binaries = append(binaries, test.Cmd[0])
337				seenBinary[test.Cmd[0]] = struct{}{}
338			}
339			for _, arg := range test.Cmd[1:] {
340				if strings.Contains(arg, "/") {
341					files = append(files, arg)
342				}
343			}
344		}
345
346		fmt.Printf("Building all_tests...\n")
347		if err := goTool("build", "-o", filepath.Join(tmpDir, "util/all_tests"), "util/all_tests.go"); err != nil {
348			fmt.Printf("Error building all_tests.go: %s\n", err)
349			os.Exit(1)
350		}
351	}
352
353	if enableSSLTests() {
354		binaries = append(binaries, "ssl/test/bssl_shim")
355		files = append(files,
356			"BUILDING.md",
357			"ssl/test/runner/cert.pem",
358			"ssl/test/runner/channel_id_key.pem",
359			"ssl/test/runner/ecdsa_p224_cert.pem",
360			"ssl/test/runner/ecdsa_p224_key.pem",
361			"ssl/test/runner/ecdsa_p256_cert.pem",
362			"ssl/test/runner/ecdsa_p256_key.pem",
363			"ssl/test/runner/ecdsa_p384_cert.pem",
364			"ssl/test/runner/ecdsa_p384_key.pem",
365			"ssl/test/runner/ecdsa_p521_cert.pem",
366			"ssl/test/runner/ecdsa_p521_key.pem",
367			"ssl/test/runner/ed25519_cert.pem",
368			"ssl/test/runner/ed25519_key.pem",
369			"ssl/test/runner/key.pem",
370			"ssl/test/runner/rsa_1024_cert.pem",
371			"ssl/test/runner/rsa_1024_key.pem",
372			"ssl/test/runner/rsa_chain_cert.pem",
373			"ssl/test/runner/rsa_chain_key.pem",
374			"util/all_tests.json",
375		)
376
377		fmt.Printf("Building runner...\n")
378		if err := goTool("test", "-c", "-o", filepath.Join(tmpDir, "ssl/test/runner/runner"), "./ssl/test/runner/"); err != nil {
379			fmt.Printf("Error building runner: %s\n", err)
380			os.Exit(1)
381		}
382	}
383
384	var libraries []string
385	if _, err := os.Stat(filepath.Join(*buildDir, "crypto/libcrypto.so")); err == nil {
386		libraries = []string{
387			"libboringssl_gtest.so",
388			"libpki.so",
389			"crypto/libcrypto.so",
390			"decrepit/libdecrepit.so",
391			"ssl/libssl.so",
392		}
393	} else if !os.IsNotExist(err) {
394		fmt.Printf("Failed to stat crypto/libcrypto.so: %s\n", err)
395		os.Exit(1)
396	}
397
398	fmt.Printf("Copying test binaries...\n")
399	for _, binary := range binaries {
400		if err := copyFile(filepath.Join(tmpDir, "build", binary), filepath.Join(*buildDir, binary)); err != nil {
401			fmt.Printf("Failed to copy %s: %s\n", binary, err)
402			os.Exit(1)
403		}
404	}
405
406	var envPrefix string
407	if len(libraries) > 0 {
408		fmt.Printf("Copying libraries...\n")
409		for _, library := range libraries {
410			// Place all the libraries in a common directory so they
411			// can be passed to LD_LIBRARY_PATH once.
412			if err := copyFile(filepath.Join(tmpDir, "build", "lib", filepath.Base(library)), filepath.Join(*buildDir, library)); err != nil {
413				fmt.Printf("Failed to copy %s: %s\n", library, err)
414				os.Exit(1)
415			}
416		}
417		envPrefix = "env LD_LIBRARY_PATH=/data/local/tmp/boringssl-tmp/build/lib "
418	}
419
420	fmt.Printf("Copying data files...\n")
421	for _, file := range files {
422		if err := copyFile(filepath.Join(tmpDir, file), file); err != nil {
423			fmt.Printf("Failed to copy %s: %s\n", file, err)
424			os.Exit(1)
425		}
426	}
427
428	fmt.Printf("Uploading files...\n")
429	if err := adb("push", "-p", tmpDir, "/data/local/tmp/boringssl-tmp"); err != nil {
430		fmt.Printf("Failed to push runner: %s\n", err)
431		os.Exit(1)
432	}
433
434	var unitTestExit int
435	if enableUnitTests() {
436		fmt.Printf("Running unit tests...\n")
437		unitTestExit, err = adbShell(fmt.Sprintf("cd /data/local/tmp/boringssl-tmp && %s./util/all_tests -json-output results.json %s", envPrefix, *allTestsArgs))
438		if err != nil {
439			fmt.Printf("Failed to run unit tests: %s\n", err)
440			os.Exit(1)
441		}
442	}
443
444	var sslTestExit int
445	if enableSSLTests() {
446		fmt.Printf("Running SSL tests...\n")
447		sslTestExit, err = adbShell(fmt.Sprintf("cd /data/local/tmp/boringssl-tmp/ssl/test/runner && %s./runner -json-output ../../../results.json %s", envPrefix, *runnerArgs))
448		if err != nil {
449			fmt.Printf("Failed to run SSL tests: %s\n", err)
450			os.Exit(1)
451		}
452	}
453
454	if *jsonOutput != "" {
455		if err := adb("pull", "-p", "/data/local/tmp/boringssl-tmp/results.json", *jsonOutput); err != nil {
456			fmt.Printf("Failed to extract results.json: %s\n", err)
457			os.Exit(1)
458		}
459	}
460
461	if unitTestExit != 0 {
462		os.Exit(unitTestExit)
463	}
464
465	if sslTestExit != 0 {
466		os.Exit(sslTestExit)
467	}
468}
469