github.com/wencode/hack@v0.2.9/test/proc_test.go (about)

     1  package proc
     2  
     3  import (
     4  	"runtime"
     5  	"testing"
     6  	"unsafe"
     7  
     8  	"github.com/wencode/hack/dl"
     9  	"github.com/wencode/hack/proc"
    10  
    11  	"github.com/wencode/hack/test/cgocall"
    12  )
    13  
    14  var (
    15  	libcfile     string
    16  	write_symbol string
    17  )
    18  
    19  func init() {
    20  	switch runtime.GOOS {
    21  	case "darwin":
    22  		libcfile = "/usr/lib/libc.dylib"
    23  		write_symbol = "write"
    24  	case "windows":
    25  		libcfile = "msvcrt.dll"
    26  		write_symbol = "_write"
    27  	default:
    28  		libcfile = "libc.so.6"
    29  		write_symbol = "write"
    30  	}
    31  
    32  }
    33  
    34  func TestWrite(t *testing.T) {
    35  	lib, err := dl.Open(libcfile)
    36  	if err != nil {
    37  		t.Fatal(err)
    38  	}
    39  	defer lib.Close()
    40  	write_addr := lib.Sym(write_symbol)
    41  	if write_addr == 0 {
    42  		t.Fatalf("can't find write symbol")
    43  	}
    44  
    45  	str := []byte("hello,world\n")
    46  	l := proc.Call(write_addr, 1, uintptr(unsafe.Pointer(&(str[0]))), uintptr(len(str)))
    47  	if int(l) != len(str) {
    48  		t.Errorf("call write failed")
    49  	}
    50  }
    51  
    52  func TestExit(t *testing.T) {
    53  	lib, err := dl.Open(libcfile)
    54  	if err != nil {
    55  		t.Fatal(err)
    56  	}
    57  	defer lib.Close()
    58  	exit_addr := lib.Sym("exit")
    59  	if exit_addr == 0 {
    60  		t.Fatalf("can't find exit symbol")
    61  	}
    62  	proc.Call(exit_addr, 0)
    63  }
    64  
    65  func BenchmarkAbsCGO(b *testing.B) {
    66  	for i := 0; i < b.N; i++ {
    67  		cgocall.Abs(i)
    68  	}
    69  }
    70  
    71  func BenchmarkAbsProc(b *testing.B) {
    72  	b.StopTimer()
    73  	lib, err := dl.Open(libcfile)
    74  	if err != nil {
    75  		b.Fatal(err)
    76  	}
    77  	defer lib.Close()
    78  	abs_addr := lib.Sym("abs")
    79  	if abs_addr == 0 {
    80  		b.Fatal("can't find abs symbol")
    81  	}
    82  
    83  	b.StartTimer()
    84  	for i := 0; i < b.N; i++ {
    85  		proc.Call(abs_addr, uintptr(i))
    86  	}
    87  }