...
Run Format

Source file src/runtime/os_windows.go

Documentation: runtime

     1  // Copyright 2009 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
     6  
     7  import (
     8  	"runtime/internal/atomic"
     9  	"unsafe"
    10  )
    11  
    12  // TODO(brainman): should not need those
    13  const (
    14  	_NSIG = 65
    15  )
    16  
    17  //go:cgo_import_dynamic runtime._AddVectoredExceptionHandler AddVectoredExceptionHandler%2 "kernel32.dll"
    18  //go:cgo_import_dynamic runtime._CloseHandle CloseHandle%1 "kernel32.dll"
    19  //go:cgo_import_dynamic runtime._CreateEventA CreateEventA%4 "kernel32.dll"
    20  //go:cgo_import_dynamic runtime._CreateIoCompletionPort CreateIoCompletionPort%4 "kernel32.dll"
    21  //go:cgo_import_dynamic runtime._CreateThread CreateThread%6 "kernel32.dll"
    22  //go:cgo_import_dynamic runtime._CreateWaitableTimerA CreateWaitableTimerA%3 "kernel32.dll"
    23  //go:cgo_import_dynamic runtime._DuplicateHandle DuplicateHandle%7 "kernel32.dll"
    24  //go:cgo_import_dynamic runtime._ExitProcess ExitProcess%1 "kernel32.dll"
    25  //go:cgo_import_dynamic runtime._FreeEnvironmentStringsW FreeEnvironmentStringsW%1 "kernel32.dll"
    26  //go:cgo_import_dynamic runtime._GetConsoleMode GetConsoleMode%2 "kernel32.dll"
    27  //go:cgo_import_dynamic runtime._GetEnvironmentStringsW GetEnvironmentStringsW%0 "kernel32.dll"
    28  //go:cgo_import_dynamic runtime._GetProcAddress GetProcAddress%2 "kernel32.dll"
    29  //go:cgo_import_dynamic runtime._GetProcessAffinityMask GetProcessAffinityMask%3 "kernel32.dll"
    30  //go:cgo_import_dynamic runtime._GetQueuedCompletionStatus GetQueuedCompletionStatus%5 "kernel32.dll"
    31  //go:cgo_import_dynamic runtime._GetStdHandle GetStdHandle%1 "kernel32.dll"
    32  //go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
    33  //go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
    34  //go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
    35  //go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
    36  //go:cgo_import_dynamic runtime._ResumeThread ResumeThread%1 "kernel32.dll"
    37  //go:cgo_import_dynamic runtime._SetConsoleCtrlHandler SetConsoleCtrlHandler%2 "kernel32.dll"
    38  //go:cgo_import_dynamic runtime._SetErrorMode SetErrorMode%1 "kernel32.dll"
    39  //go:cgo_import_dynamic runtime._SetEvent SetEvent%1 "kernel32.dll"
    40  //go:cgo_import_dynamic runtime._SetProcessPriorityBoost SetProcessPriorityBoost%2 "kernel32.dll"
    41  //go:cgo_import_dynamic runtime._SetThreadPriority SetThreadPriority%2 "kernel32.dll"
    42  //go:cgo_import_dynamic runtime._SetUnhandledExceptionFilter SetUnhandledExceptionFilter%1 "kernel32.dll"
    43  //go:cgo_import_dynamic runtime._SetWaitableTimer SetWaitableTimer%6 "kernel32.dll"
    44  //go:cgo_import_dynamic runtime._SuspendThread SuspendThread%1 "kernel32.dll"
    45  //go:cgo_import_dynamic runtime._SwitchToThread SwitchToThread%0 "kernel32.dll"
    46  //go:cgo_import_dynamic runtime._VirtualAlloc VirtualAlloc%4 "kernel32.dll"
    47  //go:cgo_import_dynamic runtime._VirtualFree VirtualFree%3 "kernel32.dll"
    48  //go:cgo_import_dynamic runtime._VirtualQuery VirtualQuery%3 "kernel32.dll"
    49  //go:cgo_import_dynamic runtime._WSAGetOverlappedResult WSAGetOverlappedResult%5 "ws2_32.dll"
    50  //go:cgo_import_dynamic runtime._WaitForSingleObject WaitForSingleObject%2 "kernel32.dll"
    51  //go:cgo_import_dynamic runtime._WriteConsoleW WriteConsoleW%5 "kernel32.dll"
    52  //go:cgo_import_dynamic runtime._WriteFile WriteFile%5 "kernel32.dll"
    53  //go:cgo_import_dynamic runtime._timeBeginPeriod timeBeginPeriod%1 "winmm.dll"
    54  //go:cgo_import_dynamic runtime._timeEndPeriod timeEndPeriod%1 "winmm.dll"
    55  
    56  type stdFunction unsafe.Pointer
    57  
    58  var (
    59  	// Following syscalls are available on every Windows PC.
    60  	// All these variables are set by the Windows executable
    61  	// loader before the Go program starts.
    62  	_AddVectoredExceptionHandler,
    63  	_CloseHandle,
    64  	_CreateEventA,
    65  	_CreateIoCompletionPort,
    66  	_CreateThread,
    67  	_CreateWaitableTimerA,
    68  	_DuplicateHandle,
    69  	_ExitProcess,
    70  	_FreeEnvironmentStringsW,
    71  	_GetConsoleMode,
    72  	_GetEnvironmentStringsW,
    73  	_GetProcAddress,
    74  	_GetProcessAffinityMask,
    75  	_GetQueuedCompletionStatus,
    76  	_GetStdHandle,
    77  	_GetSystemInfo,
    78  	_GetSystemTimeAsFileTime,
    79  	_GetThreadContext,
    80  	_LoadLibraryW,
    81  	_LoadLibraryA,
    82  	_QueryPerformanceCounter,
    83  	_QueryPerformanceFrequency,
    84  	_ResumeThread,
    85  	_SetConsoleCtrlHandler,
    86  	_SetErrorMode,
    87  	_SetEvent,
    88  	_SetProcessPriorityBoost,
    89  	_SetThreadPriority,
    90  	_SetUnhandledExceptionFilter,
    91  	_SetWaitableTimer,
    92  	_SuspendThread,
    93  	_SwitchToThread,
    94  	_VirtualAlloc,
    95  	_VirtualFree,
    96  	_VirtualQuery,
    97  	_WSAGetOverlappedResult,
    98  	_WaitForSingleObject,
    99  	_WriteConsoleW,
   100  	_WriteFile,
   101  	_timeBeginPeriod,
   102  	_timeEndPeriod,
   103  	_ stdFunction
   104  
   105  	// Following syscalls are only available on some Windows PCs.
   106  	// We will load syscalls, if available, before using them.
   107  	_AddDllDirectory,
   108  	_AddVectoredContinueHandler,
   109  	_GetQueuedCompletionStatusEx,
   110  	_LoadLibraryExW,
   111  	_ stdFunction
   112  
   113  	// Use RtlGenRandom to generate cryptographically random data.
   114  	// This approach has been recommended by Microsoft (see issue
   115  	// 15589 for details).
   116  	// The RtlGenRandom is not listed in advapi32.dll, instead
   117  	// RtlGenRandom function can be found by searching for SystemFunction036.
   118  	// Also some versions of Mingw cannot link to SystemFunction036
   119  	// when building executable as Cgo. So load SystemFunction036
   120  	// manually during runtime startup.
   121  	_RtlGenRandom stdFunction
   122  
   123  	// Load ntdll.dll manually during startup, otherwise Mingw
   124  	// links wrong printf function to cgo executable (see issue
   125  	// 12030 for details).
   126  	_NtWaitForSingleObject stdFunction
   127  )
   128  
   129  // Function to be called by windows CreateThread
   130  // to start new os thread.
   131  func tstart_stdcall(newm *m) uint32
   132  
   133  func ctrlhandler(_type uint32) uint32
   134  
   135  type mOS struct {
   136  	waitsema uintptr // semaphore for parking on locks
   137  }
   138  
   139  //go:linkname os_sigpipe os.sigpipe
   140  func os_sigpipe() {
   141  	throw("too many writes on closed pipe")
   142  }
   143  
   144  // Stubs so tests can link correctly. These should never be called.
   145  func open(name *byte, mode, perm int32) int32 {
   146  	throw("unimplemented")
   147  	return -1
   148  }
   149  func closefd(fd int32) int32 {
   150  	throw("unimplemented")
   151  	return -1
   152  }
   153  func read(fd int32, p unsafe.Pointer, n int32) int32 {
   154  	throw("unimplemented")
   155  	return -1
   156  }
   157  
   158  type sigset struct{}
   159  
   160  // Call a Windows function with stdcall conventions,
   161  // and switch to os stack during the call.
   162  func asmstdcall(fn unsafe.Pointer)
   163  
   164  var asmstdcallAddr unsafe.Pointer
   165  
   166  func windowsFindfunc(lib uintptr, name []byte) stdFunction {
   167  	if name[len(name)-1] != 0 {
   168  		throw("usage")
   169  	}
   170  	f := stdcall2(_GetProcAddress, lib, uintptr(unsafe.Pointer(&name[0])))
   171  	return stdFunction(unsafe.Pointer(f))
   172  }
   173  
   174  func loadOptionalSyscalls() {
   175  	var kernel32dll = []byte("kernel32.dll\000")
   176  	k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
   177  	if k32 == 0 {
   178  		throw("kernel32.dll not found")
   179  	}
   180  	_AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
   181  	_AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
   182  	_GetQueuedCompletionStatusEx = windowsFindfunc(k32, []byte("GetQueuedCompletionStatusEx\000"))
   183  	_LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
   184  
   185  	var advapi32dll = []byte("advapi32.dll\000")
   186  	a32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&advapi32dll[0])))
   187  	if a32 == 0 {
   188  		throw("advapi32.dll not found")
   189  	}
   190  	_RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
   191  
   192  	var ntdll = []byte("ntdll.dll\000")
   193  	n32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&ntdll[0])))
   194  	if n32 == 0 {
   195  		throw("ntdll.dll not found")
   196  	}
   197  	_NtWaitForSingleObject = windowsFindfunc(n32, []byte("NtWaitForSingleObject\000"))
   198  
   199  	if windowsFindfunc(n32, []byte("wine_get_version\000")) != nil {
   200  		// running on Wine
   201  		initWine(k32)
   202  	}
   203  }
   204  
   205  //go:nosplit
   206  func getLoadLibrary() uintptr {
   207  	return uintptr(unsafe.Pointer(_LoadLibraryW))
   208  }
   209  
   210  //go:nosplit
   211  func getLoadLibraryEx() uintptr {
   212  	return uintptr(unsafe.Pointer(_LoadLibraryExW))
   213  }
   214  
   215  //go:nosplit
   216  func getGetProcAddress() uintptr {
   217  	return uintptr(unsafe.Pointer(_GetProcAddress))
   218  }
   219  
   220  func getproccount() int32 {
   221  	var mask, sysmask uintptr
   222  	ret := stdcall3(_GetProcessAffinityMask, currentProcess, uintptr(unsafe.Pointer(&mask)), uintptr(unsafe.Pointer(&sysmask)))
   223  	if ret != 0 {
   224  		n := 0
   225  		maskbits := int(unsafe.Sizeof(mask) * 8)
   226  		for i := 0; i < maskbits; i++ {
   227  			if mask&(1<<uint(i)) != 0 {
   228  				n++
   229  			}
   230  		}
   231  		if n != 0 {
   232  			return int32(n)
   233  		}
   234  	}
   235  	// use GetSystemInfo if GetProcessAffinityMask fails
   236  	var info systeminfo
   237  	stdcall1(_GetSystemInfo, uintptr(unsafe.Pointer(&info)))
   238  	return int32(info.dwnumberofprocessors)
   239  }
   240  
   241  func getPageSize() uintptr {
   242  	var info systeminfo
   243  	stdcall1(_GetSystemInfo, uintptr(unsafe.Pointer(&info)))
   244  	return uintptr(info.dwpagesize)
   245  }
   246  
   247  const (
   248  	currentProcess = ^uintptr(0) // -1 = current process
   249  	currentThread  = ^uintptr(1) // -2 = current thread
   250  )
   251  
   252  // in sys_windows_386.s and sys_windows_amd64.s:
   253  func externalthreadhandler()
   254  func getlasterror() uint32
   255  func setlasterror(err uint32)
   256  
   257  // When loading DLLs, we prefer to use LoadLibraryEx with
   258  // LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
   259  // available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
   260  // flags are not available on some versions of Windows without a
   261  // security patch.
   262  //
   263  // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
   264  // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
   265  // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
   266  // systems that have KB2533623 installed. To determine whether the
   267  // flags are available, use GetProcAddress to get the address of the
   268  // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
   269  // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
   270  // flags can be used with LoadLibraryEx."
   271  var useLoadLibraryEx bool
   272  
   273  var timeBeginPeriodRetValue uint32
   274  
   275  // osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
   276  // timer is less than 60 ms from now. Since osRelaxing may reduce
   277  // timer resolution to 15.6 ms, this keeps timer error under roughly 1
   278  // part in 4.
   279  const osRelaxMinNS = 60 * 1e6
   280  
   281  // osRelax is called by the scheduler when transitioning to and from
   282  // all Ps being idle.
   283  //
   284  // On Windows, it adjusts the system-wide timer resolution. Go needs a
   285  // high resolution timer while running and there's little extra cost
   286  // if we're already using the CPU, but if all Ps are idle there's no
   287  // need to consume extra power to drive the high-res timer.
   288  func osRelax(relax bool) uint32 {
   289  	if relax {
   290  		return uint32(stdcall1(_timeEndPeriod, 1))
   291  	} else {
   292  		return uint32(stdcall1(_timeBeginPeriod, 1))
   293  	}
   294  }
   295  
   296  func osinit() {
   297  	asmstdcallAddr = unsafe.Pointer(funcPC(asmstdcall))
   298  	usleep2Addr = unsafe.Pointer(funcPC(usleep2))
   299  	switchtothreadAddr = unsafe.Pointer(funcPC(switchtothread))
   300  
   301  	setBadSignalMsg()
   302  
   303  	loadOptionalSyscalls()
   304  
   305  	useLoadLibraryEx = (_LoadLibraryExW != nil && _AddDllDirectory != nil)
   306  
   307  	disableWER()
   308  
   309  	initExceptionHandler()
   310  
   311  	stdcall2(_SetConsoleCtrlHandler, funcPC(ctrlhandler), 1)
   312  
   313  	timeBeginPeriodRetValue = osRelax(false)
   314  
   315  	ncpu = getproccount()
   316  
   317  	physPageSize = getPageSize()
   318  
   319  	// Windows dynamic priority boosting assumes that a process has different types
   320  	// of dedicated threads -- GUI, IO, computational, etc. Go processes use
   321  	// equivalent threads that all do a mix of GUI, IO, computations, etc.
   322  	// In such context dynamic priority boosting does nothing but harm, so we turn it off.
   323  	stdcall2(_SetProcessPriorityBoost, currentProcess, 1)
   324  }
   325  
   326  func nanotime() int64
   327  
   328  // useQPCTime controls whether time.now and nanotime use QueryPerformanceCounter.
   329  // This is only set to 1 when running under Wine.
   330  var useQPCTime uint8
   331  
   332  var qpcStartCounter int64
   333  var qpcMultiplier int64
   334  
   335  //go:nosplit
   336  func nanotimeQPC() int64 {
   337  	var counter int64 = 0
   338  	stdcall1(_QueryPerformanceCounter, uintptr(unsafe.Pointer(&counter)))
   339  
   340  	// returns number of nanoseconds
   341  	return (counter - qpcStartCounter) * qpcMultiplier
   342  }
   343  
   344  //go:nosplit
   345  func nowQPC() (sec int64, nsec int32, mono int64) {
   346  	var ft int64
   347  	stdcall1(_GetSystemTimeAsFileTime, uintptr(unsafe.Pointer(&ft)))
   348  
   349  	t := (ft - 116444736000000000) * 100
   350  
   351  	sec = t / 1000000000
   352  	nsec = int32(t - sec*1000000000)
   353  
   354  	mono = nanotimeQPC()
   355  	return
   356  }
   357  
   358  func initWine(k32 uintptr) {
   359  	_GetSystemTimeAsFileTime = windowsFindfunc(k32, []byte("GetSystemTimeAsFileTime\000"))
   360  	if _GetSystemTimeAsFileTime == nil {
   361  		throw("could not find GetSystemTimeAsFileTime() syscall")
   362  	}
   363  
   364  	_QueryPerformanceCounter = windowsFindfunc(k32, []byte("QueryPerformanceCounter\000"))
   365  	_QueryPerformanceFrequency = windowsFindfunc(k32, []byte("QueryPerformanceFrequency\000"))
   366  	if _QueryPerformanceCounter == nil || _QueryPerformanceFrequency == nil {
   367  		throw("could not find QPC syscalls")
   368  	}
   369  
   370  	// We can not simply fallback to GetSystemTimeAsFileTime() syscall, since its time is not monotonic,
   371  	// instead we use QueryPerformanceCounter family of syscalls to implement monotonic timer
   372  	// https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
   373  
   374  	var tmp int64
   375  	stdcall1(_QueryPerformanceFrequency, uintptr(unsafe.Pointer(&tmp)))
   376  	if tmp == 0 {
   377  		throw("QueryPerformanceFrequency syscall returned zero, running on unsupported hardware")
   378  	}
   379  
   380  	// This should not overflow, it is a number of ticks of the performance counter per second,
   381  	// its resolution is at most 10 per usecond (on Wine, even smaller on real hardware), so it will be at most 10 millions here,
   382  	// panic if overflows.
   383  	if tmp > (1<<31 - 1) {
   384  		throw("QueryPerformanceFrequency overflow 32 bit divider, check nosplit discussion to proceed")
   385  	}
   386  	qpcFrequency := int32(tmp)
   387  	stdcall1(_QueryPerformanceCounter, uintptr(unsafe.Pointer(&qpcStartCounter)))
   388  
   389  	// Since we are supposed to run this time calls only on Wine, it does not lose precision,
   390  	// since Wine's timer is kind of emulated at 10 Mhz, so it will be a nice round multiplier of 100
   391  	// but for general purpose system (like 3.3 Mhz timer on i7) it will not be very precise.
   392  	// We have to do it this way (or similar), since multiplying QPC counter by 100 millions overflows
   393  	// int64 and resulted time will always be invalid.
   394  	qpcMultiplier = int64(timediv(1000000000, qpcFrequency, nil))
   395  
   396  	useQPCTime = 1
   397  }
   398  
   399  //go:nosplit
   400  func getRandomData(r []byte) {
   401  	n := 0
   402  	if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
   403  		n = len(r)
   404  	}
   405  	extendRandom(r, n)
   406  }
   407  
   408  func goenvs() {
   409  	// strings is a pointer to environment variable pairs in the form:
   410  	//     "envA=valA\x00envB=valB\x00\x00" (in UTF-16)
   411  	// Two consecutive zero bytes end the list.
   412  	strings := unsafe.Pointer(stdcall0(_GetEnvironmentStringsW))
   413  	p := (*[1 << 24]uint16)(strings)[:]
   414  
   415  	n := 0
   416  	for from, i := 0, 0; true; i++ {
   417  		if p[i] == 0 {
   418  			// empty string marks the end
   419  			if i == from {
   420  				break
   421  			}
   422  			from = i + 1
   423  			n++
   424  		}
   425  	}
   426  	envs = make([]string, n)
   427  
   428  	for i := range envs {
   429  		envs[i] = gostringw(&p[0])
   430  		for p[0] != 0 {
   431  			p = p[1:]
   432  		}
   433  		p = p[1:] // skip nil byte
   434  	}
   435  
   436  	stdcall1(_FreeEnvironmentStringsW, uintptr(strings))
   437  }
   438  
   439  // exiting is set to non-zero when the process is exiting.
   440  var exiting uint32
   441  
   442  //go:nosplit
   443  func exit(code int32) {
   444  	atomic.Store(&exiting, 1)
   445  	stdcall1(_ExitProcess, uintptr(code))
   446  }
   447  
   448  //go:nosplit
   449  func write(fd uintptr, buf unsafe.Pointer, n int32) int32 {
   450  	const (
   451  		_STD_OUTPUT_HANDLE = ^uintptr(10) // -11
   452  		_STD_ERROR_HANDLE  = ^uintptr(11) // -12
   453  	)
   454  	var handle uintptr
   455  	switch fd {
   456  	case 1:
   457  		handle = stdcall1(_GetStdHandle, _STD_OUTPUT_HANDLE)
   458  	case 2:
   459  		handle = stdcall1(_GetStdHandle, _STD_ERROR_HANDLE)
   460  	default:
   461  		// assume fd is real windows handle.
   462  		handle = fd
   463  	}
   464  	isASCII := true
   465  	b := (*[1 << 30]byte)(buf)[:n]
   466  	for _, x := range b {
   467  		if x >= 0x80 {
   468  			isASCII = false
   469  			break
   470  		}
   471  	}
   472  
   473  	if !isASCII {
   474  		var m uint32
   475  		isConsole := stdcall2(_GetConsoleMode, handle, uintptr(unsafe.Pointer(&m))) != 0
   476  		// If this is a console output, various non-unicode code pages can be in use.
   477  		// Use the dedicated WriteConsole call to ensure unicode is printed correctly.
   478  		if isConsole {
   479  			return int32(writeConsole(handle, buf, n))
   480  		}
   481  	}
   482  	var written uint32
   483  	stdcall5(_WriteFile, handle, uintptr(buf), uintptr(n), uintptr(unsafe.Pointer(&written)), 0)
   484  	return int32(written)
   485  }
   486  
   487  var (
   488  	utf16ConsoleBack     [1000]uint16
   489  	utf16ConsoleBackLock mutex
   490  )
   491  
   492  // writeConsole writes bufLen bytes from buf to the console File.
   493  // It returns the number of bytes written.
   494  func writeConsole(handle uintptr, buf unsafe.Pointer, bufLen int32) int {
   495  	const surr2 = (surrogateMin + surrogateMax + 1) / 2
   496  
   497  	// Do not use defer for unlock. May cause issues when printing a panic.
   498  	lock(&utf16ConsoleBackLock)
   499  
   500  	b := (*[1 << 30]byte)(buf)[:bufLen]
   501  	s := *(*string)(unsafe.Pointer(&b))
   502  
   503  	utf16tmp := utf16ConsoleBack[:]
   504  
   505  	total := len(s)
   506  	w := 0
   507  	for _, r := range s {
   508  		if w >= len(utf16tmp)-2 {
   509  			writeConsoleUTF16(handle, utf16tmp[:w])
   510  			w = 0
   511  		}
   512  		if r < 0x10000 {
   513  			utf16tmp[w] = uint16(r)
   514  			w++
   515  		} else {
   516  			r -= 0x10000
   517  			utf16tmp[w] = surrogateMin + uint16(r>>10)&0x3ff
   518  			utf16tmp[w+1] = surr2 + uint16(r)&0x3ff
   519  			w += 2
   520  		}
   521  	}
   522  	writeConsoleUTF16(handle, utf16tmp[:w])
   523  	unlock(&utf16ConsoleBackLock)
   524  	return total
   525  }
   526  
   527  // writeConsoleUTF16 is the dedicated windows calls that correctly prints
   528  // to the console regardless of the current code page. Input is utf-16 code points.
   529  // The handle must be a console handle.
   530  func writeConsoleUTF16(handle uintptr, b []uint16) {
   531  	l := uint32(len(b))
   532  	if l == 0 {
   533  		return
   534  	}
   535  	var written uint32
   536  	stdcall5(_WriteConsoleW,
   537  		handle,
   538  		uintptr(unsafe.Pointer(&b[0])),
   539  		uintptr(l),
   540  		uintptr(unsafe.Pointer(&written)),
   541  		0,
   542  	)
   543  	return
   544  }
   545  
   546  //go:nosplit
   547  func semasleep(ns int64) int32 {
   548  	const (
   549  		_WAIT_ABANDONED = 0x00000080
   550  		_WAIT_OBJECT_0  = 0x00000000
   551  		_WAIT_TIMEOUT   = 0x00000102
   552  		_WAIT_FAILED    = 0xFFFFFFFF
   553  	)
   554  
   555  	// store ms in ns to save stack space
   556  	if ns < 0 {
   557  		ns = _INFINITE
   558  	} else {
   559  		ns = int64(timediv(ns, 1000000, nil))
   560  		if ns == 0 {
   561  			ns = 1
   562  		}
   563  	}
   564  
   565  	result := stdcall2(_WaitForSingleObject, getg().m.waitsema, uintptr(ns))
   566  	switch result {
   567  	case _WAIT_OBJECT_0: //signaled
   568  		return 0
   569  
   570  	case _WAIT_TIMEOUT:
   571  		return -1
   572  
   573  	case _WAIT_ABANDONED:
   574  		systemstack(func() {
   575  			throw("runtime.semasleep wait_abandoned")
   576  		})
   577  
   578  	case _WAIT_FAILED:
   579  		systemstack(func() {
   580  			print("runtime: waitforsingleobject wait_failed; errno=", getlasterror(), "\n")
   581  			throw("runtime.semasleep wait_failed")
   582  		})
   583  
   584  	default:
   585  		systemstack(func() {
   586  			print("runtime: waitforsingleobject unexpected; result=", result, "\n")
   587  			throw("runtime.semasleep unexpected")
   588  		})
   589  	}
   590  
   591  	return -1 // unreachable
   592  }
   593  
   594  //go:nosplit
   595  func semawakeup(mp *m) {
   596  	if stdcall1(_SetEvent, mp.waitsema) == 0 {
   597  		systemstack(func() {
   598  			print("runtime: setevent failed; errno=", getlasterror(), "\n")
   599  			throw("runtime.semawakeup")
   600  		})
   601  	}
   602  }
   603  
   604  //go:nosplit
   605  func semacreate(mp *m) {
   606  	if mp.waitsema != 0 {
   607  		return
   608  	}
   609  	mp.waitsema = stdcall4(_CreateEventA, 0, 0, 0, 0)
   610  	if mp.waitsema == 0 {
   611  		systemstack(func() {
   612  			print("runtime: createevent failed; errno=", getlasterror(), "\n")
   613  			throw("runtime.semacreate")
   614  		})
   615  	}
   616  }
   617  
   618  // May run with m.p==nil, so write barriers are not allowed. This
   619  // function is called by newosproc0, so it is also required to
   620  // operate without stack guards.
   621  //go:nowritebarrierrec
   622  //go:nosplit
   623  func newosproc(mp *m) {
   624  	// We pass 0 for the stack size to use the default for this binary.
   625  	thandle := stdcall6(_CreateThread, 0, 0,
   626  		funcPC(tstart_stdcall), uintptr(unsafe.Pointer(mp)),
   627  		0, 0)
   628  
   629  	if thandle == 0 {
   630  		if atomic.Load(&exiting) != 0 {
   631  			// CreateThread may fail if called
   632  			// concurrently with ExitProcess. If this
   633  			// happens, just freeze this thread and let
   634  			// the process exit. See issue #18253.
   635  			lock(&deadlock)
   636  			lock(&deadlock)
   637  		}
   638  		print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", getlasterror(), ")\n")
   639  		throw("runtime.newosproc")
   640  	}
   641  
   642  	// Close thandle to avoid leaking the thread object if it exits.
   643  	stdcall1(_CloseHandle, thandle)
   644  }
   645  
   646  // Used by the C library build mode. On Linux this function would allocate a
   647  // stack, but that's not necessary for Windows. No stack guards are present
   648  // and the GC has not been initialized, so write barriers will fail.
   649  //go:nowritebarrierrec
   650  //go:nosplit
   651  func newosproc0(mp *m, stk unsafe.Pointer) {
   652  	// TODO: this is completely broken. The args passed to newosproc0 (in asm_amd64.s)
   653  	// are stacksize and function, not *m and stack.
   654  	// Check os_linux.go for an implemention that might actually work.
   655  	throw("bad newosproc0")
   656  }
   657  
   658  func exitThread(wait *uint32) {
   659  	// We should never reach exitThread on Windows because we let
   660  	// the OS clean up threads.
   661  	throw("exitThread")
   662  }
   663  
   664  // Called to initialize a new m (including the bootstrap m).
   665  // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
   666  func mpreinit(mp *m) {
   667  }
   668  
   669  //go:nosplit
   670  func msigsave(mp *m) {
   671  }
   672  
   673  //go:nosplit
   674  func msigrestore(sigmask sigset) {
   675  }
   676  
   677  //go:nosplit
   678  //go:nowritebarrierrec
   679  func clearSignalHandlers() {
   680  }
   681  
   682  //go:nosplit
   683  func sigblock() {
   684  }
   685  
   686  // Called to initialize a new m (including the bootstrap m).
   687  // Called on the new thread, cannot allocate memory.
   688  func minit() {
   689  	var thandle uintptr
   690  	stdcall7(_DuplicateHandle, currentProcess, currentThread, currentProcess, uintptr(unsafe.Pointer(&thandle)), 0, 0, _DUPLICATE_SAME_ACCESS)
   691  	atomic.Storeuintptr(&getg().m.thread, thandle)
   692  
   693  	// Query the true stack base from the OS. Currently we're
   694  	// running on a small assumed stack.
   695  	var mbi memoryBasicInformation
   696  	res := stdcall3(_VirtualQuery, uintptr(unsafe.Pointer(&mbi)), uintptr(unsafe.Pointer(&mbi)), unsafe.Sizeof(mbi))
   697  	if res == 0 {
   698  		print("runtime: VirtualQuery failed; errno=", getlasterror(), "\n")
   699  		throw("VirtualQuery for stack base failed")
   700  	}
   701  	// The system leaves an 8K PAGE_GUARD region at the bottom of
   702  	// the stack (in theory VirtualQuery isn't supposed to include
   703  	// that, but it does). Add an additional 8K of slop for
   704  	// calling C functions that don't have stack checks and for
   705  	// lastcontinuehandler. We shouldn't be anywhere near this
   706  	// bound anyway.
   707  	base := mbi.allocationBase + 16<<10
   708  	// Sanity check the stack bounds.
   709  	g0 := getg()
   710  	if base > g0.stack.hi || g0.stack.hi-base > 64<<20 {
   711  		print("runtime: g0 stack [", hex(base), ",", hex(g0.stack.hi), ")\n")
   712  		throw("bad g0 stack")
   713  	}
   714  	g0.stack.lo = base
   715  	g0.stackguard0 = g0.stack.lo + _StackGuard
   716  	g0.stackguard1 = g0.stackguard0
   717  	// Sanity check the SP.
   718  	stackcheck()
   719  }
   720  
   721  // Called from dropm to undo the effect of an minit.
   722  //go:nosplit
   723  func unminit() {
   724  	tp := &getg().m.thread
   725  	stdcall1(_CloseHandle, *tp)
   726  	*tp = 0
   727  }
   728  
   729  // Calling stdcall on os stack.
   730  // May run during STW, so write barriers are not allowed.
   731  //go:nowritebarrier
   732  //go:nosplit
   733  func stdcall(fn stdFunction) uintptr {
   734  	gp := getg()
   735  	mp := gp.m
   736  	mp.libcall.fn = uintptr(unsafe.Pointer(fn))
   737  	resetLibcall := false
   738  	if mp.profilehz != 0 && mp.libcallsp == 0 {
   739  		// leave pc/sp for cpu profiler
   740  		mp.libcallg.set(gp)
   741  		mp.libcallpc = getcallerpc()
   742  		// sp must be the last, because once async cpu profiler finds
   743  		// all three values to be non-zero, it will use them
   744  		mp.libcallsp = getcallersp()
   745  		resetLibcall = true // See comment in sys_darwin.go:libcCall
   746  	}
   747  	asmcgocall(asmstdcallAddr, unsafe.Pointer(&mp.libcall))
   748  	if resetLibcall {
   749  		mp.libcallsp = 0
   750  	}
   751  	return mp.libcall.r1
   752  }
   753  
   754  //go:nosplit
   755  func stdcall0(fn stdFunction) uintptr {
   756  	mp := getg().m
   757  	mp.libcall.n = 0
   758  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&fn))) // it's unused but must be non-nil, otherwise crashes
   759  	return stdcall(fn)
   760  }
   761  
   762  //go:nosplit
   763  func stdcall1(fn stdFunction, a0 uintptr) uintptr {
   764  	mp := getg().m
   765  	mp.libcall.n = 1
   766  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   767  	return stdcall(fn)
   768  }
   769  
   770  //go:nosplit
   771  func stdcall2(fn stdFunction, a0, a1 uintptr) uintptr {
   772  	mp := getg().m
   773  	mp.libcall.n = 2
   774  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   775  	return stdcall(fn)
   776  }
   777  
   778  //go:nosplit
   779  func stdcall3(fn stdFunction, a0, a1, a2 uintptr) uintptr {
   780  	mp := getg().m
   781  	mp.libcall.n = 3
   782  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   783  	return stdcall(fn)
   784  }
   785  
   786  //go:nosplit
   787  func stdcall4(fn stdFunction, a0, a1, a2, a3 uintptr) uintptr {
   788  	mp := getg().m
   789  	mp.libcall.n = 4
   790  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   791  	return stdcall(fn)
   792  }
   793  
   794  //go:nosplit
   795  func stdcall5(fn stdFunction, a0, a1, a2, a3, a4 uintptr) uintptr {
   796  	mp := getg().m
   797  	mp.libcall.n = 5
   798  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   799  	return stdcall(fn)
   800  }
   801  
   802  //go:nosplit
   803  func stdcall6(fn stdFunction, a0, a1, a2, a3, a4, a5 uintptr) uintptr {
   804  	mp := getg().m
   805  	mp.libcall.n = 6
   806  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   807  	return stdcall(fn)
   808  }
   809  
   810  //go:nosplit
   811  func stdcall7(fn stdFunction, a0, a1, a2, a3, a4, a5, a6 uintptr) uintptr {
   812  	mp := getg().m
   813  	mp.libcall.n = 7
   814  	mp.libcall.args = uintptr(noescape(unsafe.Pointer(&a0)))
   815  	return stdcall(fn)
   816  }
   817  
   818  // in sys_windows_386.s and sys_windows_amd64.s
   819  func onosstack(fn unsafe.Pointer, arg uint32)
   820  func usleep2(usec uint32)
   821  func switchtothread()
   822  
   823  var usleep2Addr unsafe.Pointer
   824  var switchtothreadAddr unsafe.Pointer
   825  
   826  //go:nosplit
   827  func osyield() {
   828  	onosstack(switchtothreadAddr, 0)
   829  }
   830  
   831  //go:nosplit
   832  func usleep(us uint32) {
   833  	// Have 1us units; want 100ns units.
   834  	onosstack(usleep2Addr, 10*us)
   835  }
   836  
   837  func ctrlhandler1(_type uint32) uint32 {
   838  	var s uint32
   839  
   840  	switch _type {
   841  	case _CTRL_C_EVENT, _CTRL_BREAK_EVENT:
   842  		s = _SIGINT
   843  	default:
   844  		return 0
   845  	}
   846  
   847  	if sigsend(s) {
   848  		return 1
   849  	}
   850  	exit(2) // SIGINT, SIGTERM, etc
   851  	return 0
   852  }
   853  
   854  // in sys_windows_386.s and sys_windows_amd64.s
   855  func profileloop()
   856  
   857  var profiletimer uintptr
   858  
   859  func profilem(mp *m) {
   860  	var r *context
   861  	rbuf := make([]byte, unsafe.Sizeof(*r)+15)
   862  
   863  	tls := &mp.tls[0]
   864  	gp := *((**g)(unsafe.Pointer(tls)))
   865  
   866  	// align Context to 16 bytes
   867  	r = (*context)(unsafe.Pointer((uintptr(unsafe.Pointer(&rbuf[15]))) &^ 15))
   868  	r.contextflags = _CONTEXT_CONTROL
   869  	stdcall2(_GetThreadContext, mp.thread, uintptr(unsafe.Pointer(r)))
   870  	sigprof(r.ip(), r.sp(), 0, gp, mp)
   871  }
   872  
   873  func profileloop1(param uintptr) uint32 {
   874  	stdcall2(_SetThreadPriority, currentThread, _THREAD_PRIORITY_HIGHEST)
   875  
   876  	for {
   877  		stdcall2(_WaitForSingleObject, profiletimer, _INFINITE)
   878  		first := (*m)(atomic.Loadp(unsafe.Pointer(&allm)))
   879  		for mp := first; mp != nil; mp = mp.alllink {
   880  			thread := atomic.Loaduintptr(&mp.thread)
   881  			// Do not profile threads blocked on Notes,
   882  			// this includes idle worker threads,
   883  			// idle timer thread, idle heap scavenger, etc.
   884  			if thread == 0 || mp.profilehz == 0 || mp.blocked {
   885  				continue
   886  			}
   887  			stdcall1(_SuspendThread, thread)
   888  			if mp.profilehz != 0 && !mp.blocked {
   889  				profilem(mp)
   890  			}
   891  			stdcall1(_ResumeThread, thread)
   892  		}
   893  	}
   894  }
   895  
   896  func setProcessCPUProfiler(hz int32) {
   897  	if profiletimer == 0 {
   898  		timer := stdcall3(_CreateWaitableTimerA, 0, 0, 0)
   899  		atomic.Storeuintptr(&profiletimer, timer)
   900  		thread := stdcall6(_CreateThread, 0, 0, funcPC(profileloop), 0, 0, 0)
   901  		stdcall2(_SetThreadPriority, thread, _THREAD_PRIORITY_HIGHEST)
   902  		stdcall1(_CloseHandle, thread)
   903  	}
   904  }
   905  
   906  func setThreadCPUProfiler(hz int32) {
   907  	ms := int32(0)
   908  	due := ^int64(^uint64(1 << 63))
   909  	if hz > 0 {
   910  		ms = 1000 / hz
   911  		if ms == 0 {
   912  			ms = 1
   913  		}
   914  		due = int64(ms) * -10000
   915  	}
   916  	stdcall6(_SetWaitableTimer, profiletimer, uintptr(unsafe.Pointer(&due)), uintptr(ms), 0, 0, 0)
   917  	atomic.Store((*uint32)(unsafe.Pointer(&getg().m.profilehz)), uint32(hz))
   918  }
   919  

View as plain text