// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bufio"
	"bytes"
	"internal/testenv"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

// TestMain executes the test binary as the addr2line command if
// GO_ADDR2LINETEST_IS_ADDR2LINE is set, and runs the tests otherwise.
func TestMain(m *testing.M) {
	if os.Getenv("GO_ADDR2LINETEST_IS_ADDR2LINE") != "" {
		main()
		os.Exit(0)
	}

	os.Setenv("GO_ADDR2LINETEST_IS_ADDR2LINE", "1") // Set for subprocesses to inherit.
	os.Exit(m.Run())
}

func loadSyms(t *testing.T, dbgExePath string) map[string]string {
	cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "nm", dbgExePath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("%v: %v\n%s", cmd, err, string(out))
	}
	syms := make(map[string]string)
	scanner := bufio.NewScanner(bytes.NewReader(out))
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) < 3 {
			continue
		}
		syms[f[2]] = f[0]
	}
	if err := scanner.Err(); err != nil {
		t.Fatalf("error reading symbols: %v", err)
	}
	return syms
}
