...
Run Format

Source file src/runtime/syscall_windows_test.go

Documentation: runtime

     1  // Copyright 2010 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 runtime_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"internal/syscall/windows/sysdll"
    11  	"internal/testenv"
    12  	"io/ioutil"
    13  	"math"
    14  	"os"
    15  	"os/exec"
    16  	"path/filepath"
    17  	"runtime"
    18  	"strconv"
    19  	"strings"
    20  	"syscall"
    21  	"testing"
    22  	"unsafe"
    23  )
    24  
    25  type DLL struct {
    26  	*syscall.DLL
    27  	t *testing.T
    28  }
    29  
    30  func GetDLL(t *testing.T, name string) *DLL {
    31  	d, e := syscall.LoadDLL(name)
    32  	if e != nil {
    33  		t.Fatal(e)
    34  	}
    35  	return &DLL{DLL: d, t: t}
    36  }
    37  
    38  func (d *DLL) Proc(name string) *syscall.Proc {
    39  	p, e := d.FindProc(name)
    40  	if e != nil {
    41  		d.t.Fatal(e)
    42  	}
    43  	return p
    44  }
    45  
    46  func TestStdCall(t *testing.T) {
    47  	type Rect struct {
    48  		left, top, right, bottom int32
    49  	}
    50  	res := Rect{}
    51  	expected := Rect{1, 1, 40, 60}
    52  	a, _, _ := GetDLL(t, "user32.dll").Proc("UnionRect").Call(
    53  		uintptr(unsafe.Pointer(&res)),
    54  		uintptr(unsafe.Pointer(&Rect{10, 1, 14, 60})),
    55  		uintptr(unsafe.Pointer(&Rect{1, 2, 40, 50})))
    56  	if a != 1 || res.left != expected.left ||
    57  		res.top != expected.top ||
    58  		res.right != expected.right ||
    59  		res.bottom != expected.bottom {
    60  		t.Error("stdcall USER32.UnionRect returns", a, "res=", res)
    61  	}
    62  }
    63  
    64  func Test64BitReturnStdCall(t *testing.T) {
    65  
    66  	const (
    67  		VER_BUILDNUMBER      = 0x0000004
    68  		VER_MAJORVERSION     = 0x0000002
    69  		VER_MINORVERSION     = 0x0000001
    70  		VER_PLATFORMID       = 0x0000008
    71  		VER_PRODUCT_TYPE     = 0x0000080
    72  		VER_SERVICEPACKMAJOR = 0x0000020
    73  		VER_SERVICEPACKMINOR = 0x0000010
    74  		VER_SUITENAME        = 0x0000040
    75  
    76  		VER_EQUAL         = 1
    77  		VER_GREATER       = 2
    78  		VER_GREATER_EQUAL = 3
    79  		VER_LESS          = 4
    80  		VER_LESS_EQUAL    = 5
    81  
    82  		ERROR_OLD_WIN_VERSION syscall.Errno = 1150
    83  	)
    84  
    85  	type OSVersionInfoEx struct {
    86  		OSVersionInfoSize uint32
    87  		MajorVersion      uint32
    88  		MinorVersion      uint32
    89  		BuildNumber       uint32
    90  		PlatformId        uint32
    91  		CSDVersion        [128]uint16
    92  		ServicePackMajor  uint16
    93  		ServicePackMinor  uint16
    94  		SuiteMask         uint16
    95  		ProductType       byte
    96  		Reserve           byte
    97  	}
    98  
    99  	d := GetDLL(t, "kernel32.dll")
   100  
   101  	var m1, m2 uintptr
   102  	VerSetConditionMask := d.Proc("VerSetConditionMask")
   103  	m1, m2, _ = VerSetConditionMask.Call(m1, m2, VER_MAJORVERSION, VER_GREATER_EQUAL)
   104  	m1, m2, _ = VerSetConditionMask.Call(m1, m2, VER_MINORVERSION, VER_GREATER_EQUAL)
   105  	m1, m2, _ = VerSetConditionMask.Call(m1, m2, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL)
   106  	m1, m2, _ = VerSetConditionMask.Call(m1, m2, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL)
   107  
   108  	vi := OSVersionInfoEx{
   109  		MajorVersion:     5,
   110  		MinorVersion:     1,
   111  		ServicePackMajor: 2,
   112  		ServicePackMinor: 0,
   113  	}
   114  	vi.OSVersionInfoSize = uint32(unsafe.Sizeof(vi))
   115  	r, _, e2 := d.Proc("VerifyVersionInfoW").Call(
   116  		uintptr(unsafe.Pointer(&vi)),
   117  		VER_MAJORVERSION|VER_MINORVERSION|VER_SERVICEPACKMAJOR|VER_SERVICEPACKMINOR,
   118  		m1, m2)
   119  	if r == 0 && e2 != ERROR_OLD_WIN_VERSION {
   120  		t.Errorf("VerifyVersionInfo failed: %s", e2)
   121  	}
   122  }
   123  
   124  func TestCDecl(t *testing.T) {
   125  	var buf [50]byte
   126  	fmtp, _ := syscall.BytePtrFromString("%d %d %d")
   127  	a, _, _ := GetDLL(t, "user32.dll").Proc("wsprintfA").Call(
   128  		uintptr(unsafe.Pointer(&buf[0])),
   129  		uintptr(unsafe.Pointer(fmtp)),
   130  		1000, 2000, 3000)
   131  	if string(buf[:a]) != "1000 2000 3000" {
   132  		t.Error("cdecl USER32.wsprintfA returns", a, "buf=", buf[:a])
   133  	}
   134  }
   135  
   136  func TestEnumWindows(t *testing.T) {
   137  	d := GetDLL(t, "user32.dll")
   138  	isWindows := d.Proc("IsWindow")
   139  	counter := 0
   140  	cb := syscall.NewCallback(func(hwnd syscall.Handle, lparam uintptr) uintptr {
   141  		if lparam != 888 {
   142  			t.Error("lparam was not passed to callback")
   143  		}
   144  		b, _, _ := isWindows.Call(uintptr(hwnd))
   145  		if b == 0 {
   146  			t.Error("USER32.IsWindow returns FALSE")
   147  		}
   148  		counter++
   149  		return 1 // continue enumeration
   150  	})
   151  	a, _, _ := d.Proc("EnumWindows").Call(cb, 888)
   152  	if a == 0 {
   153  		t.Error("USER32.EnumWindows returns FALSE")
   154  	}
   155  	if counter == 0 {
   156  		t.Error("Callback has been never called or your have no windows")
   157  	}
   158  }
   159  
   160  func callback(hwnd syscall.Handle, lparam uintptr) uintptr {
   161  	(*(*func())(unsafe.Pointer(&lparam)))()
   162  	return 0 // stop enumeration
   163  }
   164  
   165  // nestedCall calls into Windows, back into Go, and finally to f.
   166  func nestedCall(t *testing.T, f func()) {
   167  	c := syscall.NewCallback(callback)
   168  	d := GetDLL(t, "user32.dll")
   169  	defer d.Release()
   170  	d.Proc("EnumWindows").Call(c, uintptr(*(*unsafe.Pointer)(unsafe.Pointer(&f))))
   171  }
   172  
   173  func TestCallback(t *testing.T) {
   174  	var x = false
   175  	nestedCall(t, func() { x = true })
   176  	if !x {
   177  		t.Fatal("nestedCall did not call func")
   178  	}
   179  }
   180  
   181  func TestCallbackGC(t *testing.T) {
   182  	nestedCall(t, runtime.GC)
   183  }
   184  
   185  func TestCallbackPanicLocked(t *testing.T) {
   186  	runtime.LockOSThread()
   187  	defer runtime.UnlockOSThread()
   188  
   189  	if !runtime.LockedOSThread() {
   190  		t.Fatal("runtime.LockOSThread didn't")
   191  	}
   192  	defer func() {
   193  		s := recover()
   194  		if s == nil {
   195  			t.Fatal("did not panic")
   196  		}
   197  		if s.(string) != "callback panic" {
   198  			t.Fatal("wrong panic:", s)
   199  		}
   200  		if !runtime.LockedOSThread() {
   201  			t.Fatal("lost lock on OS thread after panic")
   202  		}
   203  	}()
   204  	nestedCall(t, func() { panic("callback panic") })
   205  	panic("nestedCall returned")
   206  }
   207  
   208  func TestCallbackPanic(t *testing.T) {
   209  	// Make sure panic during callback unwinds properly.
   210  	if runtime.LockedOSThread() {
   211  		t.Fatal("locked OS thread on entry to TestCallbackPanic")
   212  	}
   213  	defer func() {
   214  		s := recover()
   215  		if s == nil {
   216  			t.Fatal("did not panic")
   217  		}
   218  		if s.(string) != "callback panic" {
   219  			t.Fatal("wrong panic:", s)
   220  		}
   221  		if runtime.LockedOSThread() {
   222  			t.Fatal("locked OS thread on exit from TestCallbackPanic")
   223  		}
   224  	}()
   225  	nestedCall(t, func() { panic("callback panic") })
   226  	panic("nestedCall returned")
   227  }
   228  
   229  func TestCallbackPanicLoop(t *testing.T) {
   230  	// Make sure we don't blow out m->g0 stack.
   231  	for i := 0; i < 100000; i++ {
   232  		TestCallbackPanic(t)
   233  	}
   234  }
   235  
   236  func TestBlockingCallback(t *testing.T) {
   237  	c := make(chan int)
   238  	go func() {
   239  		for i := 0; i < 10; i++ {
   240  			c <- <-c
   241  		}
   242  	}()
   243  	nestedCall(t, func() {
   244  		for i := 0; i < 10; i++ {
   245  			c <- i
   246  			if j := <-c; j != i {
   247  				t.Errorf("out of sync %d != %d", j, i)
   248  			}
   249  		}
   250  	})
   251  }
   252  
   253  func TestCallbackInAnotherThread(t *testing.T) {
   254  	d := GetDLL(t, "kernel32.dll")
   255  
   256  	f := func(p uintptr) uintptr {
   257  		return p
   258  	}
   259  	r, _, err := d.Proc("CreateThread").Call(0, 0, syscall.NewCallback(f), 123, 0, 0)
   260  	if r == 0 {
   261  		t.Fatalf("CreateThread failed: %v", err)
   262  	}
   263  	h := syscall.Handle(r)
   264  	defer syscall.CloseHandle(h)
   265  
   266  	switch s, err := syscall.WaitForSingleObject(h, 100); s {
   267  	case syscall.WAIT_OBJECT_0:
   268  		break
   269  	case syscall.WAIT_TIMEOUT:
   270  		t.Fatal("timeout waiting for thread to exit")
   271  	case syscall.WAIT_FAILED:
   272  		t.Fatalf("WaitForSingleObject failed: %v", err)
   273  	default:
   274  		t.Fatalf("WaitForSingleObject returns unexpected value %v", s)
   275  	}
   276  
   277  	var ec uint32
   278  	r, _, err = d.Proc("GetExitCodeThread").Call(uintptr(h), uintptr(unsafe.Pointer(&ec)))
   279  	if r == 0 {
   280  		t.Fatalf("GetExitCodeThread failed: %v", err)
   281  	}
   282  	if ec != 123 {
   283  		t.Fatalf("expected 123, but got %d", ec)
   284  	}
   285  }
   286  
   287  type cbDLLFunc int // int determines number of callback parameters
   288  
   289  func (f cbDLLFunc) stdcallName() string {
   290  	return fmt.Sprintf("stdcall%d", f)
   291  }
   292  
   293  func (f cbDLLFunc) cdeclName() string {
   294  	return fmt.Sprintf("cdecl%d", f)
   295  }
   296  
   297  func (f cbDLLFunc) buildOne(stdcall bool) string {
   298  	var funcname, attr string
   299  	if stdcall {
   300  		funcname = f.stdcallName()
   301  		attr = "__stdcall"
   302  	} else {
   303  		funcname = f.cdeclName()
   304  		attr = "__cdecl"
   305  	}
   306  	typename := "t" + funcname
   307  	p := make([]string, f)
   308  	for i := range p {
   309  		p[i] = "uintptr_t"
   310  	}
   311  	params := strings.Join(p, ",")
   312  	for i := range p {
   313  		p[i] = fmt.Sprintf("%d", i+1)
   314  	}
   315  	args := strings.Join(p, ",")
   316  	return fmt.Sprintf(`
   317  typedef void %s (*%s)(%s);
   318  void %s(%s f, uintptr_t n) {
   319  	uintptr_t i;
   320  	for(i=0;i<n;i++){
   321  		f(%s);
   322  	}
   323  }
   324  	`, attr, typename, params, funcname, typename, args)
   325  }
   326  
   327  func (f cbDLLFunc) build() string {
   328  	return "#include <stdint.h>\n\n" + f.buildOne(false) + f.buildOne(true)
   329  }
   330  
   331  var cbFuncs = [...]interface{}{
   332  	2: func(i1, i2 uintptr) uintptr {
   333  		if i1+i2 != 3 {
   334  			panic("bad input")
   335  		}
   336  		return 0
   337  	},
   338  	3: func(i1, i2, i3 uintptr) uintptr {
   339  		if i1+i2+i3 != 6 {
   340  			panic("bad input")
   341  		}
   342  		return 0
   343  	},
   344  	4: func(i1, i2, i3, i4 uintptr) uintptr {
   345  		if i1+i2+i3+i4 != 10 {
   346  			panic("bad input")
   347  		}
   348  		return 0
   349  	},
   350  	5: func(i1, i2, i3, i4, i5 uintptr) uintptr {
   351  		if i1+i2+i3+i4+i5 != 15 {
   352  			panic("bad input")
   353  		}
   354  		return 0
   355  	},
   356  	6: func(i1, i2, i3, i4, i5, i6 uintptr) uintptr {
   357  		if i1+i2+i3+i4+i5+i6 != 21 {
   358  			panic("bad input")
   359  		}
   360  		return 0
   361  	},
   362  	7: func(i1, i2, i3, i4, i5, i6, i7 uintptr) uintptr {
   363  		if i1+i2+i3+i4+i5+i6+i7 != 28 {
   364  			panic("bad input")
   365  		}
   366  		return 0
   367  	},
   368  	8: func(i1, i2, i3, i4, i5, i6, i7, i8 uintptr) uintptr {
   369  		if i1+i2+i3+i4+i5+i6+i7+i8 != 36 {
   370  			panic("bad input")
   371  		}
   372  		return 0
   373  	},
   374  	9: func(i1, i2, i3, i4, i5, i6, i7, i8, i9 uintptr) uintptr {
   375  		if i1+i2+i3+i4+i5+i6+i7+i8+i9 != 45 {
   376  			panic("bad input")
   377  		}
   378  		return 0
   379  	},
   380  }
   381  
   382  type cbDLL struct {
   383  	name      string
   384  	buildArgs func(out, src string) []string
   385  }
   386  
   387  func (d *cbDLL) buildSrc(t *testing.T, path string) {
   388  	f, err := os.Create(path)
   389  	if err != nil {
   390  		t.Fatalf("failed to create source file: %v", err)
   391  	}
   392  	defer f.Close()
   393  
   394  	for i := 2; i < 10; i++ {
   395  		fmt.Fprint(f, cbDLLFunc(i).build())
   396  	}
   397  }
   398  
   399  func (d *cbDLL) build(t *testing.T, dir string) string {
   400  	srcname := d.name + ".c"
   401  	d.buildSrc(t, filepath.Join(dir, srcname))
   402  	outname := d.name + ".dll"
   403  	args := d.buildArgs(outname, srcname)
   404  	cmd := exec.Command(args[0], args[1:]...)
   405  	cmd.Dir = dir
   406  	out, err := cmd.CombinedOutput()
   407  	if err != nil {
   408  		t.Fatalf("failed to build dll: %v - %v", err, string(out))
   409  	}
   410  	return filepath.Join(dir, outname)
   411  }
   412  
   413  var cbDLLs = []cbDLL{
   414  	{
   415  		"test",
   416  		func(out, src string) []string {
   417  			return []string{"gcc", "-shared", "-s", "-Werror", "-o", out, src}
   418  		},
   419  	},
   420  	{
   421  		"testO2",
   422  		func(out, src string) []string {
   423  			return []string{"gcc", "-shared", "-s", "-Werror", "-o", out, "-O2", src}
   424  		},
   425  	},
   426  }
   427  
   428  type cbTest struct {
   429  	n     int     // number of callback parameters
   430  	param uintptr // dll function parameter
   431  }
   432  
   433  func (test *cbTest) run(t *testing.T, dllpath string) {
   434  	dll := syscall.MustLoadDLL(dllpath)
   435  	defer dll.Release()
   436  	cb := cbFuncs[test.n]
   437  	stdcall := syscall.NewCallback(cb)
   438  	f := cbDLLFunc(test.n)
   439  	test.runOne(t, dll, f.stdcallName(), stdcall)
   440  	cdecl := syscall.NewCallbackCDecl(cb)
   441  	test.runOne(t, dll, f.cdeclName(), cdecl)
   442  }
   443  
   444  func (test *cbTest) runOne(t *testing.T, dll *syscall.DLL, proc string, cb uintptr) {
   445  	defer func() {
   446  		if r := recover(); r != nil {
   447  			t.Errorf("dll call %v(..., %d) failed: %v", proc, test.param, r)
   448  		}
   449  	}()
   450  	dll.MustFindProc(proc).Call(cb, test.param)
   451  }
   452  
   453  var cbTests = []cbTest{
   454  	{2, 1},
   455  	{2, 10000},
   456  	{3, 3},
   457  	{4, 5},
   458  	{4, 6},
   459  	{5, 2},
   460  	{6, 7},
   461  	{6, 8},
   462  	{7, 6},
   463  	{8, 1},
   464  	{9, 8},
   465  	{9, 10000},
   466  	{3, 4},
   467  	{5, 3},
   468  	{7, 7},
   469  	{8, 2},
   470  	{9, 9},
   471  }
   472  
   473  func TestStdcallAndCDeclCallbacks(t *testing.T) {
   474  	if _, err := exec.LookPath("gcc"); err != nil {
   475  		t.Skip("skipping test: gcc is missing")
   476  	}
   477  	tmp, err := ioutil.TempDir("", "TestCDeclCallback")
   478  	if err != nil {
   479  		t.Fatal("TempDir failed: ", err)
   480  	}
   481  	defer os.RemoveAll(tmp)
   482  
   483  	for _, dll := range cbDLLs {
   484  		dllPath := dll.build(t, tmp)
   485  		for _, test := range cbTests {
   486  			test.run(t, dllPath)
   487  		}
   488  	}
   489  }
   490  
   491  func TestRegisterClass(t *testing.T) {
   492  	kernel32 := GetDLL(t, "kernel32.dll")
   493  	user32 := GetDLL(t, "user32.dll")
   494  	mh, _, _ := kernel32.Proc("GetModuleHandleW").Call(0)
   495  	cb := syscall.NewCallback(func(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (rc uintptr) {
   496  		t.Fatal("callback should never get called")
   497  		return 0
   498  	})
   499  	type Wndclassex struct {
   500  		Size       uint32
   501  		Style      uint32
   502  		WndProc    uintptr
   503  		ClsExtra   int32
   504  		WndExtra   int32
   505  		Instance   syscall.Handle
   506  		Icon       syscall.Handle
   507  		Cursor     syscall.Handle
   508  		Background syscall.Handle
   509  		MenuName   *uint16
   510  		ClassName  *uint16
   511  		IconSm     syscall.Handle
   512  	}
   513  	name := syscall.StringToUTF16Ptr("test_window")
   514  	wc := Wndclassex{
   515  		WndProc:   cb,
   516  		Instance:  syscall.Handle(mh),
   517  		ClassName: name,
   518  	}
   519  	wc.Size = uint32(unsafe.Sizeof(wc))
   520  	a, _, err := user32.Proc("RegisterClassExW").Call(uintptr(unsafe.Pointer(&wc)))
   521  	if a == 0 {
   522  		t.Fatalf("RegisterClassEx failed: %v", err)
   523  	}
   524  	r, _, err := user32.Proc("UnregisterClassW").Call(uintptr(unsafe.Pointer(name)), 0)
   525  	if r == 0 {
   526  		t.Fatalf("UnregisterClass failed: %v", err)
   527  	}
   528  }
   529  
   530  func TestOutputDebugString(t *testing.T) {
   531  	d := GetDLL(t, "kernel32.dll")
   532  	p := syscall.StringToUTF16Ptr("testing OutputDebugString")
   533  	d.Proc("OutputDebugStringW").Call(uintptr(unsafe.Pointer(p)))
   534  }
   535  
   536  func TestRaiseException(t *testing.T) {
   537  	o := runTestProg(t, "testprog", "RaiseException")
   538  	if strings.Contains(o, "RaiseException should not return") {
   539  		t.Fatalf("RaiseException did not crash program: %v", o)
   540  	}
   541  	if !strings.Contains(o, "Exception 0xbad") {
   542  		t.Fatalf("No stack trace: %v", o)
   543  	}
   544  }
   545  
   546  func TestZeroDivisionException(t *testing.T) {
   547  	o := runTestProg(t, "testprog", "ZeroDivisionException")
   548  	if !strings.Contains(o, "panic: runtime error: integer divide by zero") {
   549  		t.Fatalf("No stack trace: %v", o)
   550  	}
   551  }
   552  
   553  func TestWERDialogue(t *testing.T) {
   554  	if os.Getenv("TESTING_WER_DIALOGUE") == "1" {
   555  		defer os.Exit(0)
   556  
   557  		*runtime.TestingWER = true
   558  		const EXCEPTION_NONCONTINUABLE = 1
   559  		mod := syscall.MustLoadDLL("kernel32.dll")
   560  		proc := mod.MustFindProc("RaiseException")
   561  		proc.Call(0xbad, EXCEPTION_NONCONTINUABLE, 0, 0)
   562  		println("RaiseException should not return")
   563  		return
   564  	}
   565  	cmd := exec.Command(os.Args[0], "-test.run=TestWERDialogue")
   566  	cmd.Env = []string{"TESTING_WER_DIALOGUE=1"}
   567  	// Child process should not open WER dialogue, but return immediately instead.
   568  	cmd.CombinedOutput()
   569  }
   570  
   571  func TestWindowsStackMemory(t *testing.T) {
   572  	o := runTestProg(t, "testprog", "StackMemory")
   573  	stackUsage, err := strconv.Atoi(o)
   574  	if err != nil {
   575  		t.Fatalf("Failed to read stack usage: %v", err)
   576  	}
   577  	if expected, got := 100<<10, stackUsage; got > expected {
   578  		t.Fatalf("expected < %d bytes of memory per thread, got %d", expected, got)
   579  	}
   580  }
   581  
   582  var used byte
   583  
   584  func use(buf []byte) {
   585  	for _, c := range buf {
   586  		used += c
   587  	}
   588  }
   589  
   590  func forceStackCopy() (r int) {
   591  	var f func(int) int
   592  	f = func(i int) int {
   593  		var buf [256]byte
   594  		use(buf[:])
   595  		if i == 0 {
   596  			return 0
   597  		}
   598  		return i + f(i-1)
   599  	}
   600  	r = f(128)
   601  	return
   602  }
   603  
   604  func TestReturnAfterStackGrowInCallback(t *testing.T) {
   605  	if _, err := exec.LookPath("gcc"); err != nil {
   606  		t.Skip("skipping test: gcc is missing")
   607  	}
   608  
   609  	const src = `
   610  #include <stdint.h>
   611  #include <windows.h>
   612  
   613  typedef uintptr_t __stdcall (*callback)(uintptr_t);
   614  
   615  uintptr_t cfunc(callback f, uintptr_t n) {
   616     uintptr_t r;
   617     r = f(n);
   618     SetLastError(333);
   619     return r;
   620  }
   621  `
   622  	tmpdir, err := ioutil.TempDir("", "TestReturnAfterStackGrowInCallback")
   623  	if err != nil {
   624  		t.Fatal("TempDir failed: ", err)
   625  	}
   626  	defer os.RemoveAll(tmpdir)
   627  
   628  	srcname := "mydll.c"
   629  	err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
   630  	if err != nil {
   631  		t.Fatal(err)
   632  	}
   633  	outname := "mydll.dll"
   634  	cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", outname, srcname)
   635  	cmd.Dir = tmpdir
   636  	out, err := cmd.CombinedOutput()
   637  	if err != nil {
   638  		t.Fatalf("failed to build dll: %v - %v", err, string(out))
   639  	}
   640  	dllpath := filepath.Join(tmpdir, outname)
   641  
   642  	dll := syscall.MustLoadDLL(dllpath)
   643  	defer dll.Release()
   644  
   645  	proc := dll.MustFindProc("cfunc")
   646  
   647  	cb := syscall.NewCallback(func(n uintptr) uintptr {
   648  		forceStackCopy()
   649  		return n
   650  	})
   651  
   652  	// Use a new goroutine so that we get a small stack.
   653  	type result struct {
   654  		r   uintptr
   655  		err syscall.Errno
   656  	}
   657  	c := make(chan result)
   658  	go func() {
   659  		r, _, err := proc.Call(cb, 100)
   660  		c <- result{r, err.(syscall.Errno)}
   661  	}()
   662  	want := result{r: 100, err: 333}
   663  	if got := <-c; got != want {
   664  		t.Errorf("got %d want %d", got, want)
   665  	}
   666  }
   667  
   668  func TestFloatArgs(t *testing.T) {
   669  	if _, err := exec.LookPath("gcc"); err != nil {
   670  		t.Skip("skipping test: gcc is missing")
   671  	}
   672  	if runtime.GOARCH != "amd64" {
   673  		t.Skipf("skipping test: GOARCH=%s", runtime.GOARCH)
   674  	}
   675  
   676  	const src = `
   677  #include <stdint.h>
   678  #include <windows.h>
   679  
   680  uintptr_t cfunc(uintptr_t a, double b, float c, double d) {
   681  	if (a == 1 && b == 2.2 && c == 3.3f && d == 4.4e44) {
   682  		return 1;
   683  	}
   684  	return 0;
   685  }
   686  `
   687  	tmpdir, err := ioutil.TempDir("", "TestFloatArgs")
   688  	if err != nil {
   689  		t.Fatal("TempDir failed: ", err)
   690  	}
   691  	defer os.RemoveAll(tmpdir)
   692  
   693  	srcname := "mydll.c"
   694  	err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
   695  	if err != nil {
   696  		t.Fatal(err)
   697  	}
   698  	outname := "mydll.dll"
   699  	cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", outname, srcname)
   700  	cmd.Dir = tmpdir
   701  	out, err := cmd.CombinedOutput()
   702  	if err != nil {
   703  		t.Fatalf("failed to build dll: %v - %v", err, string(out))
   704  	}
   705  	dllpath := filepath.Join(tmpdir, outname)
   706  
   707  	dll := syscall.MustLoadDLL(dllpath)
   708  	defer dll.Release()
   709  
   710  	proc := dll.MustFindProc("cfunc")
   711  
   712  	r, _, err := proc.Call(
   713  		1,
   714  		uintptr(math.Float64bits(2.2)),
   715  		uintptr(math.Float32bits(3.3)),
   716  		uintptr(math.Float64bits(4.4e44)),
   717  	)
   718  	if r != 1 {
   719  		t.Errorf("got %d want 1 (err=%v)", r, err)
   720  	}
   721  }
   722  
   723  func TestTimeBeginPeriod(t *testing.T) {
   724  	const TIMERR_NOERROR = 0
   725  	if *runtime.TimeBeginPeriodRetValue != TIMERR_NOERROR {
   726  		t.Fatalf("timeBeginPeriod failed: it returned %d", *runtime.TimeBeginPeriodRetValue)
   727  	}
   728  }
   729  
   730  // removeOneCPU removes one (any) cpu from affinity mask.
   731  // It returns new affinity mask.
   732  func removeOneCPU(mask uintptr) (uintptr, error) {
   733  	if mask == 0 {
   734  		return 0, fmt.Errorf("cpu affinity mask is empty")
   735  	}
   736  	maskbits := int(unsafe.Sizeof(mask) * 8)
   737  	for i := 0; i < maskbits; i++ {
   738  		newmask := mask & ^(1 << uint(i))
   739  		if newmask != mask {
   740  			return newmask, nil
   741  		}
   742  
   743  	}
   744  	panic("not reached")
   745  }
   746  
   747  func resumeChildThread(kernel32 *syscall.DLL, childpid int) error {
   748  	_OpenThread := kernel32.MustFindProc("OpenThread")
   749  	_ResumeThread := kernel32.MustFindProc("ResumeThread")
   750  	_Thread32First := kernel32.MustFindProc("Thread32First")
   751  	_Thread32Next := kernel32.MustFindProc("Thread32Next")
   752  
   753  	snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPTHREAD, 0)
   754  	if err != nil {
   755  		return err
   756  	}
   757  	defer syscall.CloseHandle(snapshot)
   758  
   759  	const _THREAD_SUSPEND_RESUME = 0x0002
   760  
   761  	type ThreadEntry32 struct {
   762  		Size           uint32
   763  		tUsage         uint32
   764  		ThreadID       uint32
   765  		OwnerProcessID uint32
   766  		BasePri        int32
   767  		DeltaPri       int32
   768  		Flags          uint32
   769  	}
   770  
   771  	var te ThreadEntry32
   772  	te.Size = uint32(unsafe.Sizeof(te))
   773  	ret, _, err := _Thread32First.Call(uintptr(snapshot), uintptr(unsafe.Pointer(&te)))
   774  	if ret == 0 {
   775  		return err
   776  	}
   777  	for te.OwnerProcessID != uint32(childpid) {
   778  		ret, _, err = _Thread32Next.Call(uintptr(snapshot), uintptr(unsafe.Pointer(&te)))
   779  		if ret == 0 {
   780  			return err
   781  		}
   782  	}
   783  	h, _, err := _OpenThread.Call(_THREAD_SUSPEND_RESUME, 1, uintptr(te.ThreadID))
   784  	if h == 0 {
   785  		return err
   786  	}
   787  	defer syscall.Close(syscall.Handle(h))
   788  
   789  	ret, _, err = _ResumeThread.Call(h)
   790  	if ret == 0xffffffff {
   791  		return err
   792  	}
   793  	return nil
   794  }
   795  
   796  func TestNumCPU(t *testing.T) {
   797  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
   798  		// in child process
   799  		fmt.Fprintf(os.Stderr, "%d", runtime.NumCPU())
   800  		os.Exit(0)
   801  	}
   802  
   803  	switch n := runtime.NumberOfProcessors(); {
   804  	case n < 1:
   805  		t.Fatalf("system cannot have %d cpu(s)", n)
   806  	case n == 1:
   807  		if runtime.NumCPU() != 1 {
   808  			t.Fatalf("runtime.NumCPU() returns %d on single cpu system", runtime.NumCPU())
   809  		}
   810  		return
   811  	}
   812  
   813  	const (
   814  		_CREATE_SUSPENDED   = 0x00000004
   815  		_PROCESS_ALL_ACCESS = syscall.STANDARD_RIGHTS_REQUIRED | syscall.SYNCHRONIZE | 0xfff
   816  	)
   817  
   818  	kernel32 := syscall.MustLoadDLL("kernel32.dll")
   819  	_GetProcessAffinityMask := kernel32.MustFindProc("GetProcessAffinityMask")
   820  	_SetProcessAffinityMask := kernel32.MustFindProc("SetProcessAffinityMask")
   821  
   822  	cmd := exec.Command(os.Args[0], "-test.run=TestNumCPU")
   823  	cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
   824  	var buf bytes.Buffer
   825  	cmd.Stdout = &buf
   826  	cmd.Stderr = &buf
   827  	cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: _CREATE_SUSPENDED}
   828  	err := cmd.Start()
   829  	if err != nil {
   830  		t.Fatal(err)
   831  	}
   832  	defer func() {
   833  		err = cmd.Wait()
   834  		childOutput := string(buf.Bytes())
   835  		if err != nil {
   836  			t.Fatalf("child failed: %v: %v", err, childOutput)
   837  		}
   838  		// removeOneCPU should have decreased child cpu count by 1
   839  		want := fmt.Sprintf("%d", runtime.NumCPU()-1)
   840  		if childOutput != want {
   841  			t.Fatalf("child output: want %q, got %q", want, childOutput)
   842  		}
   843  	}()
   844  
   845  	defer func() {
   846  		err = resumeChildThread(kernel32, cmd.Process.Pid)
   847  		if err != nil {
   848  			t.Fatal(err)
   849  		}
   850  	}()
   851  
   852  	ph, err := syscall.OpenProcess(_PROCESS_ALL_ACCESS, false, uint32(cmd.Process.Pid))
   853  	if err != nil {
   854  		t.Fatal(err)
   855  	}
   856  	defer syscall.CloseHandle(ph)
   857  
   858  	var mask, sysmask uintptr
   859  	ret, _, err := _GetProcessAffinityMask.Call(uintptr(ph), uintptr(unsafe.Pointer(&mask)), uintptr(unsafe.Pointer(&sysmask)))
   860  	if ret == 0 {
   861  		t.Fatal(err)
   862  	}
   863  
   864  	newmask, err := removeOneCPU(mask)
   865  	if err != nil {
   866  		t.Fatal(err)
   867  	}
   868  
   869  	ret, _, err = _SetProcessAffinityMask.Call(uintptr(ph), newmask)
   870  	if ret == 0 {
   871  		t.Fatal(err)
   872  	}
   873  	ret, _, err = _GetProcessAffinityMask.Call(uintptr(ph), uintptr(unsafe.Pointer(&mask)), uintptr(unsafe.Pointer(&sysmask)))
   874  	if ret == 0 {
   875  		t.Fatal(err)
   876  	}
   877  	if newmask != mask {
   878  		t.Fatalf("SetProcessAffinityMask didn't set newmask of 0x%x. Current mask is 0x%x.", newmask, mask)
   879  	}
   880  }
   881  
   882  // See Issue 14959
   883  func TestDLLPreloadMitigation(t *testing.T) {
   884  	if _, err := exec.LookPath("gcc"); err != nil {
   885  		t.Skip("skipping test: gcc is missing")
   886  	}
   887  
   888  	tmpdir, err := ioutil.TempDir("", "TestDLLPreloadMitigation")
   889  	if err != nil {
   890  		t.Fatal("TempDir failed: ", err)
   891  	}
   892  	defer func() {
   893  		err := os.RemoveAll(tmpdir)
   894  		if err != nil {
   895  			t.Error(err)
   896  		}
   897  	}()
   898  
   899  	dir0, err := os.Getwd()
   900  	if err != nil {
   901  		t.Fatal(err)
   902  	}
   903  	defer os.Chdir(dir0)
   904  
   905  	const src = `
   906  #include <stdint.h>
   907  #include <windows.h>
   908  
   909  uintptr_t cfunc() {
   910     SetLastError(123);
   911  }
   912  `
   913  	srcname := "nojack.c"
   914  	err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
   915  	if err != nil {
   916  		t.Fatal(err)
   917  	}
   918  	name := "nojack.dll"
   919  	cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", name, srcname)
   920  	cmd.Dir = tmpdir
   921  	out, err := cmd.CombinedOutput()
   922  	if err != nil {
   923  		t.Fatalf("failed to build dll: %v - %v", err, string(out))
   924  	}
   925  	dllpath := filepath.Join(tmpdir, name)
   926  
   927  	dll := syscall.MustLoadDLL(dllpath)
   928  	dll.MustFindProc("cfunc")
   929  	dll.Release()
   930  
   931  	// Get into the directory with the DLL we'll load by base name
   932  	// ("nojack.dll") Think of this as the user double-clicking an
   933  	// installer from their Downloads directory where a browser
   934  	// silently downloaded some malicious DLLs.
   935  	os.Chdir(tmpdir)
   936  
   937  	// First before we can load a DLL from the current directory,
   938  	// loading it only as "nojack.dll", without an absolute path.
   939  	delete(sysdll.IsSystemDLL, name) // in case test was run repeatedly
   940  	dll, err = syscall.LoadDLL(name)
   941  	if err != nil {
   942  		t.Fatalf("failed to load %s by base name before sysdll registration: %v", name, err)
   943  	}
   944  	dll.Release()
   945  
   946  	// And now verify that if we register it as a system32-only
   947  	// DLL, the implicit loading from the current directory no
   948  	// longer works.
   949  	sysdll.IsSystemDLL[name] = true
   950  	dll, err = syscall.LoadDLL(name)
   951  	if err == nil {
   952  		dll.Release()
   953  		if wantLoadLibraryEx() {
   954  			t.Fatalf("Bad: insecure load of DLL by base name %q before sysdll registration: %v", name, err)
   955  		}
   956  		t.Skip("insecure load of DLL, but expected")
   957  	}
   958  }
   959  
   960  // Test that C code called via a DLL can use large Windows thread
   961  // stacks and call back in to Go without crashing. See issue #20975.
   962  //
   963  // See also TestBigStackCallbackCgo.
   964  func TestBigStackCallbackSyscall(t *testing.T) {
   965  	if _, err := exec.LookPath("gcc"); err != nil {
   966  		t.Skip("skipping test: gcc is missing")
   967  	}
   968  
   969  	srcname, err := filepath.Abs("testdata/testprogcgo/bigstack_windows.c")
   970  	if err != nil {
   971  		t.Fatal("Abs failed: ", err)
   972  	}
   973  
   974  	tmpdir, err := ioutil.TempDir("", "TestBigStackCallback")
   975  	if err != nil {
   976  		t.Fatal("TempDir failed: ", err)
   977  	}
   978  	defer os.RemoveAll(tmpdir)
   979  
   980  	outname := "mydll.dll"
   981  	cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", outname, srcname)
   982  	cmd.Dir = tmpdir
   983  	out, err := cmd.CombinedOutput()
   984  	if err != nil {
   985  		t.Fatalf("failed to build dll: %v - %v", err, string(out))
   986  	}
   987  	dllpath := filepath.Join(tmpdir, outname)
   988  
   989  	dll := syscall.MustLoadDLL(dllpath)
   990  	defer dll.Release()
   991  
   992  	var ok bool
   993  	proc := dll.MustFindProc("bigStack")
   994  	cb := syscall.NewCallback(func() uintptr {
   995  		// Do something interesting to force stack checks.
   996  		forceStackCopy()
   997  		ok = true
   998  		return 0
   999  	})
  1000  	proc.Call(cb)
  1001  	if !ok {
  1002  		t.Fatalf("callback not called")
  1003  	}
  1004  }
  1005  
  1006  // wantLoadLibraryEx reports whether we expect LoadLibraryEx to work for tests.
  1007  func wantLoadLibraryEx() bool {
  1008  	return testenv.Builder() == "windows-amd64-gce" || testenv.Builder() == "windows-386-gce"
  1009  }
  1010  
  1011  func TestLoadLibraryEx(t *testing.T) {
  1012  	use, have, flags := runtime.LoadLibraryExStatus()
  1013  	if use {
  1014  		return // success.
  1015  	}
  1016  	if wantLoadLibraryEx() {
  1017  		t.Fatalf("Expected LoadLibraryEx+flags to be available. (LoadLibraryEx=%v; flags=%v)",
  1018  			have, flags)
  1019  	}
  1020  	t.Skipf("LoadLibraryEx not usable, but not expected. (LoadLibraryEx=%v; flags=%v)",
  1021  		have, flags)
  1022  }
  1023  
  1024  var (
  1025  	modwinmm    = syscall.NewLazyDLL("winmm.dll")
  1026  	modkernel32 = syscall.NewLazyDLL("kernel32.dll")
  1027  
  1028  	procCreateEvent = modkernel32.NewProc("CreateEventW")
  1029  	procSetEvent    = modkernel32.NewProc("SetEvent")
  1030  )
  1031  
  1032  func createEvent() (syscall.Handle, error) {
  1033  	r0, _, e0 := syscall.Syscall6(procCreateEvent.Addr(), 4, 0, 0, 0, 0, 0, 0)
  1034  	if r0 == 0 {
  1035  		return 0, syscall.Errno(e0)
  1036  	}
  1037  	return syscall.Handle(r0), nil
  1038  }
  1039  
  1040  func setEvent(h syscall.Handle) error {
  1041  	r0, _, e0 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(h), 0, 0)
  1042  	if r0 == 0 {
  1043  		return syscall.Errno(e0)
  1044  	}
  1045  	return nil
  1046  }
  1047  
  1048  func BenchmarkChanToSyscallPing(b *testing.B) {
  1049  	n := b.N
  1050  	ch := make(chan int)
  1051  	event, err := createEvent()
  1052  	if err != nil {
  1053  		b.Fatal(err)
  1054  	}
  1055  	go func() {
  1056  		for i := 0; i < n; i++ {
  1057  			syscall.WaitForSingleObject(event, syscall.INFINITE)
  1058  			ch <- 1
  1059  		}
  1060  	}()
  1061  	for i := 0; i < n; i++ {
  1062  		err := setEvent(event)
  1063  		if err != nil {
  1064  			b.Fatal(err)
  1065  		}
  1066  		<-ch
  1067  	}
  1068  }
  1069  
  1070  func BenchmarkSyscallToSyscallPing(b *testing.B) {
  1071  	n := b.N
  1072  	event1, err := createEvent()
  1073  	if err != nil {
  1074  		b.Fatal(err)
  1075  	}
  1076  	event2, err := createEvent()
  1077  	if err != nil {
  1078  		b.Fatal(err)
  1079  	}
  1080  	go func() {
  1081  		for i := 0; i < n; i++ {
  1082  			syscall.WaitForSingleObject(event1, syscall.INFINITE)
  1083  			err := setEvent(event2)
  1084  			if err != nil {
  1085  				b.Fatal(err)
  1086  			}
  1087  		}
  1088  	}()
  1089  	for i := 0; i < n; i++ {
  1090  		err := setEvent(event1)
  1091  		if err != nil {
  1092  			b.Fatal(err)
  1093  		}
  1094  		syscall.WaitForSingleObject(event2, syscall.INFINITE)
  1095  	}
  1096  }
  1097  
  1098  func BenchmarkChanToChanPing(b *testing.B) {
  1099  	n := b.N
  1100  	ch1 := make(chan int)
  1101  	ch2 := make(chan int)
  1102  	go func() {
  1103  		for i := 0; i < n; i++ {
  1104  			<-ch1
  1105  			ch2 <- 1
  1106  		}
  1107  	}()
  1108  	for i := 0; i < n; i++ {
  1109  		ch1 <- 1
  1110  		<-ch2
  1111  	}
  1112  }
  1113  
  1114  func BenchmarkOsYield(b *testing.B) {
  1115  	for i := 0; i < b.N; i++ {
  1116  		runtime.OsYield()
  1117  	}
  1118  }
  1119  
  1120  func BenchmarkRunningGoProgram(b *testing.B) {
  1121  	tmpdir, err := ioutil.TempDir("", "BenchmarkRunningGoProgram")
  1122  	if err != nil {
  1123  		b.Fatal(err)
  1124  	}
  1125  	defer os.RemoveAll(tmpdir)
  1126  
  1127  	src := filepath.Join(tmpdir, "main.go")
  1128  	err = ioutil.WriteFile(src, []byte(benchmarkRunningGoProgram), 0666)
  1129  	if err != nil {
  1130  		b.Fatal(err)
  1131  	}
  1132  
  1133  	exe := filepath.Join(tmpdir, "main.exe")
  1134  	cmd := exec.Command(testenv.GoToolPath(b), "build", "-o", exe, src)
  1135  	cmd.Dir = tmpdir
  1136  	out, err := cmd.CombinedOutput()
  1137  	if err != nil {
  1138  		b.Fatalf("building main.exe failed: %v\n%s", err, out)
  1139  	}
  1140  
  1141  	b.ResetTimer()
  1142  	for i := 0; i < b.N; i++ {
  1143  		cmd := exec.Command(exe)
  1144  		out, err := cmd.CombinedOutput()
  1145  		if err != nil {
  1146  			b.Fatalf("running main.exe failed: %v\n%s", err, out)
  1147  		}
  1148  	}
  1149  }
  1150  
  1151  const benchmarkRunningGoProgram = `
  1152  package main
  1153  
  1154  import _ "os" // average Go program will use "os" package, do the same here
  1155  
  1156  func main() {
  1157  }
  1158  `
  1159  

View as plain text