github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/internal/abi/abi_test.go (about)

     1  // Copyright 2021 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 abi_test
     6  
     7  import (
     8  	"os/exec"
     9  	"path/filepath"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/hxx258456/ccgo/internal/abi"
    14  	"github.com/hxx258456/ccgo/internal/testenv"
    15  )
    16  
    17  func TestFuncPC(t *testing.T) {
    18  	// Test that FuncPC* can get correct function PC.
    19  	pcFromAsm := abi.FuncPCTestFnAddr
    20  
    21  	// Test FuncPC for locally defined function
    22  	pcFromGo := abi.FuncPCTest()
    23  	if pcFromGo != pcFromAsm {
    24  		t.Errorf("FuncPC returns wrong PC, want %x, got %x", pcFromAsm, pcFromGo)
    25  	}
    26  
    27  	// Test FuncPC for imported function
    28  	pcFromGo = abi.FuncPCABI0(abi.FuncPCTestFn)
    29  	if pcFromGo != pcFromAsm {
    30  		t.Errorf("FuncPC returns wrong PC, want %x, got %x", pcFromAsm, pcFromGo)
    31  	}
    32  }
    33  
    34  func TestFuncPCCompileError(t *testing.T) {
    35  	// Test that FuncPC* on a function of a mismatched ABI is rejected.
    36  	testenv.MustHaveGoBuild(t)
    37  
    38  	// We want to test internal package, which we cannot normally import.
    39  	// Run the assembler and compiler manually.
    40  	tmpdir := t.TempDir()
    41  	asmSrc := filepath.Join("testdata", "x.s")
    42  	goSrc := filepath.Join("testdata", "x.go")
    43  	symabi := filepath.Join(tmpdir, "symabi")
    44  	obj := filepath.Join(tmpdir, "x.o")
    45  
    46  	// parse assembly code for symabi.
    47  	cmd := exec.Command(testenv.GoToolPath(t), "tool", "asm", "-gensymabis", "-o", symabi, asmSrc)
    48  	out, err := cmd.CombinedOutput()
    49  	if err != nil {
    50  		t.Fatalf("go tool asm -gensymabis failed: %v\n%s", err, out)
    51  	}
    52  
    53  	// compile go code.
    54  	cmd = exec.Command(testenv.GoToolPath(t), "tool", "compile", "-symabis", symabi, "-o", obj, goSrc)
    55  	out, err = cmd.CombinedOutput()
    56  	if err == nil {
    57  		t.Fatalf("go tool compile did not fail")
    58  	}
    59  
    60  	// Expect errors in line 17, 18, 20, no errors on other lines.
    61  	want := []string{"x.go:17", "x.go:18", "x.go:20"}
    62  	got := strings.Split(string(out), "\n")
    63  	if got[len(got)-1] == "" {
    64  		got = got[:len(got)-1] // remove last empty line
    65  	}
    66  	for i, s := range got {
    67  		if !strings.Contains(s, want[i]) {
    68  			t.Errorf("did not error on line %s", want[i])
    69  		}
    70  	}
    71  	if len(got) != len(want) {
    72  		t.Errorf("unexpected number of errors, want %d, got %d", len(want), len(got))
    73  	}
    74  	if t.Failed() {
    75  		t.Logf("output:\n%s", string(out))
    76  	}
    77  }