modernc.org/libc@v1.24.1/libc_windows.go (about)

     1  // Copyright 2020 The Libc 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 libc // import "modernc.org/libc"
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"math"
    11  	"os"
    12  	"os/exec"
    13  	"os/user"
    14  	"path/filepath"
    15  	"strings"
    16  	"sync"
    17  	"sync/atomic"
    18  	"syscall"
    19  	gotime "time"
    20  	"unicode"
    21  	"unicode/utf16"
    22  	"unsafe"
    23  
    24  	"modernc.org/libc/errno"
    25  	"modernc.org/libc/fcntl"
    26  	"modernc.org/libc/limits"
    27  	"modernc.org/libc/stdio"
    28  	"modernc.org/libc/sys/stat"
    29  	"modernc.org/libc/sys/types"
    30  	"modernc.org/libc/time"
    31  	"modernc.org/libc/unistd"
    32  )
    33  
    34  // Keep these outside of the var block otherwise go generate will miss them.
    35  var X__imp__environ = EnvironP()
    36  var X__imp__wenviron = uintptr(unsafe.Pointer(&wenviron))
    37  var X_imp___environ = EnvironP()
    38  var X_iob [stdio.X_IOB_ENTRIES]stdio.FILE
    39  
    40  var Xtimezone long // extern long timezone;
    41  
    42  var (
    43  	iobMap     = map[uintptr]int32{} // &_iob[fd] -> fd
    44  	wenvValid  bool
    45  	wenviron   uintptr // &winEnviron[0]
    46  	winEnviron = []uintptr{0}
    47  )
    48  
    49  func init() {
    50  	for i := range X_iob {
    51  		iobMap[uintptr(unsafe.Pointer(&X_iob[i]))] = int32(i)
    52  	}
    53  }
    54  
    55  func winGetObject(stream uintptr) interface{} {
    56  	if fd, ok := iobMap[stream]; ok {
    57  		f, _ := fdToFile(fd)
    58  		return f
    59  	}
    60  
    61  	return getObject(stream)
    62  }
    63  
    64  type (
    65  	long  = int32
    66  	ulong = uint32
    67  )
    68  
    69  var (
    70  	modkernel32 = syscall.NewLazyDLL("kernel32.dll")
    71  	//--
    72  	procAreFileApisANSI            = modkernel32.NewProc("AreFileApisANSI")
    73  	procCopyFileW                  = modkernel32.NewProc("CopyFileW")
    74  	procCreateEventA               = modkernel32.NewProc("CreateEventA")
    75  	procCreateEventW               = modkernel32.NewProc("CreateEventW")
    76  	procCreateFileA                = modkernel32.NewProc("CreateFileA")
    77  	procCreateFileMappingW         = modkernel32.NewProc("CreateFileMappingW")
    78  	procCreateFileW                = modkernel32.NewProc("CreateFileW")
    79  	procCreateHardLinkW            = modkernel32.NewProc("CreateHardLinkW")
    80  	procCreatePipe                 = modkernel32.NewProc("CreatePipe")
    81  	procCreateProcessA             = modkernel32.NewProc("CreateProcessA")
    82  	procCreateProcessW             = modkernel32.NewProc("CreateProcessW")
    83  	procCreateThread               = modkernel32.NewProc("CreateThread")
    84  	procDeleteCriticalSection      = modkernel32.NewProc("DeleteCriticalSection")
    85  	procDeviceIoControl            = modkernel32.NewProc("DeviceIoControl")
    86  	procDuplicateHandle            = modkernel32.NewProc("DuplicateHandle")
    87  	procEnterCriticalSection       = modkernel32.NewProc("EnterCriticalSection")
    88  	procFindClose                  = modkernel32.NewProc("FindClose")
    89  	procFindFirstFileExW           = modkernel32.NewProc("FindFirstFileExW")
    90  	procFindFirstFileW             = modkernel32.NewProc("FindFirstFileW")
    91  	procFindNextFileW              = modkernel32.NewProc("FindNextFileW")
    92  	procFormatMessageW             = modkernel32.NewProc("FormatMessageW")
    93  	procGetACP                     = modkernel32.NewProc("GetACP")
    94  	procGetCommState               = modkernel32.NewProc("GetCommState")
    95  	procGetComputerNameExW         = modkernel32.NewProc("GetComputerNameExW")
    96  	procGetConsoleCP               = modkernel32.NewProc("GetConsoleCP")
    97  	procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo")
    98  	procGetCurrentProcess          = modkernel32.NewProc("GetCurrentProcess")
    99  	procGetCurrentProcessId        = modkernel32.NewProc("GetCurrentProcessId")
   100  	procGetCurrentThread           = modkernel32.NewProc("GetCurrentThread")
   101  	procGetCurrentThreadId         = modkernel32.NewProc("GetCurrentThreadId")
   102  	procGetEnvironmentVariableA    = modkernel32.NewProc("GetEnvironmentVariableA")
   103  	procGetEnvironmentVariableW    = modkernel32.NewProc("GetEnvironmentVariableW")
   104  	procGetExitCodeProcess         = modkernel32.NewProc("GetExitCodeProcess")
   105  	procGetExitCodeThread          = modkernel32.NewProc("GetExitCodeThread")
   106  	procGetFileAttributesA         = modkernel32.NewProc("GetFileAttributesA")
   107  	procGetFileAttributesExA       = modkernel32.NewProc("GetFileAttributesExA")
   108  	procGetFileAttributesExW       = modkernel32.NewProc("GetFileAttributesExW")
   109  	procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle")
   110  	procGetFileSize                = modkernel32.NewProc("GetFileSize")
   111  	procGetFullPathNameW           = modkernel32.NewProc("GetFullPathNameW")
   112  	procGetLastError               = modkernel32.NewProc("GetLastError")
   113  	procGetLogicalDriveStringsA    = modkernel32.NewProc("GetLogicalDriveStringsA")
   114  	procGetModuleFileNameW         = modkernel32.NewProc("GetModuleFileNameW")
   115  	procGetModuleHandleA           = modkernel32.NewProc("GetModuleHandleA")
   116  	procGetModuleHandleW           = modkernel32.NewProc("GetModuleHandleW")
   117  	procGetPrivateProfileStringA   = modkernel32.NewProc("GetPrivateProfileStringA")
   118  	procGetProcAddress             = modkernel32.NewProc("GetProcAddress")
   119  	procGetProcessHeap             = modkernel32.NewProc("GetProcessHeap")
   120  	procGetSystemInfo              = modkernel32.NewProc("GetSystemInfo")
   121  	procGetSystemTime              = modkernel32.NewProc("GetSystemTime")
   122  	procGetSystemTimeAsFileTime    = modkernel32.NewProc("GetSystemTimeAsFileTime")
   123  	procGetTempFileNameW           = modkernel32.NewProc("GetTempFileNameW")
   124  	procGetTickCount               = modkernel32.NewProc("GetTickCount")
   125  	procGetVersionExA              = modkernel32.NewProc("GetVersionExA")
   126  	procGetVersionExW              = modkernel32.NewProc("GetVersionExW")
   127  	procGetVolumeInformationA      = modkernel32.NewProc("GetVolumeInformationA")
   128  	procGetVolumeInformationW      = modkernel32.NewProc("GetVolumeInformationW")
   129  	procHeapAlloc                  = modkernel32.NewProc("HeapAlloc")
   130  	procHeapFree                   = modkernel32.NewProc("HeapFree")
   131  	procInitializeCriticalSection  = modkernel32.NewProc("InitializeCriticalSection")
   132  	procLeaveCriticalSection       = modkernel32.NewProc("LeaveCriticalSection")
   133  	procLockFile                   = modkernel32.NewProc("LockFile")
   134  	procLockFileEx                 = modkernel32.NewProc("LockFileEx")
   135  	procLstrlenW                   = modkernel32.NewProc("lstrlenW")
   136  	procMapViewOfFile              = modkernel32.NewProc("MapViewOfFile")
   137  	procMoveFileW                  = modkernel32.NewProc("MoveFileW")
   138  	procMultiByteToWideChar        = modkernel32.NewProc("MultiByteToWideChar")
   139  	procOpenEventA                 = modkernel32.NewProc("OpenEventA")
   140  	procPeekConsoleInputW          = modkernel32.NewProc("PeekConsoleInputW")
   141  	procPeekNamedPipe              = modkernel32.NewProc("PeekNamedPipe")
   142  	procQueryPerformanceCounter    = modkernel32.NewProc("QueryPerformanceCounter")
   143  	procQueryPerformanceFrequency  = modkernel32.NewProc("QueryPerformanceFrequency")
   144  	procReadConsoleW               = modkernel32.NewProc("ReadConsoleW")
   145  	procReadFile                   = modkernel32.NewProc("ReadFile")
   146  	procResetEvent                 = modkernel32.NewProc("ResetEvent")
   147  	procSearchPathW                = modkernel32.NewProc("SearchPathW")
   148  	procSetConsoleCtrlHandler      = modkernel32.NewProc("SetConsoleCtrlHandler")
   149  	procSetConsoleMode             = modkernel32.NewProc("SetConsoleMode")
   150  	procSetConsoleTextAttribute    = modkernel32.NewProc("SetConsoleTextAttribute")
   151  	procSetEvent                   = modkernel32.NewProc("SetEvent")
   152  	procSetFilePointer             = modkernel32.NewProc("SetFilePointer")
   153  	procSleepEx                    = modkernel32.NewProc("SleepEx")
   154  	procSystemTimeToFileTime       = modkernel32.NewProc("SystemTimeToFileTime")
   155  	procTerminateThread            = modkernel32.NewProc("TerminateThread")
   156  	procUnlockFile                 = modkernel32.NewProc("UnlockFile")
   157  	procUnlockFileEx               = modkernel32.NewProc("UnlockFileEx")
   158  	procWaitForSingleObjectEx      = modkernel32.NewProc("WaitForSingleObjectEx")
   159  	procWideCharToMultiByte        = modkernel32.NewProc("WideCharToMultiByte")
   160  	procWriteConsoleA              = modkernel32.NewProc("WriteConsoleA")
   161  	procWriteConsoleW              = modkernel32.NewProc("WriteConsoleW")
   162  	procWriteFile                  = modkernel32.NewProc("WriteFile")
   163  
   164  	//	procSetConsoleCP               = modkernel32.NewProc("SetConsoleCP")
   165  	//	procSetThreadPriority          = modkernel32.NewProc("SetThreadPriority")
   166  	//--
   167  
   168  	modadvapi = syscall.NewLazyDLL("advapi32.dll")
   169  	//--
   170  	procAccessCheck                = modadvapi.NewProc("AccessCheck")
   171  	procGetAclInformation          = modadvapi.NewProc("GetAclInformation")
   172  	procGetFileSecurityA           = modadvapi.NewProc("GetFileSecurityA")
   173  	procGetFileSecurityW           = modadvapi.NewProc("GetFileSecurityW")
   174  	procGetSecurityDescriptorDacl  = modadvapi.NewProc("GetSecurityDescriptorDacl")
   175  	procGetSecurityDescriptorOwner = modadvapi.NewProc("GetSecurityDescriptorOwner")
   176  	procGetSidIdentifierAuthority  = modadvapi.NewProc("GetSidIdentifierAuthority")
   177  	procGetSidLengthRequired       = modadvapi.NewProc("GetSidLengthRequired")
   178  	procGetSidSubAuthority         = modadvapi.NewProc("GetSidSubAuthority")
   179  	procImpersonateSelf            = modadvapi.NewProc("ImpersonateSelf")
   180  	procInitializeSid              = modadvapi.NewProc("InitializeSid")
   181  	procOpenThreadToken            = modadvapi.NewProc("OpenThreadToken")
   182  	procRevertToSelf               = modadvapi.NewProc("RevertToSelf")
   183  	//--
   184  
   185  	modws2_32 = syscall.NewLazyDLL("ws2_32.dll")
   186  	//--
   187  	procWSAStartup = modws2_32.NewProc("WSAStartup")
   188  	//--
   189  
   190  	moduser32 = syscall.NewLazyDLL("user32.dll")
   191  	//--
   192  	procCreateWindowExW             = moduser32.NewProc("CreateWindowExW")
   193  	procMsgWaitForMultipleObjectsEx = moduser32.NewProc("MsgWaitForMultipleObjectsEx")
   194  	procPeekMessageW                = moduser32.NewProc("PeekMessageW")
   195  	procRegisterClassW              = moduser32.NewProc("RegisterClassW")
   196  	procUnregisterClassW            = moduser32.NewProc("UnregisterClassW")
   197  	procWaitForInputIdle            = moduser32.NewProc("WaitForInputIdle")
   198  	//--
   199  
   200  	netapi             = syscall.NewLazyDLL("netapi32.dll")
   201  	procNetGetDCName   = netapi.NewProc("NetGetDCName")
   202  	procNetUserGetInfo = netapi.NewProc("NetUserGetInfo")
   203  
   204  	userenvapi                = syscall.NewLazyDLL("userenv.dll")
   205  	procGetProfilesDirectoryW = userenvapi.NewProc("GetProfilesDirectoryW")
   206  )
   207  
   208  var (
   209  	threadCallback uintptr
   210  )
   211  
   212  func init() {
   213  	isWindows = true
   214  	threadCallback = syscall.NewCallback(ThreadProc)
   215  }
   216  
   217  // ---------------------------------
   218  // Windows filehandle-to-fd mapping
   219  // so the lib-c interface contract looks
   220  // like normal fds being passed around
   221  // but we're mapping them back and forth to
   222  // native windows file handles (syscall.Handle)
   223  //
   224  
   225  var EBADF = errors.New("EBADF")
   226  
   227  var w_nextFd int32 = 42
   228  var w_fdLock sync.Mutex
   229  var w_fd_to_file = map[int32]*file{}
   230  
   231  type file struct {
   232  	_fd    int32
   233  	hadErr bool
   234  	t      uintptr
   235  	syscall.Handle
   236  }
   237  
   238  func addFile(hdl syscall.Handle, fd int32) uintptr {
   239  	var f = file{_fd: fd, Handle: hdl}
   240  	w_fdLock.Lock()
   241  	defer w_fdLock.Unlock()
   242  	w_fd_to_file[fd] = &f
   243  	f.t = addObject(&f)
   244  	return f.t
   245  }
   246  
   247  func remFile(f *file) {
   248  	removeObject(f.t)
   249  	w_fdLock.Lock()
   250  	defer w_fdLock.Unlock()
   251  	delete(w_fd_to_file, f._fd)
   252  }
   253  
   254  func fdToFile(fd int32) (*file, bool) {
   255  	w_fdLock.Lock()
   256  	defer w_fdLock.Unlock()
   257  	f, ok := w_fd_to_file[fd]
   258  	return f, ok
   259  }
   260  
   261  // Wrap the windows handle up tied to a unique fd
   262  func wrapFdHandle(hdl syscall.Handle) (uintptr, int32) {
   263  	newFd := atomic.AddInt32(&w_nextFd, 1)
   264  	return addFile(hdl, newFd), newFd
   265  }
   266  
   267  func (f *file) err() bool {
   268  	return f.hadErr
   269  }
   270  
   271  func (f *file) setErr() {
   272  	f.hadErr = true
   273  }
   274  
   275  // -----------------------------------
   276  // On windows we have to fetch these
   277  //
   278  // stdout, stdin, sterr
   279  //
   280  // Using the windows specific GetStdHandle
   281  // they're mapped to the standard fds (0,1,2)
   282  // Note: it's possible they don't exist
   283  // if the app has been built for a GUI only
   284  // target in windows. If that's the case
   285  // panic seems like the only reasonable option
   286  // ------------------------------
   287  
   288  func newFile(t *TLS, fd int32) uintptr {
   289  
   290  	if fd == unistd.STDIN_FILENO {
   291  		h, err := syscall.GetStdHandle(syscall.STD_INPUT_HANDLE)
   292  		if err != nil {
   293  			panic("no console")
   294  		}
   295  		return addFile(h, fd)
   296  	}
   297  	if fd == unistd.STDOUT_FILENO {
   298  		h, err := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
   299  		if err != nil {
   300  			panic("no console")
   301  		}
   302  		return addFile(h, fd)
   303  	}
   304  	if fd == unistd.STDERR_FILENO {
   305  		h, err := syscall.GetStdHandle(syscall.STD_ERROR_HANDLE)
   306  		if err != nil {
   307  			panic("no console")
   308  		}
   309  		return addFile(h, fd)
   310  	}
   311  
   312  	// should not get here -- unless newFile
   313  	// is being used from somewhere we don't know about
   314  	// to originate fds.
   315  
   316  	panic("unknown fd source")
   317  	return 0
   318  }
   319  
   320  func (f *file) close(t *TLS) int32 {
   321  	remFile(f)
   322  	err := syscall.Close(f.Handle)
   323  	if err != nil {
   324  		return (-1) // EOF
   325  	}
   326  	return 0
   327  }
   328  
   329  func fwrite(fd int32, b []byte) (int, error) {
   330  	if fd == unistd.STDOUT_FILENO {
   331  		return write(b)
   332  	}
   333  
   334  	f, ok := fdToFile(fd)
   335  	if !ok {
   336  		return -1, EBADF
   337  	}
   338  
   339  	if dmesgs {
   340  		dmesg("%v: fd %v: %s", origin(1), fd, b)
   341  	}
   342  	return syscall.Write(f.Handle, b)
   343  }
   344  
   345  // int fprintf(FILE *stream, const char *format, ...);
   346  func Xfprintf(t *TLS, stream, format, args uintptr) int32 {
   347  	f, ok := winGetObject(stream).(*file)
   348  	if !ok {
   349  		t.setErrno(errno.EBADF)
   350  		return -1
   351  	}
   352  
   353  	n, _ := fwrite(f._fd, printf(format, args))
   354  	return int32(n)
   355  }
   356  
   357  // int usleep(useconds_t usec);
   358  func Xusleep(t *TLS, usec types.Useconds_t) int32 {
   359  	gotime.Sleep(gotime.Microsecond * gotime.Duration(usec))
   360  	return 0
   361  }
   362  
   363  // int getrusage(int who, struct rusage *usage);
   364  func Xgetrusage(t *TLS, who int32, usage uintptr) int32 {
   365  	panic(todo(""))
   366  	// if _, _, err := unix.Syscall(unix.SYS_GETRUSAGE, uintptr(who), usage, 0); err != 0 {
   367  	// 	t.setErrno(err)
   368  	// 	return -1
   369  	// }
   370  
   371  	// return 0
   372  }
   373  
   374  // int lstat(const char *pathname, struct stat *statbuf);
   375  func Xlstat(t *TLS, pathname, statbuf uintptr) int32 {
   376  	return Xlstat64(t, pathname, statbuf)
   377  }
   378  
   379  // int stat(const char *pathname, struct stat *statbuf);
   380  func Xstat(t *TLS, pathname, statbuf uintptr) int32 {
   381  	return Xstat64(t, pathname, statbuf)
   382  }
   383  
   384  // int chdir(const char *path);
   385  func Xchdir(t *TLS, path uintptr) int32 {
   386  	err := syscall.Chdir(GoString(path))
   387  	if err != nil {
   388  		t.setErrno(err)
   389  		return -1
   390  	}
   391  
   392  	if dmesgs {
   393  		dmesg("%v: %q: ok", origin(1), GoString(path))
   394  	}
   395  	return 0
   396  }
   397  
   398  var localtime time.Tm
   399  
   400  // struct tm *localtime(const time_t *timep);
   401  func Xlocaltime(_ *TLS, timep uintptr) uintptr {
   402  	loc := getLocalLocation()
   403  	ut := *(*time.Time_t)(unsafe.Pointer(timep))
   404  	t := gotime.Unix(int64(ut), 0).In(loc)
   405  	localtime.Ftm_sec = int32(t.Second())
   406  	localtime.Ftm_min = int32(t.Minute())
   407  	localtime.Ftm_hour = int32(t.Hour())
   408  	localtime.Ftm_mday = int32(t.Day())
   409  	localtime.Ftm_mon = int32(t.Month() - 1)
   410  	localtime.Ftm_year = int32(t.Year() - 1900)
   411  	localtime.Ftm_wday = int32(t.Weekday())
   412  	localtime.Ftm_yday = int32(t.YearDay())
   413  	localtime.Ftm_isdst = Bool32(isTimeDST(t))
   414  	return uintptr(unsafe.Pointer(&localtime))
   415  }
   416  
   417  // struct tm *localtime(const time_t *timep);
   418  func X_localtime64(_ *TLS, timep uintptr) uintptr {
   419  	return Xlocaltime(nil, timep)
   420  }
   421  
   422  // struct tm *localtime_r(const time_t *timep, struct tm *result);
   423  func Xlocaltime_r(_ *TLS, timep, result uintptr) uintptr {
   424  	panic(todo(""))
   425  	// loc := getLocalLocation()
   426  	// ut := *(*unix.Time_t)(unsafe.Pointer(timep))
   427  	// t := gotime.Unix(int64(ut), 0).In(loc)
   428  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_sec = int32(t.Second())
   429  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_min = int32(t.Minute())
   430  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_hour = int32(t.Hour())
   431  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_mday = int32(t.Day())
   432  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_mon = int32(t.Month() - 1)
   433  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_year = int32(t.Year() - 1900)
   434  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_wday = int32(t.Weekday())
   435  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_yday = int32(t.YearDay())
   436  	// (*time.Tm)(unsafe.Pointer(result)).Ftm_isdst = Bool32(isTimeDST(t))
   437  	// return result
   438  }
   439  
   440  // int _wopen(
   441  //
   442  //	const wchar_t *filename,
   443  //	int oflag [,
   444  //	int pmode]
   445  //
   446  // );
   447  func X_wopen(t *TLS, pathname uintptr, flags int32, args uintptr) int32 {
   448  	var mode types.Mode_t
   449  	if args != 0 {
   450  		mode = *(*types.Mode_t)(unsafe.Pointer(args))
   451  	}
   452  	s := goWideString(pathname)
   453  	h, err := syscall.Open(GoString(pathname), int(flags), uint32(mode))
   454  	if err != nil {
   455  		if dmesgs {
   456  			dmesg("%v: %q %#x: %v", origin(1), s, flags, err)
   457  		}
   458  
   459  		t.setErrno(err)
   460  		return 0
   461  	}
   462  
   463  	_, n := wrapFdHandle(h)
   464  	if dmesgs {
   465  		dmesg("%v: %q flags %#x mode %#o: fd %v", origin(1), s, flags, mode, n)
   466  	}
   467  	return n
   468  }
   469  
   470  // int open(const char *pathname, int flags, ...);
   471  func Xopen(t *TLS, pathname uintptr, flags int32, args uintptr) int32 {
   472  	return Xopen64(t, pathname, flags, args)
   473  }
   474  
   475  // int open(const char *pathname, int flags, ...);
   476  func Xopen64(t *TLS, pathname uintptr, flags int32, cmode uintptr) int32 {
   477  
   478  	var mode types.Mode_t
   479  	if cmode != 0 {
   480  		mode = (types.Mode_t)(VaUint32(&cmode))
   481  	}
   482  	// 	fdcwd := fcntl.AT_FDCWD
   483  	h, err := syscall.Open(GoString(pathname), int(flags), uint32(mode))
   484  	if err != nil {
   485  
   486  		if dmesgs {
   487  			dmesg("%v: %q %#x: %v", origin(1), GoString(pathname), flags, err)
   488  		}
   489  
   490  		t.setErrno(err)
   491  		return -1
   492  	}
   493  
   494  	_, n := wrapFdHandle(h)
   495  	if dmesgs {
   496  		dmesg("%v: %q flags %#x mode %#o: fd %v", origin(1), GoString(pathname), flags, mode, n)
   497  	}
   498  	return n
   499  }
   500  
   501  // off_t lseek(int fd, off_t offset, int whence);
   502  func Xlseek(t *TLS, fd int32, offset types.Off_t, whence int32) types.Off_t {
   503  	return types.Off_t(Xlseek64(t, fd, offset, whence))
   504  }
   505  
   506  func whenceStr(whence int32) string {
   507  	switch whence {
   508  	case syscall.FILE_CURRENT:
   509  		return "SEEK_CUR"
   510  	case syscall.FILE_END:
   511  		return "SEEK_END"
   512  	case syscall.FILE_BEGIN:
   513  		return "SEEK_SET"
   514  	default:
   515  		return fmt.Sprintf("whence(%d)", whence)
   516  	}
   517  }
   518  
   519  var fsyncStatbuf stat.Stat
   520  
   521  // int fsync(int fd);
   522  func Xfsync(t *TLS, fd int32) int32 {
   523  
   524  	f, ok := fdToFile(fd)
   525  	if !ok {
   526  		t.setErrno(errno.EBADF)
   527  		return -1
   528  	}
   529  	err := syscall.FlushFileBuffers(f.Handle)
   530  	if err != nil {
   531  		t.setErrno(err)
   532  		return -1
   533  	}
   534  
   535  	if dmesgs {
   536  		dmesg("%v: %d: ok", origin(1), fd)
   537  	}
   538  	return 0
   539  }
   540  
   541  // long sysconf(int name);
   542  func Xsysconf(t *TLS, name int32) long {
   543  	panic(todo(""))
   544  	// switch name {
   545  	// case unistd.X_SC_PAGESIZE:
   546  	// 	return long(unix.Getpagesize())
   547  	// }
   548  
   549  	// panic(todo(""))
   550  }
   551  
   552  // int close(int fd);
   553  func Xclose(t *TLS, fd int32) int32 {
   554  
   555  	f, ok := fdToFile(fd)
   556  	if !ok {
   557  		t.setErrno(errno.EBADF)
   558  		return -1
   559  	}
   560  
   561  	err := syscall.Close(f.Handle)
   562  	if err != nil {
   563  		t.setErrno(err)
   564  		return -1
   565  	}
   566  
   567  	if dmesgs {
   568  		dmesg("%v: %d: ok", origin(1), fd)
   569  	}
   570  	return 0
   571  }
   572  
   573  // char *getcwd(char *buf, size_t size);
   574  func Xgetcwd(t *TLS, buf uintptr, size types.Size_t) uintptr {
   575  
   576  	b := make([]uint16, size)
   577  	n, err := syscall.GetCurrentDirectory(uint32(len(b)), &b[0])
   578  	if err != nil {
   579  		t.setErrno(err)
   580  		return 0
   581  	}
   582  	// to bytes
   583  	var wd = []byte(string(utf16.Decode(b[0:n])))
   584  	if types.Size_t(len(wd)) > size {
   585  		t.setErrno(errno.ERANGE)
   586  		return 0
   587  	}
   588  
   589  	copy((*RawMem)(unsafe.Pointer(buf))[:], wd)
   590  	(*RawMem)(unsafe.Pointer(buf))[len(wd)] = 0
   591  
   592  	if dmesgs {
   593  		dmesg("%v: %q: ok", origin(1), GoString(buf))
   594  	}
   595  	return buf
   596  }
   597  
   598  // int fstat(int fd, struct stat *statbuf);
   599  func Xfstat(t *TLS, fd int32, statbuf uintptr) int32 {
   600  	return Xfstat64(t, fd, statbuf)
   601  }
   602  
   603  // int ftruncate(int fd, off_t length);
   604  func Xftruncate(t *TLS, fd int32, length types.Off_t) int32 {
   605  	return Xftruncate64(t, fd, length)
   606  }
   607  
   608  // int fcntl(int fd, int cmd, ... /* arg */ );
   609  func Xfcntl(t *TLS, fd, cmd int32, args uintptr) int32 {
   610  	return Xfcntl64(t, fd, cmd, args)
   611  }
   612  
   613  // int _read( // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/read?view=msvc-160
   614  //
   615  //	int const fd,
   616  //	void * const buffer,
   617  //	unsigned const buffer_size
   618  //
   619  // );
   620  func Xread(t *TLS, fd int32, buf uintptr, count uint32) int32 {
   621  	f, ok := fdToFile(fd)
   622  	if !ok {
   623  		t.setErrno(errno.EBADF)
   624  		return -1
   625  	}
   626  
   627  	var obuf = ((*RawMem)(unsafe.Pointer(buf)))[:count]
   628  	n, err := syscall.Read(f.Handle, obuf)
   629  	if err != nil {
   630  		t.setErrno(err)
   631  		return -1
   632  	}
   633  
   634  	if dmesgs {
   635  		// dmesg("%v: %d %#x: %#x\n%s", origin(1), fd, count, n, hex.Dump(GoBytes(buf, int(n))))
   636  		dmesg("%v: %d %#x: %#x", origin(1), fd, count, n)
   637  	}
   638  	return int32(n)
   639  }
   640  
   641  // int _write( // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/write?view=msvc-160
   642  //
   643  //	int fd,
   644  //	const void *buffer,
   645  //	unsigned int count
   646  //
   647  // );
   648  func Xwrite(t *TLS, fd int32, buf uintptr, count uint32) int32 {
   649  	f, ok := fdToFile(fd)
   650  	if !ok {
   651  		t.setErrno(errno.EBADF)
   652  		return -1
   653  	}
   654  
   655  	var obuf = ((*RawMem)(unsafe.Pointer(buf)))[:count]
   656  	n, err := syscall.Write(f.Handle, obuf)
   657  	if err != nil {
   658  		if dmesgs {
   659  			dmesg("%v: fd %v, count %#x: %v", origin(1), fd, count, err)
   660  		}
   661  		t.setErrno(err)
   662  		return -1
   663  	}
   664  
   665  	if dmesgs {
   666  		// dmesg("%v: %d %#x: %#x\n%s", origin(1), fd, count, n, hex.Dump(GoBytes(buf, int(n))))
   667  		dmesg("%v: %d %#x: %#x", origin(1), fd, count, n)
   668  	}
   669  	return int32(n)
   670  }
   671  
   672  // int fchmod(int fd, mode_t mode);
   673  func Xfchmod(t *TLS, fd int32, mode types.Mode_t) int32 {
   674  	panic(todo(""))
   675  	// if _, _, err := unix.Syscall(unix.SYS_FCHMOD, uintptr(fd), uintptr(mode), 0); err != 0 {
   676  	// 	t.setErrno(err)
   677  	// 	return -1
   678  	// }
   679  
   680  	// if dmesgs {
   681  	// 	dmesg("%v: %d %#o: ok", origin(1), fd, mode)
   682  	// }
   683  	// return 0
   684  }
   685  
   686  // // int fchown(int fd, uid_t owner, gid_t group);
   687  // func Xfchown(t *TLS, fd int32, owner types.Uid_t, group types.Gid_t) int32 {
   688  // 	if _, _, err := unix.Syscall(unix.SYS_FCHOWN, uintptr(fd), uintptr(owner), uintptr(group)); err != 0 {
   689  // 		t.setErrno(err)
   690  // 		return -1
   691  // 	}
   692  //
   693  // 	return 0
   694  // }
   695  
   696  // // uid_t geteuid(void);
   697  // func Xgeteuid(t *TLS) types.Uid_t {
   698  // 	n, _, _ := unix.Syscall(unix.SYS_GETEUID, 0, 0, 0)
   699  // 	return types.Uid_t(n)
   700  // }
   701  
   702  // int munmap(void *addr, size_t length);
   703  func Xmunmap(t *TLS, addr uintptr, length types.Size_t) int32 {
   704  	panic(todo(""))
   705  	// if _, _, err := unix.Syscall(unix.SYS_MUNMAP, addr, uintptr(length), 0); err != 0 {
   706  	// 	t.setErrno(err)
   707  	// 	return -1
   708  	// }
   709  
   710  	// return 0
   711  }
   712  
   713  // int gettimeofday(struct timeval *tv, struct timezone *tz);
   714  func Xgettimeofday(t *TLS, tv, tz uintptr) int32 {
   715  	panic(todo(""))
   716  	// if tz != 0 {
   717  	// 	panic(todo(""))
   718  	// }
   719  
   720  	// var tvs unix.Timeval
   721  	// err := unix.Gettimeofday(&tvs)
   722  	// if err != nil {
   723  	// 	t.setErrno(err)
   724  	// 	return -1
   725  	// }
   726  
   727  	// *(*unix.Timeval)(unsafe.Pointer(tv)) = tvs
   728  	// return 0
   729  }
   730  
   731  // int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
   732  func Xgetsockopt(t *TLS, _ ...interface{}) int32 {
   733  	panic(todo(""))
   734  	// if _, _, err := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(sockfd), uintptr(level), uintptr(optname), optval, optlen, 0); err != 0 {
   735  	// 	t.setErrno(err)
   736  	// 	return -1
   737  	// }
   738  
   739  	// return 0
   740  }
   741  
   742  // // int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
   743  func Xsetsockopt(t *TLS, _ ...interface{}) int32 {
   744  	panic(todo(""))
   745  }
   746  
   747  // int ioctl(int fd, unsigned long request, ...);
   748  func Xioctl(t *TLS, fd int32, request ulong, va uintptr) int32 {
   749  	panic(todo(""))
   750  	// var argp uintptr
   751  	// if va != 0 {
   752  	// 	argp = VaUintptr(&va)
   753  	// }
   754  	// n, _, err := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(request), argp)
   755  	// if err != 0 {
   756  	// 	t.setErrno(err)
   757  	// 	return -1
   758  	// }
   759  
   760  	// return int32(n)
   761  }
   762  
   763  // int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
   764  func Xselect(t *TLS, nfds int32, readfds, writefds, exceptfds, timeout uintptr) int32 {
   765  	panic(todo(""))
   766  	// n, err := unix.Select(
   767  	// 	int(nfds),
   768  	// 	(*unix.FdSet)(unsafe.Pointer(readfds)),
   769  	// 	(*unix.FdSet)(unsafe.Pointer(writefds)),
   770  	// 	(*unix.FdSet)(unsafe.Pointer(exceptfds)),
   771  	// 	(*unix.Timeval)(unsafe.Pointer(timeout)),
   772  	// )
   773  	// if err != nil {
   774  	// 	t.setErrno(err)
   775  	// 	return -1
   776  	// }
   777  
   778  	// return int32(n)
   779  }
   780  
   781  // int mkfifo(const char *pathname, mode_t mode);
   782  func Xmkfifo(t *TLS, pathname uintptr, mode types.Mode_t) int32 {
   783  	panic(todo(""))
   784  	// 	if err := unix.Mkfifo(GoString(pathname), mode); err != nil {
   785  	// 		t.setErrno(err)
   786  	// 		return -1
   787  	// 	}
   788  	//
   789  	// 	return 0
   790  }
   791  
   792  // mode_t umask(mode_t mask);
   793  func Xumask(t *TLS, mask types.Mode_t) types.Mode_t {
   794  	panic(todo(""))
   795  	// 	n, _, _ := unix.Syscall(unix.SYS_UMASK, uintptr(mask), 0, 0)
   796  	// 	return types.Mode_t(n)
   797  }
   798  
   799  // int execvp(const char *file, char *const argv[]);
   800  func Xexecvp(t *TLS, file, argv uintptr) int32 {
   801  	panic(todo(""))
   802  	// 	if _, _, err := unix.Syscall(unix.SYS_EXECVE, file, argv, Environ()); err != 0 {
   803  	// 		t.setErrno(err)
   804  	// 		return -1
   805  	// 	}
   806  	//
   807  	// 	return 0
   808  }
   809  
   810  // pid_t waitpid(pid_t pid, int *wstatus, int options);
   811  func Xwaitpid(t *TLS, pid types.Pid_t, wstatus uintptr, optname int32) types.Pid_t {
   812  	panic(todo(""))
   813  	// 	n, _, err := unix.Syscall6(unix.SYS_WAIT4, uintptr(pid), wstatus, uintptr(optname), 0, 0, 0)
   814  	// 	if err != 0 {
   815  	// 		t.setErrno(err)
   816  	// 		return -1
   817  	// 	}
   818  	//
   819  	// 	return types.Pid_t(n)
   820  }
   821  
   822  // int uname(struct utsname *buf);
   823  func Xuname(t *TLS, buf uintptr) int32 {
   824  	panic(todo(""))
   825  	// 	if _, _, err := unix.Syscall(unix.SYS_UNAME, buf, 0, 0); err != 0 {
   826  	// 		t.setErrno(err)
   827  	// 		return -1
   828  	// 	}
   829  	//
   830  	// 	return 0
   831  }
   832  
   833  // int getrlimit(int resource, struct rlimit *rlim);
   834  func Xgetrlimit(t *TLS, resource int32, rlim uintptr) int32 {
   835  	return Xgetrlimit64(t, resource, rlim)
   836  }
   837  
   838  // int setrlimit(int resource, const struct rlimit *rlim);
   839  func Xsetrlimit(t *TLS, resource int32, rlim uintptr) int32 {
   840  	return Xsetrlimit64(t, resource, rlim)
   841  }
   842  
   843  // int setrlimit(int resource, const struct rlimit *rlim);
   844  func Xsetrlimit64(t *TLS, resource int32, rlim uintptr) int32 {
   845  	panic(todo(""))
   846  	// 	if _, _, err := unix.Syscall(unix.SYS_SETRLIMIT, uintptr(resource), uintptr(rlim), 0); err != 0 {
   847  	// 		t.setErrno(err)
   848  	// 		return -1
   849  	// 	}
   850  	//
   851  	// 	return 0
   852  }
   853  
   854  // // uid_t getuid(void);
   855  // func Xgetuid(t *TLS) types.Uid_t {
   856  // 	return types.Uid_t(os.Getuid())
   857  // }
   858  
   859  // pid_t getpid(void);
   860  func Xgetpid(t *TLS) int32 {
   861  	return int32(os.Getpid())
   862  }
   863  
   864  // int system(const char *command);
   865  func Xsystem(t *TLS, command uintptr) int32 {
   866  	s := GoString(command)
   867  	if command == 0 {
   868  		panic(todo(""))
   869  	}
   870  
   871  	cmd := exec.Command("sh", "-c", s)
   872  	cmd.Stdout = os.Stdout
   873  	cmd.Stderr = os.Stderr
   874  	err := cmd.Run()
   875  	if err != nil {
   876  		ps := err.(*exec.ExitError)
   877  		return int32(ps.ExitCode())
   878  	}
   879  
   880  	return 0
   881  }
   882  
   883  // var staticGetpwuid pwd.Passwd
   884  //
   885  // func init() {
   886  // 	atExit = append(atExit, func() { closePasswd(&staticGetpwuid) })
   887  // }
   888  //
   889  // func closePasswd(p *pwd.Passwd) {
   890  // 	Xfree(nil, p.Fpw_name)
   891  // 	Xfree(nil, p.Fpw_passwd)
   892  // 	Xfree(nil, p.Fpw_gecos)
   893  // 	Xfree(nil, p.Fpw_dir)
   894  // 	Xfree(nil, p.Fpw_shell)
   895  // 	*p = pwd.Passwd{}
   896  // }
   897  
   898  // struct passwd *getpwuid(uid_t uid);
   899  func Xgetpwuid(t *TLS, uid uint32) uintptr {
   900  	panic(todo(""))
   901  	// 	f, err := os.Open("/etc/passwd")
   902  	// 	if err != nil {
   903  	// 		panic(todo("", err))
   904  	// 	}
   905  	//
   906  	// 	defer f.Close()
   907  	//
   908  	// 	sid := strconv.Itoa(int(uid))
   909  	// 	sc := bufio.NewScanner(f)
   910  	// 	for sc.Scan() {
   911  	// 		// eg. "root:x:0:0:root:/root:/bin/bash"
   912  	// 		a := strings.Split(sc.Text(), ":")
   913  	// 		if len(a) < 7 {
   914  	// 			panic(todo(""))
   915  	// 		}
   916  	//
   917  	// 		if a[2] == sid {
   918  	// 			uid, err := strconv.Atoi(a[2])
   919  	// 			if err != nil {
   920  	// 				panic(todo(""))
   921  	// 			}
   922  	//
   923  	// 			gid, err := strconv.Atoi(a[3])
   924  	// 			if err != nil {
   925  	// 				panic(todo(""))
   926  	// 			}
   927  	//
   928  	// 			closePasswd(&staticGetpwuid)
   929  	// 			gecos := a[4]
   930  	// 			if strings.Contains(gecos, ",") {
   931  	// 				a := strings.Split(gecos, ",")
   932  	// 				gecos = a[0]
   933  	// 			}
   934  	// 			initPasswd(t, &staticGetpwuid, a[0], a[1], uint32(uid), uint32(gid), gecos, a[5], a[6])
   935  	// 			return uintptr(unsafe.Pointer(&staticGetpwuid))
   936  	// 		}
   937  	// 	}
   938  	//
   939  	// 	if sc.Err() != nil {
   940  	// 		panic(todo(""))
   941  	// 	}
   942  	//
   943  	// 	return 0
   944  }
   945  
   946  // func initPasswd(t *TLS, p *pwd.Passwd, name, pwd string, uid, gid uint32, gecos, dir, shell string) {
   947  // 	p.Fpw_name = cString(t, name)
   948  // 	p.Fpw_passwd = cString(t, pwd)
   949  // 	p.Fpw_uid = uid
   950  // 	p.Fpw_gid = gid
   951  // 	p.Fpw_gecos = cString(t, gecos)
   952  // 	p.Fpw_dir = cString(t, dir)
   953  // 	p.Fpw_shell = cString(t, shell)
   954  // }
   955  
   956  // int setvbuf(FILE *stream, char *buf, int mode, size_t size);
   957  func Xsetvbuf(t *TLS, stream, buf uintptr, mode int32, size types.Size_t) int32 {
   958  	return 0 //TODO
   959  }
   960  
   961  // int raise(int sig);
   962  func Xraise(t *TLS, sig int32) int32 {
   963  	panic(todo(""))
   964  }
   965  
   966  // int backtrace(void **buffer, int size);
   967  func Xbacktrace(t *TLS, buf uintptr, size int32) int32 {
   968  	panic(todo(""))
   969  }
   970  
   971  // void backtrace_symbols_fd(void *const *buffer, int size, int fd);
   972  func Xbacktrace_symbols_fd(t *TLS, buffer uintptr, size, fd int32) {
   973  	panic(todo(""))
   974  }
   975  
   976  // int fileno(FILE *stream);
   977  func Xfileno(t *TLS, stream uintptr) int32 {
   978  	if stream == 0 {
   979  		t.setErrno(errno.EBADF)
   980  		return -1
   981  	}
   982  
   983  	f, ok := winGetObject(stream).(*file)
   984  	if !ok {
   985  		t.setErrno(errno.EBADF)
   986  		return -1
   987  	}
   988  	return f._fd
   989  }
   990  
   991  // var staticGetpwnam pwd.Passwd
   992  //
   993  // func init() {
   994  // 	atExit = append(atExit, func() { closePasswd(&staticGetpwnam) })
   995  // }
   996  //
   997  // // struct passwd *getpwnam(const char *name);
   998  // func Xgetpwnam(t *TLS, name uintptr) uintptr {
   999  // 	f, err := os.Open("/etc/passwd")
  1000  // 	if err != nil {
  1001  // 		panic(todo("", err))
  1002  // 	}
  1003  //
  1004  // 	defer f.Close()
  1005  //
  1006  // 	sname := GoString(name)
  1007  // 	sc := bufio.NewScanner(f)
  1008  // 	for sc.Scan() {
  1009  // 		// eg. "root:x:0:0:root:/root:/bin/bash"
  1010  // 		a := strings.Split(sc.Text(), ":")
  1011  // 		if len(a) < 7 {
  1012  // 			panic(todo(""))
  1013  // 		}
  1014  //
  1015  // 		if a[0] == sname {
  1016  // 			uid, err := strconv.Atoi(a[2])
  1017  // 			if err != nil {
  1018  // 				panic(todo(""))
  1019  // 			}
  1020  //
  1021  // 			gid, err := strconv.Atoi(a[3])
  1022  // 			if err != nil {
  1023  // 				panic(todo(""))
  1024  // 			}
  1025  //
  1026  // 			closePasswd(&staticGetpwnam)
  1027  // 			gecos := a[4]
  1028  // 			if strings.Contains(gecos, ",") {
  1029  // 				a := strings.Split(gecos, ",")
  1030  // 				gecos = a[0]
  1031  // 			}
  1032  // 			initPasswd(t, &staticGetpwnam, a[0], a[1], uint32(uid), uint32(gid), gecos, a[5], a[6])
  1033  // 			return uintptr(unsafe.Pointer(&staticGetpwnam))
  1034  // 		}
  1035  // 	}
  1036  //
  1037  // 	if sc.Err() != nil {
  1038  // 		panic(todo(""))
  1039  // 	}
  1040  //
  1041  // 	return 0
  1042  // }
  1043  //
  1044  // var staticGetgrnam grp.Group
  1045  //
  1046  // func init() {
  1047  // 	atExit = append(atExit, func() { closeGroup(&staticGetgrnam) })
  1048  // }
  1049  //
  1050  // // struct group *getgrnam(const char *name);
  1051  // func Xgetgrnam(t *TLS, name uintptr) uintptr {
  1052  // 	f, err := os.Open("/etc/group")
  1053  // 	if err != nil {
  1054  // 		panic(todo(""))
  1055  // 	}
  1056  //
  1057  // 	defer f.Close()
  1058  //
  1059  // 	sname := GoString(name)
  1060  // 	sc := bufio.NewScanner(f)
  1061  // 	for sc.Scan() {
  1062  // 		// eg. "root:x:0:"
  1063  // 		a := strings.Split(sc.Text(), ":")
  1064  // 		if len(a) < 4 {
  1065  // 			panic(todo(""))
  1066  // 		}
  1067  //
  1068  // 		if a[0] == sname {
  1069  // 			closeGroup(&staticGetgrnam)
  1070  // 			gid, err := strconv.Atoi(a[2])
  1071  // 			if err != nil {
  1072  // 				panic(todo(""))
  1073  // 			}
  1074  //
  1075  // 			var names []string
  1076  // 			if a[3] != "" {
  1077  // 				names = strings.Split(a[3], ",")
  1078  // 			}
  1079  // 			initGroup(t, &staticGetgrnam, a[0], a[1], uint32(gid), names)
  1080  // 			return uintptr(unsafe.Pointer(&staticGetgrnam))
  1081  // 		}
  1082  // 	}
  1083  //
  1084  // 	if sc.Err() != nil {
  1085  // 		panic(todo(""))
  1086  // 	}
  1087  //
  1088  // 	return 0
  1089  // }
  1090  //
  1091  // func closeGroup(p *grp.Group) {
  1092  // 	Xfree(nil, p.Fgr_name)
  1093  // 	Xfree(nil, p.Fgr_passwd)
  1094  // 	if p.Fgr_mem != 0 {
  1095  // 		panic(todo(""))
  1096  // 	}
  1097  //
  1098  // 	*p = grp.Group{}
  1099  // }
  1100  //
  1101  // func initGroup(t *TLS, p *grp.Group, name, pwd string, gid uint32, names []string) {
  1102  // 	p.Fgr_name = cString(t, name)
  1103  // 	p.Fgr_passwd = cString(t, pwd)
  1104  // 	p.Fgr_gid = gid
  1105  // 	p.Fgr_mem = 0
  1106  // 	if len(names) != 0 {
  1107  // 		panic(todo("%q %q %v %q %v", name, pwd, gid, names, len(names)))
  1108  // 	}
  1109  // }
  1110  //
  1111  // func init() {
  1112  // 	atExit = append(atExit, func() { closeGroup(&staticGetgrgid) })
  1113  // }
  1114  //
  1115  // var staticGetgrgid grp.Group
  1116  //
  1117  // // struct group *getgrgid(gid_t gid);
  1118  // func Xgetgrgid(t *TLS, gid uint32) uintptr {
  1119  // 	f, err := os.Open("/etc/group")
  1120  // 	if err != nil {
  1121  // 		panic(todo(""))
  1122  // 	}
  1123  //
  1124  // 	defer f.Close()
  1125  //
  1126  // 	sid := strconv.Itoa(int(gid))
  1127  // 	sc := bufio.NewScanner(f)
  1128  // 	for sc.Scan() {
  1129  // 		// eg. "root:x:0:"
  1130  // 		a := strings.Split(sc.Text(), ":")
  1131  // 		if len(a) < 4 {
  1132  // 			panic(todo(""))
  1133  // 		}
  1134  //
  1135  // 		if a[2] == sid {
  1136  // 			closeGroup(&staticGetgrgid)
  1137  // 			var names []string
  1138  // 			if a[3] != "" {
  1139  // 				names = strings.Split(a[3], ",")
  1140  // 			}
  1141  // 			initGroup(t, &staticGetgrgid, a[0], a[1], gid, names)
  1142  // 			return uintptr(unsafe.Pointer(&staticGetgrgid))
  1143  // 		}
  1144  // 	}
  1145  //
  1146  // 	if sc.Err() != nil {
  1147  // 		panic(todo(""))
  1148  // 	}
  1149  //
  1150  // 	return 0
  1151  // }
  1152  
  1153  // int mkstemps(char *template, int suffixlen);
  1154  func Xmkstemps(t *TLS, template uintptr, suffixlen int32) int32 {
  1155  	return Xmkstemps64(t, template, suffixlen)
  1156  }
  1157  
  1158  // int mkstemps(char *template, int suffixlen);
  1159  func Xmkstemps64(t *TLS, template uintptr, suffixlen int32) int32 {
  1160  	panic(todo(""))
  1161  	// 	len := uintptr(Xstrlen(t, template))
  1162  	// 	x := template + uintptr(len-6) - uintptr(suffixlen)
  1163  	// 	for i := uintptr(0); i < 6; i++ {
  1164  	// 		if *(*byte)(unsafe.Pointer(x + i)) != 'X' {
  1165  	// 			t.setErrno(errno.EINVAL)
  1166  	// 			return -1
  1167  	// 		}
  1168  	// 	}
  1169  	//
  1170  	// 	fd, err := tempFile(template, x)
  1171  	// 	if err != 0 {
  1172  	// 		t.setErrno(err)
  1173  	// 		return -1
  1174  	// 	}
  1175  	//
  1176  	// 	return int32(fd)
  1177  }
  1178  
  1179  // int mkstemp(char *template);
  1180  func Xmkstemp64(t *TLS, template uintptr) int32 {
  1181  	return Xmkstemps64(t, template, 0)
  1182  }
  1183  
  1184  // func newFtsent(t *TLS, info int, path string, stat *unix.Stat_t, err syscall.Errno) (r *fts.FTSENT) {
  1185  // 	var statp uintptr
  1186  // 	if stat != nil {
  1187  // 		statp = Xmalloc(t, types.Size_t(unsafe.Sizeof(unix.Stat_t{})))
  1188  // 		if statp == 0 {
  1189  // 			panic("OOM")
  1190  // 		}
  1191  //
  1192  // 		*(*unix.Stat_t)(unsafe.Pointer(statp)) = *stat
  1193  // 	}
  1194  // 	csp := CString(path)
  1195  // 	if csp == 0 {
  1196  // 		panic("OOM")
  1197  // 	}
  1198  //
  1199  // 	return &fts.FTSENT{
  1200  // 		Ffts_info:    uint16(info),
  1201  // 		Ffts_path:    csp,
  1202  // 		Ffts_pathlen: uint16(len(path)),
  1203  // 		Ffts_statp:   statp,
  1204  // 		Ffts_errno:   int32(err),
  1205  // 	}
  1206  // }
  1207  //
  1208  // func newCFtsent(t *TLS, info int, path string, stat *unix.Stat_t, err syscall.Errno) uintptr {
  1209  // 	p := Xcalloc(t, types.Size_t(unsafe.Sizeof(fts.FTSENT{})))
  1210  // 	if p == 0 {
  1211  // 		panic("OOM")
  1212  // 	}
  1213  //
  1214  // 	*(*fts.FTSENT)(unsafe.Pointer(p)) = *newFtsent(t, info, path, stat, err)
  1215  // 	return p
  1216  // }
  1217  //
  1218  // func ftsentClose(t *TLS, p uintptr) {
  1219  // 	Xfree(t, (*fts.FTSENT)(unsafe.Pointer(p)).Ffts_path)
  1220  // 	Xfree(t, (*fts.FTSENT)(unsafe.Pointer(p)).Ffts_statp)
  1221  // }
  1222  
  1223  type ftstream struct {
  1224  	s []uintptr
  1225  	x int
  1226  }
  1227  
  1228  // func (f *ftstream) close(t *TLS) {
  1229  // 	for _, p := range f.s {
  1230  // 		ftsentClose(t, p)
  1231  // 		Xfree(t, p)
  1232  // 	}
  1233  // 	*f = ftstream{}
  1234  // }
  1235  //
  1236  // // FTS *fts_open(char * const *path_argv, int options, int (*compar)(const FTSENT **, const FTSENT **));
  1237  // func Xfts_open(t *TLS, path_argv uintptr, options int32, compar uintptr) uintptr {
  1238  // 	return Xfts64_open(t, path_argv, options, compar)
  1239  // }
  1240  
  1241  // FTS *fts_open(char * const *path_argv, int options, int (*compar)(const FTSENT **, const FTSENT **));
  1242  func Xfts64_open(t *TLS, path_argv uintptr, options int32, compar uintptr) uintptr {
  1243  	panic(todo(""))
  1244  	// 	f := &ftstream{}
  1245  	//
  1246  	// 	var walk func(string)
  1247  	// 	walk = func(path string) {
  1248  	// 		var fi os.FileInfo
  1249  	// 		var err error
  1250  	// 		switch {
  1251  	// 		case options&fts.FTS_LOGICAL != 0:
  1252  	// 			fi, err = os.Stat(path)
  1253  	// 		case options&fts.FTS_PHYSICAL != 0:
  1254  	// 			fi, err = os.Lstat(path)
  1255  	// 		default:
  1256  	// 			panic(todo(""))
  1257  	// 		}
  1258  	//
  1259  	// 		if err != nil {
  1260  	// 			panic(todo(""))
  1261  	// 		}
  1262  	//
  1263  	// 		var statp *unix.Stat_t
  1264  	// 		if options&fts.FTS_NOSTAT == 0 {
  1265  	// 			var stat unix.Stat_t
  1266  	// 			switch {
  1267  	// 			case options&fts.FTS_LOGICAL != 0:
  1268  	// 				if err := unix.Stat(path, &stat); err != nil {
  1269  	// 					panic(todo(""))
  1270  	// 				}
  1271  	// 			case options&fts.FTS_PHYSICAL != 0:
  1272  	// 				if err := unix.Lstat(path, &stat); err != nil {
  1273  	// 					panic(todo(""))
  1274  	// 				}
  1275  	// 			default:
  1276  	// 				panic(todo(""))
  1277  	// 			}
  1278  	//
  1279  	// 			statp = &stat
  1280  	// 		}
  1281  	//
  1282  	// 	out:
  1283  	// 		switch {
  1284  	// 		case fi.IsDir():
  1285  	// 			f.s = append(f.s, newCFtsent(t, fts.FTS_D, path, statp, 0))
  1286  	// 			g, err := os.Open(path)
  1287  	// 			switch x := err.(type) {
  1288  	// 			case nil:
  1289  	// 				// ok
  1290  	// 			case *os.PathError:
  1291  	// 				f.s = append(f.s, newCFtsent(t, fts.FTS_DNR, path, statp, errno.EACCES))
  1292  	// 				break out
  1293  	// 			default:
  1294  	// 				panic(todo("%q: %v %T", path, x, x))
  1295  	// 			}
  1296  	//
  1297  	// 			names, err := g.Readdirnames(-1)
  1298  	// 			g.Close()
  1299  	// 			if err != nil {
  1300  	// 				panic(todo(""))
  1301  	// 			}
  1302  	//
  1303  	// 			for _, name := range names {
  1304  	// 				walk(path + "/" + name)
  1305  	// 				if f == nil {
  1306  	// 					break out
  1307  	// 				}
  1308  	// 			}
  1309  	//
  1310  	// 			f.s = append(f.s, newCFtsent(t, fts.FTS_DP, path, statp, 0))
  1311  	// 		default:
  1312  	// 			info := fts.FTS_F
  1313  	// 			if fi.Mode()&os.ModeSymlink != 0 {
  1314  	// 				info = fts.FTS_SL
  1315  	// 			}
  1316  	// 			switch {
  1317  	// 			case statp != nil:
  1318  	// 				f.s = append(f.s, newCFtsent(t, info, path, statp, 0))
  1319  	// 			case options&fts.FTS_NOSTAT != 0:
  1320  	// 				f.s = append(f.s, newCFtsent(t, fts.FTS_NSOK, path, nil, 0))
  1321  	// 			default:
  1322  	// 				panic(todo(""))
  1323  	// 			}
  1324  	// 		}
  1325  	// 	}
  1326  	//
  1327  	// 	for {
  1328  	// 		p := *(*uintptr)(unsafe.Pointer(path_argv))
  1329  	// 		if p == 0 {
  1330  	// 			if f == nil {
  1331  	// 				return 0
  1332  	// 			}
  1333  	//
  1334  	// 			if compar != 0 {
  1335  	// 				panic(todo(""))
  1336  	// 			}
  1337  	//
  1338  	// 			return addObject(f)
  1339  	// 		}
  1340  	//
  1341  	// 		walk(GoString(p))
  1342  	// 		path_argv += unsafe.Sizeof(uintptr(0))
  1343  	// 	}
  1344  }
  1345  
  1346  // FTSENT *fts_read(FTS *ftsp);
  1347  func Xfts_read(t *TLS, ftsp uintptr) uintptr {
  1348  	return Xfts64_read(t, ftsp)
  1349  }
  1350  
  1351  // FTSENT *fts_read(FTS *ftsp);
  1352  func Xfts64_read(t *TLS, ftsp uintptr) uintptr {
  1353  	panic(todo(""))
  1354  	// 	f := winGetObject(ftsp).(*ftstream)
  1355  	// 	if f.x == len(f.s) {
  1356  	// 		t.setErrno(0)
  1357  	// 		return 0
  1358  	// 	}
  1359  	//
  1360  	// 	r := f.s[f.x]
  1361  	// 	if e := (*fts.FTSENT)(unsafe.Pointer(r)).Ffts_errno; e != 0 {
  1362  	// 		t.setErrno(e)
  1363  	// 	}
  1364  	// 	f.x++
  1365  	// 	return r
  1366  }
  1367  
  1368  // int fts_close(FTS *ftsp);
  1369  func Xfts_close(t *TLS, ftsp uintptr) int32 {
  1370  	return Xfts64_close(t, ftsp)
  1371  }
  1372  
  1373  // int fts_close(FTS *ftsp);
  1374  func Xfts64_close(t *TLS, ftsp uintptr) int32 {
  1375  	panic(todo(""))
  1376  	// 	winGetObject(ftsp).(*ftstream).close(t)
  1377  	// 	removeObject(ftsp)
  1378  	// 	return 0
  1379  }
  1380  
  1381  // void tzset (void);
  1382  func Xtzset(t *TLS) {
  1383  	//TODO
  1384  }
  1385  
  1386  var strerrorBuf [256]byte
  1387  
  1388  // char *strerror(int errnum);
  1389  func Xstrerror(t *TLS, errnum int32) uintptr {
  1390  	copy((*RawMem)(unsafe.Pointer(&strerrorBuf[0]))[:len(strerrorBuf):len(strerrorBuf)], fmt.Sprintf("errno %d\x00", errnum))
  1391  	return uintptr(unsafe.Pointer(&strerrorBuf[0]))
  1392  }
  1393  
  1394  // void *dlopen(const char *filename, int flags);
  1395  func Xdlopen(t *TLS, filename uintptr, flags int32) uintptr {
  1396  	panic(todo(""))
  1397  }
  1398  
  1399  // char *dlerror(void);
  1400  func Xdlerror(t *TLS) uintptr {
  1401  	panic(todo(""))
  1402  }
  1403  
  1404  // int dlclose(void *handle);
  1405  func Xdlclose(t *TLS, handle uintptr) int32 {
  1406  	panic(todo(""))
  1407  }
  1408  
  1409  // void *dlsym(void *handle, const char *symbol);
  1410  func Xdlsym(t *TLS, handle, symbol uintptr) uintptr {
  1411  	panic(todo(""))
  1412  }
  1413  
  1414  // void perror(const char *s);
  1415  func Xperror(t *TLS, s uintptr) {
  1416  	panic(todo(""))
  1417  }
  1418  
  1419  // int pclose(FILE *stream);
  1420  func Xpclose(t *TLS, stream uintptr) int32 {
  1421  	panic(todo(""))
  1422  }
  1423  
  1424  var gai_strerrorBuf [100]byte
  1425  
  1426  // const char *gai_strerror(int errcode);
  1427  func Xgai_strerror(t *TLS, errcode int32) uintptr {
  1428  	copy(gai_strerrorBuf[:], fmt.Sprintf("gai error %d\x00", errcode))
  1429  	return uintptr(unsafe.Pointer(&gai_strerrorBuf))
  1430  }
  1431  
  1432  // int tcgetattr(int fd, struct termios *termios_p);
  1433  func Xtcgetattr(t *TLS, fd int32, termios_p uintptr) int32 {
  1434  	panic(todo(""))
  1435  }
  1436  
  1437  // int tcsetattr(int fd, int optional_actions, const struct termios *termios_p);
  1438  func Xtcsetattr(t *TLS, fd, optional_actions int32, termios_p uintptr) int32 {
  1439  	panic(todo(""))
  1440  }
  1441  
  1442  // // speed_t cfgetospeed(const struct termios *termios_p);
  1443  // func Xcfgetospeed(t *TLS, termios_p uintptr) termios.Speed_t {
  1444  // 	panic(todo(""))
  1445  // }
  1446  
  1447  // int cfsetospeed(struct termios *termios_p, speed_t speed);
  1448  func Xcfsetospeed(t *TLS, termios_p uintptr, speed uint32) int32 {
  1449  	panic(todo(""))
  1450  }
  1451  
  1452  // int cfsetispeed(struct termios *termios_p, speed_t speed);
  1453  func Xcfsetispeed(t *TLS, termios_p uintptr, speed uint32) int32 {
  1454  	panic(todo(""))
  1455  }
  1456  
  1457  // pid_t fork(void);
  1458  func Xfork(t *TLS) int32 {
  1459  	t.setErrno(errno.ENOSYS)
  1460  	return -1
  1461  }
  1462  
  1463  // char *setlocale(int category, const char *locale);
  1464  func Xsetlocale(t *TLS, category int32, locale uintptr) uintptr {
  1465  	return 0 //TODO
  1466  }
  1467  
  1468  // // char *nl_langinfo(nl_item item);
  1469  // func Xnl_langinfo(t *TLS, item langinfo.Nl_item) uintptr {
  1470  // 	panic(todo(""))
  1471  // }
  1472  
  1473  // FILE *popen(const char *command, const char *type);
  1474  func Xpopen(t *TLS, command, type1 uintptr) uintptr {
  1475  	panic(todo(""))
  1476  }
  1477  
  1478  // char *realpath(const char *path, char *resolved_path);
  1479  func Xrealpath(t *TLS, path, resolved_path uintptr) uintptr {
  1480  	s, err := filepath.EvalSymlinks(GoString(path))
  1481  	if err != nil {
  1482  		if os.IsNotExist(err) {
  1483  			if dmesgs {
  1484  				dmesg("%v: %q: %v", origin(1), GoString(path), err)
  1485  			}
  1486  			t.setErrno(errno.ENOENT)
  1487  			return 0
  1488  		}
  1489  
  1490  		panic(todo("", err))
  1491  	}
  1492  
  1493  	if resolved_path == 0 {
  1494  		panic(todo(""))
  1495  	}
  1496  
  1497  	if len(s) >= limits.PATH_MAX {
  1498  		s = s[:limits.PATH_MAX-1]
  1499  	}
  1500  
  1501  	copy((*RawMem)(unsafe.Pointer(resolved_path))[:len(s):len(s)], s)
  1502  	(*RawMem)(unsafe.Pointer(resolved_path))[len(s)] = 0
  1503  	return resolved_path
  1504  }
  1505  
  1506  // struct tm *gmtime_r(const time_t *timep, struct tm *result);
  1507  func Xgmtime_r(t *TLS, timep, result uintptr) uintptr {
  1508  	panic(todo(""))
  1509  }
  1510  
  1511  // // char *inet_ntoa(struct in_addr in);
  1512  // func Xinet_ntoa(t *TLS, in1 in.In_addr) uintptr {
  1513  // 	panic(todo(""))
  1514  // }
  1515  
  1516  // func X__ccgo_in6addr_anyp(t *TLS) uintptr {
  1517  // 	return uintptr(unsafe.Pointer(&in6_addr_any))
  1518  // }
  1519  
  1520  func Xabort(t *TLS) {
  1521  	panic(todo(""))
  1522  	// 	if dmesgs {
  1523  	// 		dmesg("%v:\n%s", origin(1), debug.Stack())
  1524  	// 	}
  1525  	// 	p := Xmalloc(t, types.Size_t(unsafe.Sizeof(signal.Sigaction{})))
  1526  	// 	if p == 0 {
  1527  	//		panic("OOM")
  1528  	//	}
  1529  	//
  1530  	// 	*(*signal.Sigaction)(unsafe.Pointer(p)) = signal.Sigaction{
  1531  	// 		F__sigaction_handler: struct{ Fsa_handler signal.X__sighandler_t }{Fsa_handler: signal.SIG_DFL},
  1532  	// 	}
  1533  	// 	Xsigaction(t, signal.SIGABRT, p, 0)
  1534  	// 	Xfree(t, p)
  1535  	// 	unix.Kill(unix.Getpid(), syscall.Signal(signal.SIGABRT))
  1536  	// 	panic(todo("unrechable"))
  1537  }
  1538  
  1539  // int fflush(FILE *stream);
  1540  func Xfflush(t *TLS, stream uintptr) int32 {
  1541  	f, ok := winGetObject(stream).(*file)
  1542  	if !ok {
  1543  		t.setErrno(errno.EBADF)
  1544  		return -1
  1545  	}
  1546  	err := syscall.FlushFileBuffers(f.Handle)
  1547  	if err != nil {
  1548  		t.setErrno(err)
  1549  		return -1
  1550  	}
  1551  	return 0
  1552  }
  1553  
  1554  // size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
  1555  func Xfread(t *TLS, ptr uintptr, size, nmemb types.Size_t, stream uintptr) types.Size_t {
  1556  	f, ok := winGetObject(stream).(*file)
  1557  	if !ok {
  1558  		t.setErrno(errno.EBADF)
  1559  		return 0
  1560  	}
  1561  
  1562  	var sz = size * nmemb
  1563  	var obuf = ((*RawMem)(unsafe.Pointer(ptr)))[:sz]
  1564  	n, err := syscall.Read(f.Handle, obuf)
  1565  	if err != nil {
  1566  		f.setErr()
  1567  		return 0
  1568  	}
  1569  
  1570  	if dmesgs {
  1571  		// dmesg("%v: %d %#x x %#x: %#x\n%s", origin(1), file(stream).fd(), size, nmemb, types.Size_t(m)/size, hex.Dump(GoBytes(ptr, int(m))))
  1572  		dmesg("%v: %d %#x x %#x: %#x\n%s", origin(1), f._fd, size, nmemb, types.Size_t(n)/size)
  1573  	}
  1574  
  1575  	return types.Size_t(n) / size
  1576  
  1577  }
  1578  
  1579  // size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  1580  func Xfwrite(t *TLS, ptr uintptr, size, nmemb types.Size_t, stream uintptr) types.Size_t {
  1581  	if ptr == 0 || size == 0 {
  1582  		return 0
  1583  	}
  1584  
  1585  	f, ok := winGetObject(stream).(*file)
  1586  	if !ok {
  1587  		t.setErrno(errno.EBADF)
  1588  		return 0
  1589  	}
  1590  
  1591  	var sz = size * nmemb
  1592  	var obuf = ((*RawMem)(unsafe.Pointer(ptr)))[:sz]
  1593  	n, err := syscall.Write(f.Handle, obuf)
  1594  	if err != nil {
  1595  		f.setErr()
  1596  		return 0
  1597  	}
  1598  
  1599  	if dmesgs {
  1600  		// 		// dmesg("%v: %d %#x x %#x: %#x\n%s", origin(1), file(stream).fd(), size, nmemb, types.Size_t(m)/size, hex.Dump(GoBytes(ptr, int(m))))
  1601  		dmesg("%v: %d %#x x %#x: %#x\n%s", origin(1), f._fd, size, nmemb, types.Size_t(n)/size)
  1602  	}
  1603  	return types.Size_t(n) / size
  1604  }
  1605  
  1606  // int fclose(FILE *stream);
  1607  func Xfclose(t *TLS, stream uintptr) int32 {
  1608  	f, ok := winGetObject(stream).(*file)
  1609  	if !ok {
  1610  		t.setErrno(errno.EBADF)
  1611  		return -1
  1612  	}
  1613  	return f.close(t)
  1614  }
  1615  
  1616  // int fputc(int c, FILE *stream);
  1617  func Xfputc(t *TLS, c int32, stream uintptr) int32 {
  1618  	f, ok := winGetObject(stream).(*file)
  1619  	if !ok {
  1620  		t.setErrno(errno.EBADF)
  1621  		return -1
  1622  	}
  1623  	if _, err := fwrite(f._fd, []byte{byte(c)}); err != nil {
  1624  		return -1
  1625  	}
  1626  	return int32(byte(c))
  1627  }
  1628  
  1629  // int fseek(FILE *stream, long offset, int whence);
  1630  func Xfseek(t *TLS, stream uintptr, offset long, whence int32) int32 {
  1631  	f, ok := winGetObject(stream).(*file)
  1632  	if !ok {
  1633  		t.setErrno(errno.EBADF)
  1634  		return -1
  1635  	}
  1636  	if n := Xlseek(t, f._fd, types.Off_t(offset), whence); n < 0 {
  1637  		if dmesgs {
  1638  			dmesg("%v: fd %v, off %#x, whence %v: %v", origin(1), f._fd, offset, whenceStr(whence), n)
  1639  		}
  1640  		f.setErr()
  1641  		return -1
  1642  	}
  1643  
  1644  	if dmesgs {
  1645  		dmesg("%v: fd %v, off %#x, whence %v: ok", origin(1), f._fd, offset, whenceStr(whence))
  1646  	}
  1647  	return 0
  1648  }
  1649  
  1650  // long ftell(FILE *stream);
  1651  func Xftell(t *TLS, stream uintptr) long {
  1652  	f, ok := winGetObject(stream).(*file)
  1653  	if !ok {
  1654  		t.setErrno(errno.EBADF)
  1655  		return -1
  1656  	}
  1657  
  1658  	n := Xlseek(t, f._fd, 0, syscall.FILE_CURRENT)
  1659  	if n < 0 {
  1660  		f.setErr()
  1661  		return -1
  1662  	}
  1663  
  1664  	if dmesgs {
  1665  		dmesg("%v: fd %v, n %#x: ok %#x", origin(1), f._fd, n, long(n))
  1666  	}
  1667  	return long(n)
  1668  }
  1669  
  1670  // int ferror(FILE *stream);
  1671  func Xferror(t *TLS, stream uintptr) int32 {
  1672  	f, ok := winGetObject(stream).(*file)
  1673  	if !ok {
  1674  		t.setErrno(errno.EBADF)
  1675  		return -1
  1676  	}
  1677  
  1678  	return Bool32(f.err())
  1679  }
  1680  
  1681  // int getc(FILE *stream);
  1682  func Xfgetc(t *TLS, stream uintptr) int32 {
  1683  	f, ok := winGetObject(stream).(*file)
  1684  	if !ok {
  1685  		t.setErrno(errno.EBADF)
  1686  		return stdio.EOF
  1687  	}
  1688  
  1689  	var buf [1]byte
  1690  	if n, _ := syscall.Read(f.Handle, buf[:]); n != 0 {
  1691  		return int32(buf[0])
  1692  	}
  1693  
  1694  	return stdio.EOF
  1695  }
  1696  
  1697  // int ungetc(int c, FILE *stream);
  1698  func Xungetc(t *TLS, c int32, stream uintptr) int32 {
  1699  	panic(todo(""))
  1700  }
  1701  
  1702  // int fscanf(FILE *stream, const char *format, ...);
  1703  func Xfscanf(t *TLS, stream, format, va uintptr) int32 {
  1704  	panic(todo(""))
  1705  }
  1706  
  1707  // int fputs(const char *s, FILE *stream);
  1708  func Xfputs(t *TLS, s, stream uintptr) int32 {
  1709  	f, ok := winGetObject(stream).(*file)
  1710  	if !ok {
  1711  		t.setErrno(errno.EBADF)
  1712  		return -1
  1713  	}
  1714  	gS := GoString(s)
  1715  	if _, err := fwrite(f._fd, []byte(gS)); err != nil {
  1716  		return -1
  1717  	}
  1718  	return 0
  1719  }
  1720  
  1721  // var getservbynameStaticResult netdb.Servent
  1722  //
  1723  // // struct servent *getservbyname(const char *name, const char *proto);
  1724  // func Xgetservbyname(t *TLS, name, proto uintptr) uintptr {
  1725  // 	var protoent *gonetdb.Protoent
  1726  // 	if proto != 0 {
  1727  // 		protoent = gonetdb.GetProtoByName(GoString(proto))
  1728  // 	}
  1729  // 	servent := gonetdb.GetServByName(GoString(name), protoent)
  1730  // 	if servent == nil {
  1731  // 		if dmesgs {
  1732  // 			dmesg("%q %q: nil (protoent %+v)", GoString(name), GoString(proto), protoent)
  1733  // 		}
  1734  // 		return 0
  1735  // 	}
  1736  //
  1737  // 	Xfree(t, (*netdb.Servent)(unsafe.Pointer(&getservbynameStaticResult)).Fs_name)
  1738  // 	if v := (*netdb.Servent)(unsafe.Pointer(&getservbynameStaticResult)).Fs_aliases; v != 0 {
  1739  // 		for {
  1740  // 			p := *(*uintptr)(unsafe.Pointer(v))
  1741  // 			if p == 0 {
  1742  // 				break
  1743  // 			}
  1744  //
  1745  // 			Xfree(t, p)
  1746  // 			v += unsafe.Sizeof(uintptr(0))
  1747  // 		}
  1748  // 		Xfree(t, v)
  1749  // 	}
  1750  // 	Xfree(t, (*netdb.Servent)(unsafe.Pointer(&getservbynameStaticResult)).Fs_proto)
  1751  // 	cname, err := CString(servent.Name)
  1752  // 	if err != nil {
  1753  // 		getservbynameStaticResult = netdb.Servent{}
  1754  // 		return 0
  1755  // 	}
  1756  //
  1757  // 	var protoname uintptr
  1758  // 	if protoent != nil {
  1759  // 		if protoname, err = CString(protoent.Name); err != nil {
  1760  // 			Xfree(t, cname)
  1761  // 			getservbynameStaticResult = netdb.Servent{}
  1762  // 			return 0
  1763  // 		}
  1764  // 	}
  1765  // 	var a []uintptr
  1766  // 	for _, v := range servent.Aliases {
  1767  // 		cs, err := CString(v)
  1768  // 		if err != nil {
  1769  // 			for _, v := range a {
  1770  // 				Xfree(t, v)
  1771  // 			}
  1772  // 			return 0
  1773  // 		}
  1774  //
  1775  // 		a = append(a, cs)
  1776  // 	}
  1777  // 	v := Xcalloc(t, types.Size_t(len(a)+1), types.Size_t(unsafe.Sizeof(uintptr(0))))
  1778  // 	if v == 0 {
  1779  // 		Xfree(t, cname)
  1780  // 		Xfree(t, protoname)
  1781  // 		for _, v := range a {
  1782  // 			Xfree(t, v)
  1783  // 		}
  1784  // 		getservbynameStaticResult = netdb.Servent{}
  1785  // 		return 0
  1786  // 	}
  1787  // 	for _, p := range a {
  1788  // 		*(*uintptr)(unsafe.Pointer(v)) = p
  1789  // 		v += unsafe.Sizeof(uintptr(0))
  1790  // 	}
  1791  //
  1792  // 	getservbynameStaticResult = netdb.Servent{
  1793  // 		Fs_name:    cname,
  1794  // 		Fs_aliases: v,
  1795  // 		Fs_port:    int32(servent.Port),
  1796  // 		Fs_proto:   protoname,
  1797  // 	}
  1798  // 	return uintptr(unsafe.Pointer(&getservbynameStaticResult))
  1799  // }
  1800  
  1801  // func Xreaddir64(t *TLS, dir uintptr) uintptr {
  1802  // 	return Xreaddir(t, dir)
  1803  // }
  1804  
  1805  // func fcntlCmdStr(cmd int32) string {
  1806  // 	switch cmd {
  1807  // 	case fcntl.F_GETOWN:
  1808  // 		return "F_GETOWN"
  1809  // 	case fcntl.F_SETLK:
  1810  // 		return "F_SETLK"
  1811  // 	case fcntl.F_GETLK:
  1812  // 		return "F_GETLK"
  1813  // 	case fcntl.F_SETFD:
  1814  // 		return "F_SETFD"
  1815  // 	case fcntl.F_GETFD:
  1816  // 		return "F_GETFD"
  1817  // 	default:
  1818  // 		return fmt.Sprintf("cmd(%d)", cmd)
  1819  // 	}
  1820  // }
  1821  
  1822  // _CRTIMP extern int *__cdecl _errno(void); // /usr/share/mingw-w64/include/errno.h:17:
  1823  func X_errno(t *TLS) uintptr {
  1824  	return t.errnop
  1825  }
  1826  
  1827  // int vfscanf(FILE * restrict stream, const char * restrict format, va_list arg);
  1828  func X__ms_vfscanf(t *TLS, stream, format, ap uintptr) int32 {
  1829  	panic(todo(""))
  1830  }
  1831  
  1832  // int vsscanf(const char *str, const char *format, va_list ap);
  1833  func X__ms_vsscanf(t *TLS, str, format, ap uintptr) int32 {
  1834  	panic(todo(""))
  1835  }
  1836  
  1837  // int vscanf(const char *format, va_list ap);
  1838  func X__ms_vscanf(t *TLS, format, ap uintptr) int32 {
  1839  	panic(todo(""))
  1840  }
  1841  
  1842  // int vsnprintf(char *str, size_t size, const char *format, va_list ap);
  1843  func X__ms_vsnprintf(t *TLS, str uintptr, size types.Size_t, format, ap uintptr) int32 {
  1844  	return Xvsnprintf(t, str, size, format, ap)
  1845  }
  1846  
  1847  // int vfwscanf(FILE *stream, const wchar_t *format, va_list argptr;);
  1848  func X__ms_vfwscanf(t *TLS, stream uintptr, format, ap uintptr) int32 {
  1849  	panic(todo(""))
  1850  }
  1851  
  1852  // int vwscanf(const wchar_t * restrict format, va_list arg);
  1853  func X__ms_vwscanf(t *TLS, format, ap uintptr) int32 {
  1854  	panic(todo(""))
  1855  }
  1856  
  1857  // int _vsnwprintf(wchar_t *buffer, size_t count, const wchar_t *format, va_list argptr);
  1858  func X_vsnwprintf(t *TLS, buffer uintptr, count types.Size_t, format, ap uintptr) int32 {
  1859  	panic(todo(""))
  1860  }
  1861  
  1862  // int vswscanf(const wchar_t *buffer, const wchar_t *format, va_list arglist);
  1863  func X__ms_vswscanf(t *TLS, stream uintptr, format, ap uintptr) int32 {
  1864  	panic(todo(""))
  1865  }
  1866  
  1867  // __acrt_iob_func
  1868  func X__acrt_iob_func(t *TLS, fd uint32) uintptr {
  1869  
  1870  	f, ok := fdToFile(int32(fd))
  1871  	if !ok {
  1872  		t.setErrno(EBADF)
  1873  		return 0
  1874  	}
  1875  	return f.t
  1876  }
  1877  
  1878  // BOOL SetEvent(
  1879  //
  1880  //	HANDLE hEvent
  1881  //
  1882  // );
  1883  func XSetEvent(t *TLS, hEvent uintptr) int32 {
  1884  	r0, _, err := syscall.Syscall(procSetEvent.Addr(), 1, hEvent, 0, 0)
  1885  	if r0 == 0 {
  1886  		t.setErrno(err)
  1887  	}
  1888  	return int32(r0)
  1889  }
  1890  
  1891  // int _stricmp(
  1892  //
  1893  //	const char *string1,
  1894  //	const char *string2
  1895  //
  1896  // );
  1897  func X_stricmp(t *TLS, string1, string2 uintptr) int32 {
  1898  	var s1 = strings.ToLower(GoString(string1))
  1899  	var s2 = strings.ToLower(GoString(string2))
  1900  	return int32(strings.Compare(s1, s2))
  1901  }
  1902  
  1903  // BOOL HeapFree(
  1904  //
  1905  //	HANDLE                 hHeap,
  1906  //	DWORD                  dwFlags,
  1907  //	_Frees_ptr_opt_ LPVOID lpMem
  1908  //
  1909  // );
  1910  func XHeapFree(t *TLS, hHeap uintptr, dwFlags uint32, lpMem uintptr) int32 {
  1911  	r0, _, err := syscall.Syscall(procHeapFree.Addr(), 3, hHeap, uintptr(dwFlags), lpMem)
  1912  	if err != 0 {
  1913  		t.setErrno(err)
  1914  	}
  1915  	return int32(r0)
  1916  }
  1917  
  1918  // HANDLE GetProcessHeap();
  1919  func XGetProcessHeap(t *TLS) uintptr {
  1920  	r0, _, err := syscall.Syscall(procGetProcessHeap.Addr(), 0, 0, 0, 0)
  1921  	if r0 == 0 {
  1922  		t.setErrno(err)
  1923  	}
  1924  	return r0
  1925  }
  1926  
  1927  // LPVOID HeapAlloc(
  1928  //
  1929  //	HANDLE hHeap,
  1930  //	DWORD  dwFlags,
  1931  //	SIZE_T dwBytes
  1932  //
  1933  // );
  1934  func XHeapAlloc(t *TLS, hHeap uintptr, dwFlags uint32, dwBytes types.Size_t) uintptr {
  1935  	r0, _, err := syscall.Syscall(procHeapAlloc.Addr(), 3, hHeap, uintptr(dwFlags), uintptr(dwBytes))
  1936  	if r0 == 0 {
  1937  		t.setErrno(err)
  1938  	}
  1939  	return r0
  1940  }
  1941  
  1942  // WCHAR * gai_strerrorW(
  1943  //
  1944  //	int ecode
  1945  //
  1946  // );
  1947  func Xgai_strerrorW(t *TLS, _ ...interface{}) uintptr {
  1948  	panic(todo(""))
  1949  }
  1950  
  1951  // servent * getservbyname(
  1952  //
  1953  //	const char *name,
  1954  //	const char *proto
  1955  //
  1956  // );
  1957  func Xgetservbyname(t *TLS, _ ...interface{}) uintptr {
  1958  	panic(todo(""))
  1959  }
  1960  
  1961  // INT WSAAPI getaddrinfo(
  1962  //
  1963  //	PCSTR           pNodeName,
  1964  //	PCSTR           pServiceName,
  1965  //	const ADDRINFOA *pHints,
  1966  //	PADDRINFOA      *ppResult
  1967  //
  1968  // );
  1969  func XWspiapiGetAddrInfo(t *TLS, _ ...interface{}) int32 {
  1970  	panic(todo(""))
  1971  }
  1972  
  1973  // int wcscmp(
  1974  //
  1975  //	const wchar_t *string1,
  1976  //	const wchar_t *string2
  1977  //
  1978  // );
  1979  func Xwcscmp(t *TLS, string1, string2 uintptr) int32 {
  1980  	var s1 = goWideString(string1)
  1981  	var s2 = goWideString(string2)
  1982  	return int32(strings.Compare(s1, s2))
  1983  }
  1984  
  1985  // BOOL IsDebuggerPresent();
  1986  func XIsDebuggerPresent(t *TLS) int32 {
  1987  	panic(todo(""))
  1988  }
  1989  
  1990  func XExitProcess(t *TLS, _ ...interface{}) int32 {
  1991  	panic(todo(""))
  1992  }
  1993  
  1994  // BOOL GetVersionExW(
  1995  //
  1996  //	LPOSVERSIONINFOW lpVersionInformation
  1997  //
  1998  // );
  1999  func XGetVersionExW(t *TLS, lpVersionInformation uintptr) int32 {
  2000  	r0, _, err := syscall.Syscall(procGetVersionExW.Addr(), 1, lpVersionInformation, 0, 0)
  2001  	if r0 == 0 {
  2002  		t.setErrno(err)
  2003  	}
  2004  	return int32(r0)
  2005  }
  2006  
  2007  // BOOL GetVolumeNameForVolumeMountPointW(
  2008  //
  2009  //	LPCWSTR lpszVolumeMountPoint,
  2010  //	LPWSTR  lpszVolumeName,
  2011  //	DWORD   cchBufferLength
  2012  //
  2013  // );
  2014  func XGetVolumeNameForVolumeMountPointW(t *TLS, _ ...interface{}) int32 {
  2015  	panic(todo(""))
  2016  }
  2017  
  2018  // size_t wcslen(
  2019  //
  2020  //	const wchar_t *str
  2021  //
  2022  // );
  2023  func Xwcslen(t *TLS, str uintptr) types.Size_t {
  2024  	r0, _, _ := syscall.Syscall(procLstrlenW.Addr(), 1, str, 0, 0)
  2025  	return types.Size_t(r0)
  2026  }
  2027  
  2028  // HANDLE WINAPI GetStdHandle(
  2029  //
  2030  //	_In_ DWORD nStdHandle
  2031  //
  2032  // );
  2033  func XGetStdHandle(t *TLS, nStdHandle uint32) uintptr {
  2034  	h, err := syscall.GetStdHandle(int(nStdHandle))
  2035  	if err != nil {
  2036  		panic("no console")
  2037  	}
  2038  	return uintptr(h)
  2039  }
  2040  
  2041  // BOOL CloseHandle(
  2042  //
  2043  //	HANDLE hObject
  2044  //
  2045  // );
  2046  func XCloseHandle(t *TLS, hObject uintptr) int32 {
  2047  	r := syscall.CloseHandle(syscall.Handle(hObject))
  2048  	if r != nil {
  2049  		return errno.EINVAL
  2050  	}
  2051  	return 1
  2052  }
  2053  
  2054  // DWORD GetLastError();
  2055  func XGetLastError(t *TLS) uint32 {
  2056  	var rv = *(*int32)(unsafe.Pointer(t.errnop))
  2057  	return uint32(rv)
  2058  
  2059  	//r1, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0)
  2060  	//return uint32(r1)
  2061  }
  2062  
  2063  // DWORD SetFilePointer(
  2064  //
  2065  //	HANDLE hFile,
  2066  //	LONG   lDistanceToMove,
  2067  //	PLONG  lpDistanceToMoveHigh,
  2068  //	DWORD  dwMoveMethod
  2069  //
  2070  // );
  2071  func XSetFilePointer(t *TLS, hFile uintptr, lDistanceToMove long, lpDistanceToMoveHigh uintptr, dwMoveMethod uint32) uint32 {
  2072  	r0, _, e1 := syscall.Syscall6(procSetFilePointer.Addr(), 4, hFile, uintptr(lDistanceToMove), lpDistanceToMoveHigh, uintptr(dwMoveMethod), 0, 0)
  2073  	var uOff = uint32(r0)
  2074  	if uOff == 0xffffffff {
  2075  		if e1 != 0 {
  2076  			t.setErrno(e1)
  2077  		} else {
  2078  			t.setErrno(errno.EINVAL)
  2079  		}
  2080  	}
  2081  	return uint32(r0)
  2082  }
  2083  
  2084  // BOOL SetEndOfFile(
  2085  //
  2086  //	HANDLE hFile
  2087  //
  2088  // );
  2089  func XSetEndOfFile(t *TLS, hFile uintptr) int32 {
  2090  	err := syscall.SetEndOfFile(syscall.Handle(hFile))
  2091  	if err != nil {
  2092  		t.setErrno(err)
  2093  		return 0
  2094  	}
  2095  	return 1
  2096  }
  2097  
  2098  // BOOL ReadFile(
  2099  //
  2100  //	HANDLE       hFile,
  2101  //	LPVOID       lpBuffer,
  2102  //	DWORD        nNumberOfBytesToRead,
  2103  //	LPDWORD      lpNumberOfBytesRead,
  2104  //	LPOVERLAPPED lpOverlapped
  2105  //
  2106  // );
  2107  func XReadFile(t *TLS, hFile, lpBuffer uintptr, nNumberOfBytesToRead uint32, lpNumberOfBytesRead, lpOverlapped uintptr) int32 {
  2108  	r1, _, e1 := syscall.Syscall6(procReadFile.Addr(), 5,
  2109  		hFile, lpBuffer, uintptr(nNumberOfBytesToRead), uintptr(lpNumberOfBytesRead), uintptr(lpOverlapped), 0)
  2110  	if r1 == 0 {
  2111  		if e1 != 0 {
  2112  			t.setErrno(e1)
  2113  		} else {
  2114  			t.setErrno(errno.EINVAL)
  2115  		}
  2116  		return 0
  2117  	}
  2118  	return int32(r1)
  2119  }
  2120  
  2121  // BOOL WriteFile(
  2122  //
  2123  //	HANDLE       hFile,
  2124  //	LPCVOID      lpBuffer,
  2125  //	DWORD        nNumberOfBytesToWrite,
  2126  //	LPDWORD      lpNumberOfBytesWritten,
  2127  //	LPOVERLAPPED lpOverlapped
  2128  //
  2129  // );
  2130  func XWriteFile(t *TLS, hFile, lpBuffer uintptr, nNumberOfBytesToWrite uint32, lpNumberOfBytesWritten, lpOverlapped uintptr) int32 {
  2131  	r1, _, e1 := syscall.Syscall6(procWriteFile.Addr(), 5,
  2132  		hFile, lpBuffer, uintptr(nNumberOfBytesToWrite), lpNumberOfBytesWritten, lpOverlapped, 0)
  2133  	if r1 == 0 {
  2134  		if e1 != 0 {
  2135  			t.setErrno(e1)
  2136  		} else {
  2137  			t.setErrno(errno.EINVAL)
  2138  		}
  2139  		return 0
  2140  	}
  2141  	return int32(r1)
  2142  }
  2143  
  2144  // DWORD GetFileAttributesW(
  2145  //
  2146  //	LPCWSTR lpFileName
  2147  //
  2148  // );
  2149  func XGetFileAttributesW(t *TLS, lpFileName uintptr) uint32 {
  2150  	attrs, err := syscall.GetFileAttributes((*uint16)(unsafe.Pointer(lpFileName)))
  2151  	if attrs == syscall.INVALID_FILE_ATTRIBUTES {
  2152  		if err != nil {
  2153  			t.setErrno(err)
  2154  		} else {
  2155  			t.setErrno(errno.EINVAL)
  2156  		}
  2157  	}
  2158  	return attrs
  2159  }
  2160  
  2161  // HANDLE CreateFileW(
  2162  //
  2163  //	LPCWSTR               lpFileName,
  2164  //	DWORD                 dwDesiredAccess,
  2165  //	DWORD                 dwShareMode,
  2166  //	LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  2167  //	DWORD                 dwCreationDisposition,
  2168  //	DWORD                 dwFlagsAndAttributes,
  2169  //	HANDLE                hTemplateFile
  2170  //
  2171  // );
  2172  func XCreateFileW(t *TLS, lpFileName uintptr, dwDesiredAccess, dwShareMode uint32, lpSecurityAttributes uintptr, dwCreationDisposition, dwFlagsAndAttributes uint32, hTemplateFile uintptr) uintptr {
  2173  
  2174  	r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, lpFileName, uintptr(dwDesiredAccess), uintptr(dwShareMode), lpSecurityAttributes,
  2175  		uintptr(dwCreationDisposition), uintptr(dwFlagsAndAttributes), hTemplateFile, 0, 0)
  2176  	h := syscall.Handle(r0)
  2177  	if h == syscall.InvalidHandle {
  2178  		if e1 != 0 {
  2179  			t.setErrno(e1)
  2180  		} else {
  2181  			t.setErrno(errno.EINVAL)
  2182  		}
  2183  		return r0
  2184  	}
  2185  	return uintptr(h)
  2186  }
  2187  
  2188  // BOOL DuplicateHandle(
  2189  //
  2190  //	HANDLE   hSourceProcessHandle,
  2191  //	HANDLE   hSourceHandle,
  2192  //	HANDLE   hTargetProcessHandle,
  2193  //	LPHANDLE lpTargetHandle,
  2194  //	DWORD    dwDesiredAccess,
  2195  //	BOOL     bInheritHandle,
  2196  //	DWORD    dwOptions
  2197  //
  2198  // );
  2199  func XDuplicateHandle(t *TLS, hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle uintptr, dwDesiredAccess uint32, bInheritHandle int32, dwOptions uint32) int32 {
  2200  	r0, _, err := syscall.Syscall9(procDuplicateHandle.Addr(), 7, hSourceProcessHandle, hSourceHandle, hTargetProcessHandle,
  2201  		lpTargetHandle, uintptr(dwDesiredAccess), uintptr(bInheritHandle), uintptr(dwOptions), 0, 0)
  2202  	if r0 == 0 {
  2203  		t.setErrno(err)
  2204  	}
  2205  	return int32(r0)
  2206  }
  2207  
  2208  // HANDLE GetCurrentProcess();
  2209  func XGetCurrentProcess(t *TLS) uintptr {
  2210  	r0, _, e1 := syscall.Syscall(procGetCurrentProcess.Addr(), 0, 0, 0, 0)
  2211  	if r0 == 0 {
  2212  		if e1 != 0 {
  2213  			t.setErrno(e1)
  2214  		} else {
  2215  			t.setErrno(errno.EINVAL)
  2216  		}
  2217  	}
  2218  	return r0
  2219  }
  2220  
  2221  // BOOL FlushFileBuffers(
  2222  //
  2223  //	HANDLE hFile
  2224  //
  2225  // );
  2226  func XFlushFileBuffers(t *TLS, hFile uintptr) int32 {
  2227  	err := syscall.FlushFileBuffers(syscall.Handle(hFile))
  2228  	if err != nil {
  2229  		t.setErrno(err)
  2230  		return -1
  2231  	}
  2232  	return 1
  2233  
  2234  }
  2235  
  2236  // DWORD GetFileType(
  2237  //
  2238  //	HANDLE hFile
  2239  //
  2240  // );
  2241  func XGetFileType(t *TLS, hFile uintptr) uint32 {
  2242  	n, err := syscall.GetFileType(syscall.Handle(hFile))
  2243  	if err != nil {
  2244  		t.setErrno(err)
  2245  	}
  2246  	return n
  2247  }
  2248  
  2249  // BOOL WINAPI GetConsoleMode(
  2250  //
  2251  //	_In_  HANDLE  hConsoleHandle,
  2252  //	_Out_ LPDWORD lpMode
  2253  //
  2254  // );
  2255  func XGetConsoleMode(t *TLS, hConsoleHandle, lpMode uintptr) int32 {
  2256  	err := syscall.GetConsoleMode(syscall.Handle(hConsoleHandle), (*uint32)(unsafe.Pointer(lpMode)))
  2257  	if err != nil {
  2258  		t.setErrno(err)
  2259  		return 0
  2260  	}
  2261  	return 1
  2262  }
  2263  
  2264  // BOOL GetCommState(
  2265  //
  2266  //	HANDLE hFile,
  2267  //	LPDCB  lpDCB
  2268  //
  2269  // );
  2270  func XGetCommState(t *TLS, hFile, lpDCB uintptr) int32 {
  2271  	r1, _, err := syscall.Syscall(procGetCommState.Addr(), 2, hFile, lpDCB, 0)
  2272  	if r1 == 0 {
  2273  		t.setErrno(err)
  2274  		return 0
  2275  	}
  2276  	return int32(r1)
  2277  }
  2278  
  2279  // int _wcsnicmp(
  2280  //
  2281  //	const wchar_t *string1,
  2282  //	const wchar_t *string2,
  2283  //	size_t count
  2284  //
  2285  // );
  2286  func X_wcsnicmp(t *TLS, string1, string2 uintptr, count types.Size_t) int32 {
  2287  
  2288  	var s1 = strings.ToLower(goWideString(string1))
  2289  	var l1 = len(s1)
  2290  	var s2 = strings.ToLower(goWideString(string2))
  2291  	var l2 = len(s2)
  2292  
  2293  	// shorter is lesser
  2294  	if l1 < l2 {
  2295  		return -1
  2296  	}
  2297  	if l2 > l1 {
  2298  		return 1
  2299  	}
  2300  
  2301  	// compare at most count
  2302  	var cmpLen = count
  2303  	if types.Size_t(l1) < cmpLen {
  2304  		cmpLen = types.Size_t(l1)
  2305  	}
  2306  	return int32(strings.Compare(s1[:cmpLen], s2[:cmpLen]))
  2307  }
  2308  
  2309  // BOOL WINAPI ReadConsole(
  2310  //
  2311  //	_In_     HANDLE  hConsoleInput,
  2312  //	_Out_    LPVOID  lpBuffer,
  2313  //	_In_     DWORD   nNumberOfCharsToRead,
  2314  //	_Out_    LPDWORD lpNumberOfCharsRead,
  2315  //	_In_opt_ LPVOID  pInputControl
  2316  //
  2317  // );
  2318  func XReadConsoleW(t *TLS, hConsoleInput, lpBuffer uintptr, nNumberOfCharsToRead uint32, lpNumberOfCharsRead, pInputControl uintptr) int32 {
  2319  
  2320  	rv, _, err := syscall.Syscall6(procReadConsoleW.Addr(), 5, hConsoleInput,
  2321  		lpBuffer, uintptr(nNumberOfCharsToRead), lpNumberOfCharsRead, pInputControl, 0)
  2322  	if rv == 0 {
  2323  		t.setErrno(err)
  2324  	}
  2325  
  2326  	return int32(rv)
  2327  }
  2328  
  2329  // BOOL WINAPI WriteConsoleW(
  2330  //
  2331  //	_In_             HANDLE  hConsoleOutput,
  2332  //	_In_       const VOID    *lpBuffer,
  2333  //	_In_             DWORD   nNumberOfCharsToWrite,
  2334  //	_Out_opt_        LPDWORD lpNumberOfCharsWritten,
  2335  //	_Reserved_       LPVOID  lpReserved
  2336  //
  2337  // );
  2338  func XWriteConsoleW(t *TLS, hConsoleOutput, lpBuffer uintptr, nNumberOfCharsToWrite uint32, lpNumberOfCharsWritten, lpReserved uintptr) int32 {
  2339  	rv, _, err := syscall.Syscall6(procWriteConsoleW.Addr(), 5, hConsoleOutput,
  2340  		lpBuffer, uintptr(nNumberOfCharsToWrite), lpNumberOfCharsWritten, lpReserved, 0)
  2341  	if rv == 0 {
  2342  		t.setErrno(err)
  2343  	}
  2344  	return int32(rv)
  2345  }
  2346  
  2347  // DWORD WaitForSingleObject(
  2348  //
  2349  //	HANDLE hHandle,
  2350  //	DWORD  dwMilliseconds
  2351  //
  2352  // );
  2353  func XWaitForSingleObject(t *TLS, hHandle uintptr, dwMilliseconds uint32) uint32 {
  2354  	rv, err := syscall.WaitForSingleObject(syscall.Handle(hHandle), dwMilliseconds)
  2355  	if err != nil {
  2356  		t.setErrno(err)
  2357  	}
  2358  	return rv
  2359  }
  2360  
  2361  // BOOL ResetEvent(
  2362  //
  2363  //	HANDLE hEvent
  2364  //
  2365  // );
  2366  func XResetEvent(t *TLS, hEvent uintptr) int32 {
  2367  	rv, _, err := syscall.Syscall(procResetEvent.Addr(), 1, hEvent, 0, 0)
  2368  	if rv == 0 {
  2369  		t.setErrno(err)
  2370  	}
  2371  	return int32(rv)
  2372  }
  2373  
  2374  // BOOL WINAPI PeekConsoleInput(
  2375  //
  2376  //	_In_  HANDLE        hConsoleInput,
  2377  //	_Out_ PINPUT_RECORD lpBuffer,
  2378  //	_In_  DWORD         nLength,
  2379  //	_Out_ LPDWORD       lpNumberOfEventsRead
  2380  //
  2381  // );
  2382  func XPeekConsoleInputW(t *TLS, hConsoleInput, lpBuffer uintptr, nLength uint32, lpNumberOfEventsRead uintptr) int32 {
  2383  	r0, _, err := syscall.Syscall6(procPeekConsoleInputW.Addr(), 4, hConsoleInput, lpBuffer, uintptr(nLength), lpNumberOfEventsRead, 0, 0)
  2384  	if r0 == 0 {
  2385  		t.setErrno(err)
  2386  	}
  2387  	return int32(r0)
  2388  }
  2389  
  2390  // int WINAPIV wsprintfA(
  2391  //
  2392  //	LPSTR  ,
  2393  //	LPCSTR ,
  2394  //	...
  2395  //
  2396  // );
  2397  func XwsprintfA(t *TLS, buf, format, args uintptr) int32 {
  2398  	return Xsprintf(t, buf, format, args)
  2399  }
  2400  
  2401  // UINT WINAPI GetConsoleCP(void);
  2402  func XGetConsoleCP(t *TLS) uint32 {
  2403  	r0, _, err := syscall.Syscall(procGetConsoleCP.Addr(), 0, 0, 0, 0)
  2404  	if r0 == 0 {
  2405  		t.setErrno(err)
  2406  	}
  2407  	return uint32(r0)
  2408  }
  2409  
  2410  // UINT WINAPI SetConsoleCP(UNIT);
  2411  //func setConsoleCP(cp uint32) uint32 {
  2412  //
  2413  //	r0, _, _ := syscall.Syscall(procSetConsoleCP.Addr(), 1, uintptr(cp), 0, 0)
  2414  //	if r0 == 0 {
  2415  //		panic("setcp failed")
  2416  //	}
  2417  //	return uint32(r0)
  2418  //}
  2419  
  2420  // HANDLE CreateEventW(
  2421  //
  2422  //	LPSECURITY_ATTRIBUTES lpEventAttributes,
  2423  //	BOOL                  bManualReset,
  2424  //	BOOL                  bInitialState,
  2425  //	LPCWSTR               lpName
  2426  //
  2427  // );
  2428  func XCreateEventW(t *TLS, lpEventAttributes uintptr, bManualReset, bInitialState int32, lpName uintptr) uintptr {
  2429  	r0, _, err := syscall.Syscall6(procCreateEventW.Addr(), 4, lpEventAttributes, uintptr(bManualReset),
  2430  		uintptr(bInitialState), lpName, 0, 0)
  2431  	if r0 == 0 {
  2432  		t.setErrno(err)
  2433  	}
  2434  	return r0
  2435  }
  2436  
  2437  type ThreadAdapter struct {
  2438  	token      uintptr
  2439  	tls        *TLS
  2440  	param      uintptr
  2441  	threadFunc func(*TLS, uintptr) uint32
  2442  }
  2443  
  2444  func (ta *ThreadAdapter) run() uintptr {
  2445  	r := ta.threadFunc(ta.tls, ta.param)
  2446  	ta.tls.Close()
  2447  	removeObject(ta.token)
  2448  	return uintptr(r)
  2449  }
  2450  
  2451  func ThreadProc(p uintptr) uintptr {
  2452  	adp, ok := winGetObject(p).(*ThreadAdapter)
  2453  	if !ok {
  2454  		panic("invalid thread")
  2455  	}
  2456  	return adp.run()
  2457  }
  2458  
  2459  // HANDLE CreateThread(
  2460  //
  2461  //	LPSECURITY_ATTRIBUTES   lpThreadAttributes,
  2462  //	SIZE_T                  dwStackSize,
  2463  //	LPTHREAD_START_ROUTINE  lpStartAddress,
  2464  //	__drv_aliasesMem LPVOID lpParameter,
  2465  //	DWORD                   dwCreationFlags,
  2466  //	LPDWORD                 lpThreadId
  2467  //
  2468  // );
  2469  func XCreateThread(t *TLS, lpThreadAttributes uintptr, dwStackSize types.Size_t, lpStartAddress, lpParameter uintptr, dwCreationFlags uint32, lpThreadId uintptr) uintptr {
  2470  	f := (*struct{ f func(*TLS, uintptr) uint32 })(unsafe.Pointer(&struct{ uintptr }{lpStartAddress})).f
  2471  	var tAdp = ThreadAdapter{threadFunc: f, tls: NewTLS(), param: lpParameter}
  2472  	tAdp.token = addObject(&tAdp)
  2473  
  2474  	r0, _, err := syscall.Syscall6(procCreateThread.Addr(), 6, lpThreadAttributes, uintptr(dwStackSize),
  2475  		threadCallback, tAdp.token, uintptr(dwCreationFlags), lpThreadId)
  2476  	if r0 == 0 {
  2477  		t.setErrno(err)
  2478  	}
  2479  	return r0
  2480  }
  2481  
  2482  // BOOL SetThreadPriority(
  2483  //
  2484  //	HANDLE hThread,
  2485  //	int    nPriority
  2486  //
  2487  // );
  2488  func XSetThreadPriority(t *TLS, hThread uintptr, nPriority int32) int32 {
  2489  
  2490  	//r0, _, err := syscall.Syscall(procSetThreadPriority.Addr(), 2, hThread, uintptr(nPriority), 0)
  2491  	//if r0 == 0 {
  2492  	//	t.setErrno(err)
  2493  	//}
  2494  	//return int32(r0)
  2495  	return 1
  2496  }
  2497  
  2498  // BOOL WINAPI SetConsoleMode(
  2499  //
  2500  //	_In_ HANDLE hConsoleHandle,
  2501  //	_In_ DWORD  dwMode
  2502  //
  2503  // );
  2504  func XSetConsoleMode(t *TLS, hConsoleHandle uintptr, dwMode uint32) int32 {
  2505  	rv, _, err := syscall.Syscall(procSetConsoleMode.Addr(), 2, hConsoleHandle, uintptr(dwMode), 0)
  2506  	if rv == 0 {
  2507  		t.setErrno(err)
  2508  	}
  2509  	return int32(rv)
  2510  }
  2511  
  2512  func XPurgeComm(t *TLS, _ ...interface{}) int32 {
  2513  	panic(todo(""))
  2514  }
  2515  
  2516  func XClearCommError(t *TLS, _ ...interface{}) int32 {
  2517  	panic(todo(""))
  2518  }
  2519  
  2520  // void DeleteCriticalSection(
  2521  //
  2522  //	LPCRITICAL_SECTION lpCriticalSection
  2523  //
  2524  // );
  2525  func XDeleteCriticalSection(t *TLS, lpCriticalSection uintptr) {
  2526  	syscall.Syscall(procDeleteCriticalSection.Addr(), 1, lpCriticalSection, 0, 0)
  2527  }
  2528  
  2529  // void EnterCriticalSection(
  2530  //
  2531  //	LPCRITICAL_SECTION lpCriticalSection
  2532  //
  2533  // );
  2534  func XEnterCriticalSection(t *TLS, lpCriticalSection uintptr) {
  2535  	syscall.Syscall(procEnterCriticalSection.Addr(), 1, lpCriticalSection, 0, 0)
  2536  }
  2537  
  2538  // void LeaveCriticalSection(
  2539  //
  2540  //	LPCRITICAL_SECTION lpCriticalSection
  2541  //
  2542  // );
  2543  func XLeaveCriticalSection(t *TLS, lpCriticalSection uintptr) {
  2544  	syscall.Syscall(procLeaveCriticalSection.Addr(), 1, lpCriticalSection, 0, 0)
  2545  }
  2546  
  2547  func XGetOverlappedResult(t *TLS, _ ...interface{}) int32 {
  2548  	panic(todo(""))
  2549  }
  2550  
  2551  func XSetupComm(t *TLS, _ ...interface{}) int32 {
  2552  	panic(todo(""))
  2553  }
  2554  
  2555  func XSetCommTimeouts(t *TLS, _ ...interface{}) int32 {
  2556  	panic(todo(""))
  2557  }
  2558  
  2559  // void InitializeCriticalSection(
  2560  //
  2561  //	LPCRITICAL_SECTION lpCriticalSection
  2562  //
  2563  // );
  2564  func XInitializeCriticalSection(t *TLS, lpCriticalSection uintptr) {
  2565  	// InitializeCriticalSection always succeeds, even in low memory situations.
  2566  	syscall.Syscall(procInitializeCriticalSection.Addr(), 1, lpCriticalSection, 0, 0)
  2567  }
  2568  
  2569  func XBuildCommDCBW(t *TLS, _ ...interface{}) int32 {
  2570  	panic(todo(""))
  2571  }
  2572  
  2573  func XSetCommState(t *TLS, _ ...interface{}) int32 {
  2574  	panic(todo(""))
  2575  }
  2576  
  2577  func X_strnicmp(t *TLS, _ ...interface{}) int32 {
  2578  	panic(todo(""))
  2579  }
  2580  
  2581  func XEscapeCommFunction(t *TLS, _ ...interface{}) int32 {
  2582  	panic(todo(""))
  2583  }
  2584  
  2585  func XGetCommModemStatus(t *TLS, _ ...interface{}) int32 {
  2586  	panic(todo(""))
  2587  }
  2588  
  2589  // BOOL MoveFileW(
  2590  //
  2591  //	LPCWSTR lpExistingFileName,
  2592  //	LPCWSTR lpNewFileName
  2593  //
  2594  // );
  2595  func XMoveFileW(t *TLS, lpExistingFileName, lpNewFileName uintptr) int32 {
  2596  	r0, _, err := syscall.Syscall(procMoveFileW.Addr(), 2, lpExistingFileName, lpNewFileName, 0)
  2597  	if err != 0 {
  2598  		t.setErrno(err)
  2599  	}
  2600  	return int32(r0)
  2601  }
  2602  
  2603  // DWORD GetFullPathNameW(
  2604  //
  2605  //	LPCWSTR lpFileName,
  2606  //	DWORD   nBufferLength,
  2607  //	LPWSTR  lpBuffer,
  2608  //	LPWSTR  *lpFilePart
  2609  //
  2610  // );
  2611  func XGetFullPathNameW(t *TLS, lpFileName uintptr, nBufferLength uint32, lpBuffer, lpFilePart uintptr) uint32 {
  2612  	r0, _, e1 := syscall.Syscall6(procGetFullPathNameW.Addr(), 4, lpFileName, uintptr(nBufferLength), uintptr(lpBuffer), uintptr(lpFilePart), 0, 0)
  2613  	n := uint32(r0)
  2614  	if n == 0 {
  2615  		if e1 != 0 {
  2616  			t.setErrno(e1)
  2617  		} else {
  2618  			t.setErrno(errno.EINVAL)
  2619  		}
  2620  	}
  2621  	return n
  2622  }
  2623  
  2624  // LPWSTR CharLowerW(
  2625  //
  2626  //	LPWSTR lpsz
  2627  //
  2628  // );
  2629  func XCharLowerW(t *TLS, lpsz uintptr) uintptr {
  2630  	panic(todo(""))
  2631  }
  2632  
  2633  // BOOL CreateDirectoryW(
  2634  //
  2635  //	LPCWSTR                lpPathName,
  2636  //	LPSECURITY_ATTRIBUTES lpSecurityAttributes
  2637  //
  2638  // );
  2639  func XCreateDirectoryW(t *TLS, lpPathName, lpSecurityAttributes uintptr) int32 {
  2640  	err := syscall.CreateDirectory((*uint16)(unsafe.Pointer(lpPathName)),
  2641  		(*syscall.SecurityAttributes)(unsafe.Pointer(lpSecurityAttributes)))
  2642  	if err != nil {
  2643  		t.setErrno(err)
  2644  		return 0
  2645  	}
  2646  	return 1
  2647  }
  2648  
  2649  // BOOL SetFileAttributesW(
  2650  //
  2651  //	LPCWSTR lpFileName,
  2652  //	DWORD   dwFileAttributes
  2653  //
  2654  // );
  2655  func XSetFileAttributesW(t *TLS, lpFileName uintptr, dwFileAttributes uint32) int32 {
  2656  	err := syscall.SetFileAttributes((*uint16)(unsafe.Pointer(lpFileName)), dwFileAttributes)
  2657  	if err != nil {
  2658  		t.setErrno(err)
  2659  		return 0
  2660  	}
  2661  	return 1
  2662  }
  2663  
  2664  // UINT GetTempFileNameW(
  2665  //
  2666  //	LPCWSTR lpPathName,
  2667  //	LPCWSTR lpPrefixString,
  2668  //	UINT    uUnique,
  2669  //	LPWSTR  lpTempFileName
  2670  //
  2671  // );
  2672  func XGetTempFileNameW(t *TLS, lpPathName, lpPrefixString uintptr, uUnique uint32, lpTempFileName uintptr) uint32 {
  2673  	r0, _, e1 := syscall.Syscall6(procGetTempFileNameW.Addr(), 4, lpPathName, lpPrefixString, uintptr(uUnique), lpTempFileName, 0, 0)
  2674  	if r0 == 0 {
  2675  		t.setErrno(e1)
  2676  	}
  2677  	return uint32(r0)
  2678  }
  2679  
  2680  // BOOL CopyFileW(
  2681  //
  2682  //	LPCWSTR lpExistingFileName,
  2683  //	LPCWSTR lpNewFileName,
  2684  //	BOOL    bFailIfExists
  2685  //
  2686  // );
  2687  func XCopyFileW(t *TLS, lpExistingFileName, lpNewFileName uintptr, bFailIfExists int32) int32 {
  2688  	r0, _, e1 := syscall.Syscall(procCopyFileW.Addr(), 3, lpExistingFileName, lpNewFileName, uintptr(bFailIfExists))
  2689  	if r0 == 0 {
  2690  		t.setErrno(e1)
  2691  	}
  2692  	return int32(r0)
  2693  }
  2694  
  2695  // BOOL DeleteFileW(
  2696  //
  2697  //	LPCWSTR lpFileName
  2698  //
  2699  // );
  2700  func XDeleteFileW(t *TLS, lpFileName uintptr) int32 {
  2701  	err := syscall.DeleteFile((*uint16)(unsafe.Pointer(lpFileName)))
  2702  	if err != nil {
  2703  		t.setErrno(err)
  2704  		return 0
  2705  	}
  2706  	return 1
  2707  }
  2708  
  2709  // BOOL RemoveDirectoryW(
  2710  //
  2711  //	LPCWSTR lpPathName
  2712  //
  2713  // );
  2714  func XRemoveDirectoryW(t *TLS, lpPathName uintptr) int32 {
  2715  	err := syscall.RemoveDirectory((*uint16)(unsafe.Pointer(lpPathName)))
  2716  	if err != nil {
  2717  		t.setErrno(err)
  2718  		return 0
  2719  	}
  2720  	return 1
  2721  }
  2722  
  2723  // HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData);
  2724  func XFindFirstFileW(t *TLS, lpFileName, lpFindFileData uintptr) uintptr {
  2725  	r0, _, e1 := syscall.Syscall(procFindFirstFileW.Addr(), 2, lpFileName, lpFindFileData, 0)
  2726  	handle := syscall.Handle(r0)
  2727  	if handle == syscall.InvalidHandle {
  2728  		if e1 != 0 {
  2729  			t.setErrno(e1)
  2730  		} else {
  2731  			t.setErrno(errno.EINVAL)
  2732  		}
  2733  	}
  2734  	return r0
  2735  }
  2736  
  2737  // HANDLE FindFirstFileExW(
  2738  //
  2739  //	LPCWSTR            lpFileName,
  2740  //	FINDEX_INFO_LEVELS fInfoLevelId,
  2741  //	LPVOID             lpFindFileData,
  2742  //	FINDEX_SEARCH_OPS  fSearchOp,
  2743  //	LPVOID             lpSearchFilter,
  2744  //	DWORD              dwAdditionalFlags
  2745  //
  2746  // );
  2747  func XFindFirstFileExW(t *TLS, lpFileName uintptr, fInfoLevelId int32, lpFindFileData uintptr, fSearchOp int32, lpSearchFilter uintptr, dwAdditionalFlags uint32) uintptr {
  2748  	r0, _, e1 := syscall.Syscall6(procFindFirstFileExW.Addr(), 6, lpFileName, uintptr(fInfoLevelId), lpFindFileData, uintptr(fSearchOp), lpSearchFilter, uintptr(dwAdditionalFlags))
  2749  	handle := syscall.Handle(r0)
  2750  	if handle == syscall.InvalidHandle {
  2751  		if e1 != 0 {
  2752  			t.setErrno(e1)
  2753  		} else {
  2754  			t.setErrno(errno.EINVAL)
  2755  		}
  2756  	}
  2757  	return r0
  2758  }
  2759  
  2760  // BOOL FindClose(HANDLE hFindFile);
  2761  func XFindClose(t *TLS, hFindFile uintptr) int32 {
  2762  	r0, _, e1 := syscall.Syscall(procFindClose.Addr(), 1, hFindFile, 0, 0)
  2763  	if r0 == 0 {
  2764  		if e1 != 0 {
  2765  			t.setErrno(e1)
  2766  		} else {
  2767  			t.setErrno(errno.EINVAL)
  2768  		}
  2769  	}
  2770  	return int32(r0)
  2771  }
  2772  
  2773  // BOOL FindNextFileW(
  2774  //
  2775  //	HANDLE             hFindFile,
  2776  //	LPWIN32_FIND_DATAW lpFindFileData
  2777  //
  2778  // );
  2779  func XFindNextFileW(t *TLS, hFindFile, lpFindFileData uintptr) int32 {
  2780  	r0, _, e1 := syscall.Syscall(procFindNextFileW.Addr(), 2, hFindFile, lpFindFileData, 0)
  2781  	if r0 == 0 {
  2782  		if e1 != 0 {
  2783  			t.setErrno(e1)
  2784  		} else {
  2785  			t.setErrno(errno.EINVAL)
  2786  		}
  2787  	}
  2788  	return int32(r0)
  2789  }
  2790  
  2791  // DWORD GetLogicalDriveStringsA(
  2792  //
  2793  //	DWORD nBufferLength,
  2794  //	LPSTR lpBuffer
  2795  //
  2796  // );
  2797  func XGetLogicalDriveStringsA(t *TLS, nBufferLength uint32, lpBuffer uintptr) uint32 {
  2798  	r0, _, err := syscall.Syscall(procGetLogicalDriveStringsA.Addr(), 2, uintptr(nBufferLength), lpBuffer, 0)
  2799  	if err != 0 {
  2800  		t.setErrno(err)
  2801  	}
  2802  	return uint32(r0)
  2803  }
  2804  
  2805  // BOOL GetVolumeInformationA(
  2806  //
  2807  //	LPCSTR  lpRootPathName,
  2808  //	LPSTR   lpVolumeNameBuffer,
  2809  //	DWORD   nVolumeNameSize,
  2810  //	LPDWORD lpVolumeSerialNumber,
  2811  //	LPDWORD lpMaximumComponentLength,
  2812  //	LPDWORD lpFileSystemFlags,
  2813  //	LPSTR   lpFileSystemNameBuffer,
  2814  //	DWORD   nFileSystemNameSize
  2815  //
  2816  // );
  2817  func XGetVolumeInformationA(t *TLS, lpRootPathName, lpVolumeNameBuffer uintptr, nVolumeNameSize uint32, lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer uintptr, nFileSystemNameSize uint32) int32 {
  2818  	r0, _, err := syscall.Syscall9(procGetVolumeInformationA.Addr(), 8,
  2819  		lpRootPathName,
  2820  		lpVolumeNameBuffer,
  2821  		uintptr(nVolumeNameSize),
  2822  		lpVolumeSerialNumber,
  2823  		lpMaximumComponentLength,
  2824  		lpFileSystemFlags,
  2825  		lpFileSystemNameBuffer,
  2826  		uintptr(nFileSystemNameSize),
  2827  		0,
  2828  	)
  2829  	if err != 0 {
  2830  		t.setErrno(err)
  2831  	}
  2832  	return int32(r0)
  2833  }
  2834  
  2835  // BOOL CreateHardLinkW(
  2836  //
  2837  //	LPCWSTR               lpFileName,
  2838  //	LPCWSTR               lpExistingFileName,
  2839  //	LPSECURITY_ATTRIBUTES lpSecurityAttributes
  2840  //
  2841  // );
  2842  func XCreateHardLinkW(t *TLS, lpFileName, lpExistingFileName, lpSecurityAttributes uintptr) int32 {
  2843  	r0, _, err := syscall.Syscall(procCreateHardLinkW.Addr(), 1, lpFileName, lpExistingFileName, lpSecurityAttributes)
  2844  	if err != 0 {
  2845  		t.setErrno(err)
  2846  	}
  2847  	return int32(r0)
  2848  }
  2849  
  2850  // BOOL DeviceIoControl(
  2851  //
  2852  //	HANDLE       hDevice,
  2853  //	DWORD        dwIoControlCode,
  2854  //	LPVOID       lpInBuffer,
  2855  //	DWORD        nInBufferSize,
  2856  //	LPVOID       lpOutBuffer,
  2857  //	DWORD        nOutBufferSize,
  2858  //	LPDWORD      lpBytesReturned,
  2859  //	LPOVERLAPPED lpOverlapped
  2860  //
  2861  // );
  2862  func XDeviceIoControl(t *TLS, hDevice uintptr, dwIoControlCode uint32, lpInBuffer uintptr, nInBufferSize uint32, lpOutBuffer uintptr, nOutBufferSize uint32, lpBytesReturned, lpOverlapped uintptr) int32 {
  2863  	r0, _, err := syscall.Syscall9(procDeviceIoControl.Addr(), 8, hDevice, uintptr(dwIoControlCode), lpInBuffer,
  2864  		uintptr(nInBufferSize), lpOutBuffer, uintptr(nOutBufferSize), lpBytesReturned, lpOverlapped, 0)
  2865  	if r0 == 0 {
  2866  		t.setErrno(err)
  2867  	}
  2868  	return int32(r0)
  2869  }
  2870  
  2871  // int wcsncmp(
  2872  //
  2873  //	const wchar_t *string1,
  2874  //	const wchar_t *string2,
  2875  //	size_t count
  2876  //
  2877  // );
  2878  func Xwcsncmp(t *TLS, string1, string2 uintptr, count types.Size_t) int32 {
  2879  	var s1 = goWideString(string1)
  2880  	var l1 = len(s1)
  2881  	var s2 = goWideString(string2)
  2882  	var l2 = len(s2)
  2883  
  2884  	// shorter is lesser
  2885  	if l1 < l2 {
  2886  		return -1
  2887  	}
  2888  	if l2 > l1 {
  2889  		return 1
  2890  	}
  2891  
  2892  	// compare at most count
  2893  	var cmpLen = count
  2894  	if types.Size_t(l1) < cmpLen {
  2895  		cmpLen = types.Size_t(l1)
  2896  	}
  2897  	return int32(strings.Compare(s1[:cmpLen], s2[:cmpLen]))
  2898  }
  2899  
  2900  // int MultiByteToWideChar(
  2901  //
  2902  //	UINT                              CodePage,
  2903  //	DWORD                             dwFlags,
  2904  //	_In_NLS_string_(cbMultiByte)LPCCH lpMultiByteStr,
  2905  //	int                               cbMultiByte,
  2906  //	LPWSTR                            lpWideCharStr,
  2907  //	int                               cchWideChar
  2908  //
  2909  // );
  2910  func XMultiByteToWideChar(t *TLS, CodePage uint32, dwFlags uint32, lpMultiByteStr uintptr, cbMultiByte int32, lpWideCharStr uintptr, cchWideChar int32) int32 {
  2911  	r1, _, _ := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6,
  2912  		uintptr(CodePage), uintptr(dwFlags), uintptr(lpMultiByteStr),
  2913  		uintptr(cbMultiByte), uintptr(lpWideCharStr), uintptr(cchWideChar))
  2914  	return (int32(r1))
  2915  }
  2916  
  2917  // void OutputDebugStringW(
  2918  //
  2919  //	LPCWSTR lpOutputString
  2920  //
  2921  // );
  2922  func XOutputDebugStringW(t *TLS, lpOutputString uintptr) {
  2923  	panic(todo(""))
  2924  }
  2925  
  2926  func XMessageBeep(t *TLS, _ ...interface{}) int32 {
  2927  	panic(todo(""))
  2928  }
  2929  
  2930  //====
  2931  
  2932  // long _InterlockedCompareExchange(
  2933  //
  2934  //	long volatile * Destination,
  2935  //	long Exchange,
  2936  //	long Comparand
  2937  //
  2938  // );
  2939  func X_InterlockedCompareExchange(t *TLS, Destination uintptr, Exchange, Comparand long) long {
  2940  
  2941  	// The function returns the initial value of the Destination parameter.
  2942  	var v = *(*int32)(unsafe.Pointer(Destination))
  2943  	_ = atomic.CompareAndSwapInt32((*int32)(unsafe.Pointer(Destination)), Comparand, Exchange)
  2944  	return long(v)
  2945  }
  2946  
  2947  // int rename(const char *oldpath, const char *newpath);
  2948  func Xrename(t *TLS, oldpath, newpath uintptr) int32 {
  2949  	panic(todo(""))
  2950  }
  2951  
  2952  // BOOL AreFileApisANSI();
  2953  func XAreFileApisANSI(t *TLS) int32 {
  2954  
  2955  	r0, _, _ := syscall.Syscall(procAreFileApisANSI.Addr(), 0, 0, 0, 0)
  2956  	return int32(r0)
  2957  }
  2958  
  2959  // HANDLE CreateFileA(
  2960  //
  2961  //	LPCSTR                lpFileName,
  2962  //	DWORD                 dwDesiredAccess,
  2963  //	DWORD                 dwShareMode,
  2964  //	LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  2965  //	DWORD                 dwCreationDisposition,
  2966  //	DWORD                 dwFlagsAndAttributes,
  2967  //	HANDLE                hTemplateFile
  2968  //
  2969  // );
  2970  func XCreateFileA(t *TLS, lpFileName uintptr, dwDesiredAccess, dwShareMode uint32,
  2971  	lpSecurityAttributes uintptr, dwCreationDisposition, dwFlagsAndAttributes uint32, hTemplateFile uintptr) uintptr {
  2972  
  2973  	r0, _, e1 := syscall.Syscall9(procCreateFileA.Addr(), 7, lpFileName, uintptr(dwDesiredAccess), uintptr(dwShareMode), lpSecurityAttributes,
  2974  		uintptr(dwCreationDisposition), uintptr(dwFlagsAndAttributes), hTemplateFile, 0, 0)
  2975  	h := syscall.Handle(r0)
  2976  	if h == syscall.InvalidHandle {
  2977  		if e1 != 0 {
  2978  			t.setErrno(e1)
  2979  		} else {
  2980  			t.setErrno(errno.EINVAL)
  2981  		}
  2982  		return r0
  2983  	}
  2984  	return uintptr(h)
  2985  
  2986  }
  2987  
  2988  // HANDLE CreateFileMappingA(
  2989  //
  2990  //	HANDLE                hFile,
  2991  //	LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
  2992  //	DWORD                 flProtect,
  2993  //	DWORD                 dwMaximumSizeHigh,
  2994  //	DWORD                 dwMaximumSizeLow,
  2995  //	LPCSTR                lpName
  2996  //
  2997  // );
  2998  func XCreateFileMappingA(t *TLS, hFile, lpFileMappingAttributes uintptr, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow uint32, lpName uintptr) uintptr {
  2999  	panic(todo(""))
  3000  }
  3001  
  3002  // HANDLE CreateFileMappingW(
  3003  //
  3004  //	HANDLE                hFile,
  3005  //	LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
  3006  //	DWORD                 flProtect,
  3007  //	DWORD                 dwMaximumSizeHigh,
  3008  //	DWORD                 dwMaximumSizeLow,
  3009  //	LPCWSTR               lpName
  3010  //
  3011  // );
  3012  func XCreateFileMappingW(t *TLS, hFile, lpFileMappingAttributes uintptr, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow uint32, lpName uintptr) uintptr {
  3013  	h, _, e1 := syscall.Syscall6(procCreateFileMappingW.Addr(), 6, hFile, lpFileMappingAttributes, uintptr(flProtect),
  3014  		uintptr(dwMaximumSizeHigh), uintptr(dwMaximumSizeLow), lpName)
  3015  	if h == 0 {
  3016  		if e1 != 0 {
  3017  			t.setErrno(e1)
  3018  		} else {
  3019  			t.setErrno(errno.EINVAL)
  3020  		}
  3021  	}
  3022  	return h
  3023  }
  3024  
  3025  // HANDLE CreateMutexW(
  3026  //
  3027  //	LPSECURITY_ATTRIBUTES lpMutexAttributes,
  3028  //	BOOL                  bInitialOwner,
  3029  //	LPCWSTR               lpName
  3030  //
  3031  // );
  3032  func XCreateMutexW(t *TLS, lpMutexAttributes uintptr, bInitialOwner int32, lpName uintptr) uintptr {
  3033  	panic(todo(""))
  3034  }
  3035  
  3036  // BOOL DeleteFileA(
  3037  //
  3038  //	LPCSTR lpFileName
  3039  //
  3040  // );
  3041  func XDeleteFileA(t *TLS, lpFileName uintptr) int32 {
  3042  	panic(todo(""))
  3043  }
  3044  
  3045  // DWORD FormatMessageA(
  3046  //
  3047  //	DWORD   dwFlags,
  3048  //	LPCVOID lpSource,
  3049  //	DWORD   dwMessageId,
  3050  //	DWORD   dwLanguageId,
  3051  //	LPSTR   lpBuffer,
  3052  //	DWORD   nSize,
  3053  //	va_list *Arguments
  3054  //
  3055  // );
  3056  func XFormatMessageA(t *TLS, dwFlagsAndAttributes uint32, lpSource uintptr, dwMessageId, dwLanguageId uint32, lpBuffer uintptr, nSize uint32, Arguments uintptr) uint32 {
  3057  	panic(todo(""))
  3058  }
  3059  
  3060  // DWORD FormatMessageW(
  3061  //
  3062  //	DWORD   dwFlags,
  3063  //	LPCVOID lpSource,
  3064  //	DWORD   dwMessageId,
  3065  //	DWORD   dwLanguageId,
  3066  //	LPWSTR  lpBuffer,
  3067  //	DWORD   nSize,
  3068  //	va_list *Arguments
  3069  //
  3070  // );
  3071  func XFormatMessageW(t *TLS, dwFlags uint32, lpSource uintptr, dwMessageId, dwLanguageId uint32, lpBuffer uintptr, nSize uint32, Arguments uintptr) uint32 {
  3072  	r0, _, e1 := syscall.Syscall9(procFormatMessageW.Addr(), 7,
  3073  		uintptr(dwFlags), lpSource, uintptr(dwMessageId), uintptr(dwLanguageId),
  3074  		lpBuffer, uintptr(nSize), Arguments, 0, 0)
  3075  	n := uint32(r0)
  3076  	if n == 0 {
  3077  		if e1 != 0 {
  3078  			t.setErrno(e1)
  3079  		} else {
  3080  			t.setErrno(errno.EINVAL)
  3081  		}
  3082  	}
  3083  	return n
  3084  }
  3085  
  3086  // BOOL FreeLibrary(HMODULE hLibModule);
  3087  func XFreeLibrary(t *TLS, hLibModule uintptr) int32 {
  3088  	panic(todo(""))
  3089  }
  3090  
  3091  // DWORD GetCurrentProcessId();
  3092  func XGetCurrentProcessId(t *TLS) uint32 {
  3093  	r0, _, _ := syscall.Syscall(procGetCurrentProcessId.Addr(), 0, 0, 0, 0)
  3094  	pid := uint32(r0)
  3095  	return pid
  3096  }
  3097  
  3098  // BOOL GetDiskFreeSpaceA(
  3099  //
  3100  //	LPCSTR  lpRootPathName,
  3101  //	LPDWORD lpSectorsPerCluster,
  3102  //	LPDWORD lpBytesPerSector,
  3103  //	LPDWORD lpNumberOfFreeClusters,
  3104  //	LPDWORD lpTotalNumberOfClusters
  3105  //
  3106  // );
  3107  func XGetDiskFreeSpaceA(t *TLS, lpRootPathName, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters uintptr) int32 {
  3108  	panic(todo(""))
  3109  }
  3110  
  3111  // BOOL GetDiskFreeSpaceW(
  3112  //
  3113  //	LPCWSTR lpRootPathName,
  3114  //	LPDWORD lpSectorsPerCluster,
  3115  //	LPDWORD lpBytesPerSector,
  3116  //	LPDWORD lpNumberOfFreeClusters,
  3117  //	LPDWORD lpTotalNumberOfClusters
  3118  //
  3119  // );
  3120  func XGetDiskFreeSpaceW(t *TLS, lpRootPathName, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters uintptr) int32 {
  3121  	panic(todo(""))
  3122  }
  3123  
  3124  // DWORD GetFileAttributesA(
  3125  //
  3126  //	LPCSTR lpFileName
  3127  //
  3128  // );
  3129  func XGetFileAttributesA(t *TLS, lpFileName uintptr) uint32 {
  3130  	r0, _, err := syscall.Syscall(procGetFileAttributesA.Addr(), 1, lpFileName, 0, 0)
  3131  	if err != 0 {
  3132  		t.setErrno(err)
  3133  	}
  3134  	return uint32(r0)
  3135  }
  3136  
  3137  // BOOL GetFileAttributesExW(
  3138  //
  3139  //	LPCWSTR                lpFileName,
  3140  //	GET_FILEEX_INFO_LEVELS fInfoLevelId,
  3141  //	LPVOID                 lpFileInformation
  3142  //
  3143  // );
  3144  func XGetFileAttributesExW(t *TLS, lpFileName uintptr, fInfoLevelId uint32, lpFileInformation uintptr) int32 {
  3145  	r1, _, e1 := syscall.Syscall(procGetFileAttributesExW.Addr(), 3, lpFileName, uintptr(fInfoLevelId), lpFileInformation)
  3146  	if r1 == 0 {
  3147  		if e1 != 0 {
  3148  			t.setErrno(e1)
  3149  		} else {
  3150  			t.setErrno(errno.EINVAL)
  3151  		}
  3152  		return 0
  3153  	}
  3154  	return int32(r1)
  3155  }
  3156  
  3157  // DWORD GetFileSize(
  3158  //
  3159  //	HANDLE  hFile,
  3160  //	LPDWORD lpFileSizeHigh
  3161  //
  3162  // );
  3163  func XGetFileSize(t *TLS, hFile, lpFileSizeHigh uintptr) uint32 {
  3164  	r1, _, e1 := syscall.Syscall(procGetFileSize.Addr(), 2, hFile, lpFileSizeHigh, 0)
  3165  	if r1 == math.MaxUint32 {
  3166  		if lpFileSizeHigh == 0 {
  3167  			// If the function fails and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE.
  3168  			// Note that if the return value is INVALID_FILE_SIZE (0xffffffff),
  3169  			// an application must call GetLastError to determine whether the function has succeeded or failed.
  3170  			t.setErrno(e1)
  3171  			return math.MaxUint32
  3172  		} else {
  3173  			// If the function fails and lpFileSizeHigh is non-NULL, the return value is INVALID_FILE_SIZE
  3174  			// and GetLastError will return a value other than NO_ERROR.
  3175  			t.setErrno(e1)
  3176  			return math.MaxUint32
  3177  		}
  3178  	}
  3179  	return uint32(r1)
  3180  }
  3181  
  3182  // DWORD GetFullPathNameA(
  3183  //
  3184  //	LPCSTR lpFileName,
  3185  //	DWORD  nBufferLength,
  3186  //	LPSTR  lpBuffer,
  3187  //	LPSTR  *lpFilePart
  3188  //
  3189  // );
  3190  func XGetFullPathNameA(t *TLS, lpFileName uintptr, nBufferLength uint32, lpBuffer, lpFilePart uintptr) uint32 {
  3191  	panic(todo(""))
  3192  }
  3193  
  3194  // FARPROC GetProcAddress(HMODULE hModule, LPCSTR  lpProcName);
  3195  func XGetProcAddress(t *TLS, hModule, lpProcName uintptr) uintptr {
  3196  
  3197  	return 0
  3198  
  3199  	//panic(todo(GoString(lpProcName)))
  3200  	//
  3201  	//r0, _, err := syscall.Syscall(procGetProcAddress.Addr(), 2, hModule, lpProcName, 0)
  3202  	//if r0 == 0 {
  3203  	//	t.setErrno(err)
  3204  	//}
  3205  	//return r0
  3206  }
  3207  
  3208  // NTSYSAPI NTSTATUS RtlGetVersion( // ntdll.dll
  3209  //
  3210  //	PRTL_OSVERSIONINFOW lpVersionInformation
  3211  //
  3212  // );
  3213  func XRtlGetVersion(t *TLS, lpVersionInformation uintptr) uintptr {
  3214  	panic(todo(""))
  3215  }
  3216  
  3217  // void GetSystemInfo(
  3218  //
  3219  //	LPSYSTEM_INFO lpSystemInfo
  3220  //
  3221  // );
  3222  func XGetSystemInfo(t *TLS, lpSystemInfo uintptr) {
  3223  	syscall.Syscall(procGetSystemInfo.Addr(), 1, lpSystemInfo, 0, 0)
  3224  }
  3225  
  3226  // void GetSystemTime(LPSYSTEMTIME lpSystemTime);
  3227  func XGetSystemTime(t *TLS, lpSystemTime uintptr) {
  3228  	syscall.Syscall(procGetSystemTime.Addr(), 1, lpSystemTime, 0, 0)
  3229  }
  3230  
  3231  // void GetSystemTimeAsFileTime(
  3232  //
  3233  //	LPFILETIME lpSystemTimeAsFileTime
  3234  //
  3235  // );
  3236  func XGetSystemTimeAsFileTime(t *TLS, lpSystemTimeAsFileTime uintptr) {
  3237  	syscall.Syscall(procGetSystemTimeAsFileTime.Addr(), 1, lpSystemTimeAsFileTime, 0, 0)
  3238  }
  3239  
  3240  // DWORD GetTempPathA(
  3241  //
  3242  //	DWORD nBufferLength,
  3243  //	LPSTR lpBuffer
  3244  //
  3245  // );
  3246  func XGetTempPathA(t *TLS, nBufferLength uint32, lpBuffer uintptr) uint32 {
  3247  	panic(todo(""))
  3248  }
  3249  
  3250  // DWORD GetTempPathW(
  3251  //
  3252  //	DWORD  nBufferLength,
  3253  //	LPWSTR lpBuffer
  3254  //
  3255  // );
  3256  func XGetTempPathW(t *TLS, nBufferLength uint32, lpBuffer uintptr) uint32 {
  3257  	rv, err := syscall.GetTempPath(nBufferLength, (*uint16)(unsafe.Pointer(lpBuffer)))
  3258  	if err != nil {
  3259  		t.setErrno(err)
  3260  	}
  3261  	return rv
  3262  }
  3263  
  3264  // DWORD GetTickCount();
  3265  func XGetTickCount(t *TLS) uint32 {
  3266  	r0, _, _ := syscall.Syscall(procGetTickCount.Addr(), 0, 0, 0, 0)
  3267  	return uint32(r0)
  3268  }
  3269  
  3270  // BOOL GetVersionExA(
  3271  //
  3272  //	LPOSVERSIONINFOA lpVersionInformation
  3273  //
  3274  // );
  3275  func XGetVersionExA(t *TLS, lpVersionInformation uintptr) int32 {
  3276  	r0, _, err := syscall.Syscall(procGetVersionExA.Addr(), 1, lpVersionInformation, 0, 0)
  3277  	if r0 == 0 {
  3278  		t.setErrno(err)
  3279  	}
  3280  	return int32(r0)
  3281  }
  3282  
  3283  // HANDLE HeapCreate(
  3284  //
  3285  //	DWORD  flOptions,
  3286  //	SIZE_T dwInitialSize,
  3287  //	SIZE_T dwMaximumSize
  3288  //
  3289  // );
  3290  func XHeapCreate(t *TLS, flOptions uint32, dwInitialSize, dwMaximumSize types.Size_t) uintptr {
  3291  	panic(todo(""))
  3292  }
  3293  
  3294  // BOOL HeapDestroy(
  3295  //
  3296  //	HANDLE hHeap
  3297  //
  3298  // );
  3299  func XHeapDestroy(t *TLS, hHeap uintptr) int32 {
  3300  	panic(todo(""))
  3301  }
  3302  
  3303  // LPVOID HeapReAlloc(
  3304  //
  3305  //	HANDLE                 hHeap,
  3306  //	DWORD                  dwFlags,
  3307  //	_Frees_ptr_opt_ LPVOID lpMem,
  3308  //	SIZE_T                 dwBytes
  3309  //
  3310  // );
  3311  func XHeapReAlloc(t *TLS, hHeap uintptr, dwFlags uint32, lpMem uintptr, dwBytes types.Size_t) uintptr {
  3312  	panic(todo(""))
  3313  }
  3314  
  3315  // SIZE_T HeapSize(
  3316  //
  3317  //	HANDLE  hHeap,
  3318  //	DWORD   dwFlags,
  3319  //	LPCVOID lpMem
  3320  //
  3321  // );
  3322  func XHeapSize(t *TLS, hHeap uintptr, dwFlags uint32, lpMem uintptr) types.Size_t {
  3323  	panic(todo(""))
  3324  }
  3325  
  3326  // BOOL HeapValidate(
  3327  //
  3328  //	HANDLE  hHeap,
  3329  //	DWORD   dwFlags,
  3330  //	LPCVOID lpMem
  3331  //
  3332  // );
  3333  func XHeapValidate(t *TLS, hHeap uintptr, dwFlags uint32, lpMem uintptr) int32 {
  3334  	panic(todo(""))
  3335  }
  3336  
  3337  // SIZE_T HeapCompact(
  3338  //
  3339  //	HANDLE hHeap,
  3340  //	DWORD  dwFlags
  3341  //
  3342  // );
  3343  func XHeapCompact(t *TLS, hHeap uintptr, dwFlags uint32) types.Size_t {
  3344  	panic(todo(""))
  3345  }
  3346  
  3347  // HMODULE LoadLibraryA(LPCSTR lpLibFileName);
  3348  func XLoadLibraryA(t *TLS, lpLibFileName uintptr) uintptr {
  3349  	panic(todo(""))
  3350  }
  3351  
  3352  // HMODULE LoadLibraryW(
  3353  //
  3354  //	LPCWSTR lpLibFileName
  3355  //
  3356  // );
  3357  func XLoadLibraryW(t *TLS, lpLibFileName uintptr) uintptr {
  3358  	panic(todo(""))
  3359  }
  3360  
  3361  // HLOCAL LocalFree(
  3362  //
  3363  //	HLOCAL hMem
  3364  //
  3365  // );
  3366  func XLocalFree(t *TLS, hMem uintptr) uintptr {
  3367  	h, err := syscall.LocalFree(syscall.Handle(hMem))
  3368  	if h != 0 {
  3369  		if err != nil {
  3370  			t.setErrno(err)
  3371  		} else {
  3372  			t.setErrno(errno.EINVAL)
  3373  		}
  3374  		return uintptr(h)
  3375  	}
  3376  	return 0
  3377  }
  3378  
  3379  // BOOL LockFile(
  3380  //
  3381  //	HANDLE hFile,
  3382  //	DWORD  dwFileOffsetLow,
  3383  //	DWORD  dwFileOffsetHigh,
  3384  //	DWORD  nNumberOfBytesToLockLow,
  3385  //	DWORD  nNumberOfBytesToLockHigh
  3386  //
  3387  // );
  3388  func XLockFile(t *TLS, hFile uintptr, dwFileOffsetLow, dwFileOffsetHigh, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh uint32) int32 {
  3389  
  3390  	r1, _, e1 := syscall.Syscall6(procLockFile.Addr(), 5,
  3391  		hFile, uintptr(dwFileOffsetLow), uintptr(dwFileOffsetHigh), uintptr(nNumberOfBytesToLockLow), uintptr(nNumberOfBytesToLockHigh), 0)
  3392  	if r1 == 0 {
  3393  		if e1 != 0 {
  3394  			t.setErrno(e1)
  3395  		} else {
  3396  			t.setErrno(errno.EINVAL)
  3397  		}
  3398  		return 0
  3399  	}
  3400  	return int32(r1)
  3401  
  3402  }
  3403  
  3404  // BOOL LockFileEx(
  3405  //
  3406  //	HANDLE       hFile,
  3407  //	DWORD        dwFlags,
  3408  //	DWORD        dwReserved,
  3409  //	DWORD        nNumberOfBytesToLockLow,
  3410  //	DWORD        nNumberOfBytesToLockHigh,
  3411  //	LPOVERLAPPED lpOverlapped
  3412  //
  3413  // );
  3414  func XLockFileEx(t *TLS, hFile uintptr, dwFlags, dwReserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh uint32, lpOverlapped uintptr) int32 {
  3415  	r1, _, e1 := syscall.Syscall6(procLockFileEx.Addr(), 6,
  3416  		hFile, uintptr(dwFlags), uintptr(dwReserved), uintptr(nNumberOfBytesToLockLow), uintptr(nNumberOfBytesToLockHigh), lpOverlapped)
  3417  	if r1 == 0 {
  3418  		if e1 != 0 {
  3419  			t.setErrno(e1)
  3420  		} else {
  3421  			t.setErrno(errno.EINVAL)
  3422  		}
  3423  		return 0
  3424  	}
  3425  	return int32(r1)
  3426  }
  3427  
  3428  // LPVOID MapViewOfFile(
  3429  //
  3430  //	HANDLE hFileMappingObject,
  3431  //	DWORD  dwDesiredAccess,
  3432  //	DWORD  dwFileOffsetHigh,
  3433  //	DWORD  dwFileOffsetLow,
  3434  //	SIZE_T dwNumberOfBytesToMap
  3435  //
  3436  // );
  3437  func XMapViewOfFile(t *TLS, hFileMappingObject uintptr, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow uint32, dwNumberOfBytesToMap types.Size_t) uintptr {
  3438  	h, _, e1 := syscall.Syscall6(procMapViewOfFile.Addr(), 5, hFileMappingObject, uintptr(dwDesiredAccess),
  3439  		uintptr(dwFileOffsetHigh), uintptr(dwFileOffsetLow), uintptr(dwNumberOfBytesToMap), 0)
  3440  	if h == 0 {
  3441  		if e1 != 0 {
  3442  			t.setErrno(e1)
  3443  		} else {
  3444  			t.setErrno(errno.EINVAL)
  3445  		}
  3446  	}
  3447  	return h
  3448  }
  3449  
  3450  // BOOL QueryPerformanceCounter(
  3451  //
  3452  //	LARGE_INTEGER *lpPerformanceCount
  3453  //
  3454  // );
  3455  func XQueryPerformanceCounter(t *TLS, lpPerformanceCount uintptr) int32 {
  3456  	r0, _, _ := syscall.Syscall(procQueryPerformanceCounter.Addr(), 1, lpPerformanceCount, 0, 0)
  3457  	return int32(r0)
  3458  }
  3459  
  3460  // void Sleep(
  3461  //
  3462  //	DWORD dwMilliseconds
  3463  //
  3464  // );
  3465  func XSleep(t *TLS, dwMilliseconds uint32) {
  3466  	gotime.Sleep(gotime.Duration(dwMilliseconds) * gotime.Millisecond)
  3467  }
  3468  
  3469  // BOOL SystemTimeToFileTime(const SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime);
  3470  func XSystemTimeToFileTime(t *TLS, lpSystemTime, lpFileTime uintptr) int32 {
  3471  	r0, _, _ := syscall.Syscall(procSystemTimeToFileTime.Addr(), 2, lpSystemTime, lpFileTime, 0)
  3472  	return int32(r0)
  3473  }
  3474  
  3475  // BOOL UnlockFile(
  3476  //
  3477  //	HANDLE hFile,
  3478  //	DWORD  dwFileOffsetLow,
  3479  //	DWORD  dwFileOffsetHigh,
  3480  //	DWORD  nNumberOfBytesToUnlockLow,
  3481  //	DWORD  nNumberOfBytesToUnlockHigh
  3482  //
  3483  // );
  3484  func XUnlockFile(t *TLS, hFile uintptr, dwFileOffsetLow, dwFileOffsetHigh, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh uint32) int32 {
  3485  	r1, _, e1 := syscall.Syscall6(procUnlockFile.Addr(), 5,
  3486  		hFile, uintptr(dwFileOffsetLow), uintptr(dwFileOffsetHigh), uintptr(nNumberOfBytesToUnlockLow), uintptr(nNumberOfBytesToUnlockHigh), 0)
  3487  	if r1 == 0 {
  3488  		if e1 != 0 {
  3489  			t.setErrno(e1)
  3490  		} else {
  3491  			t.setErrno(errno.EINVAL)
  3492  		}
  3493  		return 0
  3494  	}
  3495  	return int32(r1)
  3496  }
  3497  
  3498  // BOOL UnlockFileEx(
  3499  //
  3500  //	HANDLE       hFile,
  3501  //	DWORD        dwReserved,
  3502  //	DWORD        nNumberOfBytesToUnlockLow,
  3503  //	DWORD        nNumberOfBytesToUnlockHigh,
  3504  //	LPOVERLAPPED lpOverlapped
  3505  //
  3506  // );
  3507  func XUnlockFileEx(t *TLS, hFile uintptr, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh uint32, lpOverlapped uintptr) int32 {
  3508  	r1, _, e1 := syscall.Syscall6(procUnlockFileEx.Addr(), 5,
  3509  		hFile, uintptr(dwReserved), uintptr(nNumberOfBytesToUnlockLow), uintptr(nNumberOfBytesToUnlockHigh), lpOverlapped, 0)
  3510  	if r1 == 0 {
  3511  		if e1 != 0 {
  3512  			t.setErrno(e1)
  3513  		} else {
  3514  			t.setErrno(errno.EINVAL)
  3515  		}
  3516  		return 0
  3517  	}
  3518  	return int32(r1)
  3519  }
  3520  
  3521  // BOOL UnmapViewOfFile(
  3522  //
  3523  //	LPCVOID lpBaseAddress
  3524  //
  3525  // );
  3526  func XUnmapViewOfFile(t *TLS, lpBaseAddress uintptr) int32 {
  3527  	err := syscall.UnmapViewOfFile(lpBaseAddress)
  3528  	if err != nil {
  3529  		t.setErrno(err)
  3530  		return 0
  3531  	}
  3532  	return 1
  3533  }
  3534  
  3535  // int WideCharToMultiByte(
  3536  //
  3537  //	UINT                               CodePage,
  3538  //	DWORD                              dwFlags,
  3539  //	_In_NLS_string_(cchWideChar)LPCWCH lpWideCharStr,
  3540  //	int                                cchWideChar,
  3541  //	LPSTR                              lpMultiByteStr,
  3542  //	int                                cbMultiByte,
  3543  //	LPCCH                              lpDefaultChar,
  3544  //	LPBOOL                             lpUsedDefaultChar
  3545  //
  3546  // );
  3547  func XWideCharToMultiByte(t *TLS, CodePage uint32, dwFlags uint32, lpWideCharStr uintptr, cchWideChar int32, lpMultiByteStr uintptr, cbMultiByte int32, lpDefaultChar, lpUsedDefaultChar uintptr) int32 {
  3548  	r1, _, _ := syscall.Syscall9(procWideCharToMultiByte.Addr(), 8,
  3549  		uintptr(CodePage), uintptr(dwFlags), lpWideCharStr,
  3550  		uintptr(cchWideChar), lpMultiByteStr, uintptr(cbMultiByte),
  3551  		lpDefaultChar, lpUsedDefaultChar, 0)
  3552  	return (int32(r1))
  3553  }
  3554  
  3555  // void OutputDebugStringA(
  3556  //
  3557  //	LPCSTR lpOutputString
  3558  //
  3559  // )
  3560  func XOutputDebugStringA(t *TLS, lpOutputString uintptr) {
  3561  	panic(todo(""))
  3562  }
  3563  
  3564  // BOOL FlushViewOfFile(
  3565  //
  3566  //	LPCVOID lpBaseAddress,
  3567  //	SIZE_T  dwNumberOfBytesToFlush
  3568  //
  3569  // );
  3570  func XFlushViewOfFile(t *TLS, lpBaseAddress uintptr, dwNumberOfBytesToFlush types.Size_t) int32 {
  3571  	err := syscall.FlushViewOfFile(lpBaseAddress, uintptr(dwNumberOfBytesToFlush))
  3572  	if err != nil {
  3573  		t.setErrno(err)
  3574  		return 0
  3575  	}
  3576  	return 1
  3577  }
  3578  
  3579  type _ino_t = uint16 /* types.h:43:24 */
  3580  type _dev_t = uint32 /* types.h:51:22 */
  3581  type _stat64 = struct {
  3582  	Fst_dev   _dev_t
  3583  	Fst_ino   _ino_t
  3584  	Fst_mode  uint16
  3585  	Fst_nlink int16
  3586  	Fst_uid   int16
  3587  	Fst_gid   int16
  3588  	_         [2]byte
  3589  	Fst_rdev  _dev_t
  3590  	_         [4]byte
  3591  	Fst_size  int64
  3592  	Fst_atime int64
  3593  	Fst_mtime int64
  3594  	Fst_ctime int64
  3595  } /* _mingw_stat64.h:83:3 */
  3596  
  3597  var (
  3598  	Windows_Tick   int64 = 10000000
  3599  	SecToUnixEpoch int64 = 11644473600
  3600  )
  3601  
  3602  func WindowsTickToUnixSeconds(windowsTicks int64) int64 {
  3603  	return (windowsTicks/Windows_Tick - SecToUnixEpoch)
  3604  }
  3605  
  3606  // int _stat64(const char *path, struct __stat64 *buffer);
  3607  func X_stat64(t *TLS, path, buffer uintptr) int32 {
  3608  
  3609  	var fa syscall.Win32FileAttributeData
  3610  	r1, _, e1 := syscall.Syscall(procGetFileAttributesExA.Addr(), 3, path, syscall.GetFileExInfoStandard, (uintptr)(unsafe.Pointer(&fa)))
  3611  	if r1 == 0 {
  3612  		if e1 != 0 {
  3613  			t.setErrno(e1)
  3614  		} else {
  3615  			t.setErrno(errno.EINVAL)
  3616  		}
  3617  		return -1
  3618  	}
  3619  
  3620  	var bStat64 = (*_stat64)(unsafe.Pointer(buffer))
  3621  	var accessTime = int64(fa.LastAccessTime.HighDateTime)<<32 + int64(fa.LastAccessTime.LowDateTime)
  3622  	bStat64.Fst_atime = WindowsTickToUnixSeconds(accessTime)
  3623  	var modTime = int64(fa.LastWriteTime.HighDateTime)<<32 + int64(fa.LastWriteTime.LowDateTime)
  3624  	bStat64.Fst_mtime = WindowsTickToUnixSeconds(modTime)
  3625  	var crTime = int64(fa.CreationTime.HighDateTime)<<32 + int64(fa.CreationTime.LowDateTime)
  3626  	bStat64.Fst_ctime = WindowsTickToUnixSeconds(crTime)
  3627  	var fSz = int64(fa.FileSizeHigh)<<32 + int64(fa.FileSizeLow)
  3628  	bStat64.Fst_size = fSz
  3629  	bStat64.Fst_mode = WindowsAttrbiutesToStat(fa.FileAttributes)
  3630  
  3631  	return 0
  3632  }
  3633  
  3634  func WindowsAttrbiutesToStat(fa uint32) uint16 {
  3635  	var src_mode = fa & 0xff
  3636  	var st_mode uint16
  3637  	if (src_mode & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 {
  3638  		st_mode = syscall.S_IFDIR
  3639  	} else {
  3640  		st_mode = syscall.S_IFREG
  3641  	}
  3642  
  3643  	if src_mode&syscall.FILE_ATTRIBUTE_READONLY != 0 {
  3644  		st_mode = st_mode | syscall.S_IRUSR
  3645  	} else {
  3646  		st_mode = st_mode | syscall.S_IRUSR | syscall.S_IWUSR
  3647  	}
  3648  	// fill group fields
  3649  	st_mode = st_mode | (st_mode&0x700)>>3
  3650  	st_mode = st_mode | (st_mode&0x700)>>6
  3651  	return st_mode
  3652  }
  3653  
  3654  // int _chsize(
  3655  //
  3656  //	int fd,
  3657  //	long size
  3658  //
  3659  // );
  3660  func X_chsize(t *TLS, fd int32, size long) int32 {
  3661  
  3662  	f, ok := fdToFile(fd)
  3663  	if !ok {
  3664  		t.setErrno(EBADF)
  3665  		return -1
  3666  	}
  3667  
  3668  	err := syscall.Ftruncate(f.Handle, int64(size))
  3669  	if err != nil {
  3670  		t.setErrno(err)
  3671  		return -1
  3672  	}
  3673  
  3674  	return 0
  3675  }
  3676  
  3677  // int _snprintf(char *str, size_t size, const char *format, ...);
  3678  func X_snprintf(t *TLS, str uintptr, size types.Size_t, format, args uintptr) int32 {
  3679  	return Xsnprintf(t, str, size, format, args)
  3680  }
  3681  
  3682  const wErr_ERROR_INSUFFICIENT_BUFFER = 122
  3683  
  3684  func win32FindDataToFileInfo(t *TLS, fdata *stat.X_finddata64i32_t, wfd *syscall.Win32finddata) int32 {
  3685  	// t64 = 64-bit time value
  3686  	var accessTime = int64(wfd.LastAccessTime.HighDateTime)<<32 + int64(wfd.LastAccessTime.LowDateTime)
  3687  	fdata.Ftime_access = WindowsTickToUnixSeconds(accessTime)
  3688  	var modTime = int64(wfd.LastWriteTime.HighDateTime)<<32 + int64(wfd.LastWriteTime.LowDateTime)
  3689  	fdata.Ftime_write = WindowsTickToUnixSeconds(modTime)
  3690  	var crTime = int64(wfd.CreationTime.HighDateTime)<<32 + int64(wfd.CreationTime.LowDateTime)
  3691  	fdata.Ftime_create = WindowsTickToUnixSeconds(crTime)
  3692  	// i32 = 32-bit size
  3693  	fdata.Fsize = wfd.FileSizeLow
  3694  	fdata.Fattrib = wfd.FileAttributes
  3695  
  3696  	var cp = XGetConsoleCP(t)
  3697  	var wcFn = (uintptr)(unsafe.Pointer(&wfd.FileName[0]))
  3698  	var mbcsFn = (uintptr)(unsafe.Pointer(&fdata.Fname[0]))
  3699  	rv := XWideCharToMultiByte(t, cp, 0, wcFn, -1, mbcsFn, 260, 0, 0)
  3700  	if rv == wErr_ERROR_INSUFFICIENT_BUFFER {
  3701  		t.setErrno(errno.ENOMEM)
  3702  		return -1
  3703  	}
  3704  	return 0
  3705  }
  3706  
  3707  // intptr_t _findfirst64i32(
  3708  //
  3709  //	const char *filespec,
  3710  //	struct _finddata64i32_t *fileinfo
  3711  //
  3712  // );
  3713  func X_findfirst64i32(t *TLS, filespec, fileinfo uintptr) types.Intptr_t {
  3714  
  3715  	// Note: this is the 'narrow' character findfirst -- expects output
  3716  	// as mbcs -- conversion below -- via ToFileInfo
  3717  
  3718  	var gsFileSpec = GoString(filespec)
  3719  	namep, err := syscall.UTF16PtrFromString(gsFileSpec)
  3720  	if err != nil {
  3721  		t.setErrno(err)
  3722  		return types.Intptr_t(-1)
  3723  	}
  3724  
  3725  	var fdata = (*stat.X_finddata64i32_t)(unsafe.Pointer(fileinfo))
  3726  	var wfd syscall.Win32finddata
  3727  	h, err := syscall.FindFirstFile((*uint16)(unsafe.Pointer(namep)), &wfd)
  3728  	if err != nil {
  3729  		t.setErrno(err)
  3730  		return types.Intptr_t(-1)
  3731  	}
  3732  	rv := win32FindDataToFileInfo(t, fdata, &wfd)
  3733  	if rv != 0 {
  3734  		if h != 0 {
  3735  			syscall.FindClose(h)
  3736  		}
  3737  		return types.Intptr_t(-1)
  3738  	}
  3739  	return types.Intptr_t(h)
  3740  }
  3741  
  3742  // int _findnext64i32(
  3743  //
  3744  //	intptr_t handle,
  3745  //	struct _finddata64i32_t *fileinfo
  3746  //
  3747  // );
  3748  func X_findnext64i32(t *TLS, handle types.Intptr_t, fileinfo uintptr) int32 {
  3749  
  3750  	var fdata = (*stat.X_finddata64i32_t)(unsafe.Pointer(fileinfo))
  3751  	var wfd syscall.Win32finddata
  3752  
  3753  	err := syscall.FindNextFile(syscall.Handle(handle), &wfd)
  3754  	if err != nil {
  3755  		t.setErrno(err)
  3756  		return -1
  3757  	}
  3758  
  3759  	rv := win32FindDataToFileInfo(t, fdata, &wfd)
  3760  	if rv != 0 {
  3761  		return -1
  3762  	}
  3763  	return 0
  3764  }
  3765  
  3766  // int _findclose(
  3767  //
  3768  //	intptr_t handle
  3769  //
  3770  // );
  3771  func X_findclose(t *TLS, handle types.Intptr_t) int32 {
  3772  
  3773  	err := syscall.FindClose(syscall.Handle(handle))
  3774  	if err != nil {
  3775  		t.setErrno(err)
  3776  		return -1
  3777  	}
  3778  	return 0
  3779  }
  3780  
  3781  // DWORD GetEnvironmentVariableA(
  3782  //
  3783  //	LPCSTR lpName,
  3784  //	LPSTR  lpBuffer,
  3785  //	DWORD  nSize
  3786  //
  3787  // );
  3788  func XGetEnvironmentVariableA(t *TLS, lpName, lpBuffer uintptr, nSize uint32) uint32 {
  3789  	r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableA.Addr(), 3, lpName, lpBuffer, uintptr(nSize))
  3790  	n := uint32(r0)
  3791  	if n == 0 {
  3792  		if e1 != 0 {
  3793  			t.setErrno(e1)
  3794  		} else {
  3795  			t.setErrno(errno.EINVAL)
  3796  		}
  3797  	}
  3798  	return n
  3799  }
  3800  
  3801  // int _fstat64(
  3802  //
  3803  //	int fd,
  3804  //	struct __stat64 *buffer
  3805  //
  3806  // );
  3807  func X_fstat64(t *TLS, fd int32, buffer uintptr) int32 {
  3808  
  3809  	f, ok := fdToFile(fd)
  3810  	if !ok {
  3811  		t.setErrno(EBADF)
  3812  		return -1
  3813  	}
  3814  
  3815  	var d syscall.ByHandleFileInformation
  3816  	err := syscall.GetFileInformationByHandle(f.Handle, &d)
  3817  	if err != nil {
  3818  		t.setErrno(EBADF)
  3819  		return -1
  3820  	}
  3821  
  3822  	var bStat64 = (*_stat64)(unsafe.Pointer(buffer))
  3823  	var accessTime = int64(d.LastAccessTime.HighDateTime)<<32 + int64(d.LastAccessTime.LowDateTime)
  3824  	bStat64.Fst_atime = WindowsTickToUnixSeconds(accessTime)
  3825  	var modTime = int64(d.LastWriteTime.HighDateTime)<<32 + int64(d.LastWriteTime.LowDateTime)
  3826  	bStat64.Fst_mtime = WindowsTickToUnixSeconds(modTime)
  3827  	var crTime = int64(d.CreationTime.HighDateTime)<<32 + int64(d.CreationTime.LowDateTime)
  3828  	bStat64.Fst_ctime = WindowsTickToUnixSeconds(crTime)
  3829  	var fSz = int64(d.FileSizeHigh)<<32 + int64(d.FileSizeLow)
  3830  	bStat64.Fst_size = fSz
  3831  	bStat64.Fst_mode = WindowsAttrbiutesToStat(d.FileAttributes)
  3832  
  3833  	return 0
  3834  }
  3835  
  3836  // HANDLE CreateEventA(
  3837  //
  3838  //	LPSECURITY_ATTRIBUTES lpEventAttributes,
  3839  //	BOOL                  bManualReset,
  3840  //	BOOL                  bInitialState,
  3841  //	LPCSTR                lpName
  3842  //
  3843  // );
  3844  func XCreateEventA(t *TLS, lpEventAttributes uintptr, bManualReset, bInitialState int32, lpName uintptr) uintptr {
  3845  	r0, _, err := syscall.Syscall6(procCreateEventA.Addr(), 4, lpEventAttributes, uintptr(bManualReset),
  3846  		uintptr(bInitialState), lpName, 0, 0)
  3847  	if r0 == 0 {
  3848  		t.setErrno(err)
  3849  	}
  3850  	return r0
  3851  }
  3852  
  3853  // BOOL WINAPI CancelSynchronousIo(
  3854  //
  3855  //	_In_ HANDLE hThread
  3856  //
  3857  // );
  3858  func XCancelSynchronousIo(t *TLS, hThread uintptr) int32 {
  3859  	panic(todo(""))
  3860  }
  3861  
  3862  func X_endthreadex(t *TLS, _ ...interface{}) {
  3863  	// NOOP
  3864  }
  3865  
  3866  // The calling convention for beginthread is cdecl -- but in this
  3867  // case we're just intercepting it and sending it through CreateThread which expects stdcall
  3868  // and gets that via the go callback. This is safe because the thread is calling into go
  3869  // not a cdecl function which would expect the stack setup of cdecl.
  3870  func X_beginthread(t *TLS, procAddr uintptr, stack_sz uint32, args uintptr) int32 {
  3871  	f := (*struct{ f func(*TLS, uintptr) uint32 })(unsafe.Pointer(&struct{ uintptr }{procAddr})).f
  3872  	var tAdp = ThreadAdapter{threadFunc: f, tls: NewTLS(), param: args}
  3873  	tAdp.token = addObject(&tAdp)
  3874  
  3875  	r0, _, err := syscall.Syscall6(procCreateThread.Addr(), 6, 0, uintptr(stack_sz),
  3876  		threadCallback, tAdp.token, 0, 0)
  3877  	if r0 == 0 {
  3878  		t.setErrno(err)
  3879  	}
  3880  	return int32(r0)
  3881  }
  3882  
  3883  // uintptr_t _beginthreadex( // NATIVE CODE
  3884  //
  3885  //	void *security,
  3886  //	unsigned stack_size,
  3887  //	unsigned ( __stdcall *start_address )( void * ),
  3888  //	void *arglist,
  3889  //	unsigned initflag,
  3890  //	unsigned *thrdaddr
  3891  //
  3892  // );
  3893  func X_beginthreadex(t *TLS, _ uintptr, stack_sz uint32, procAddr uintptr, args uintptr, initf uint32, thAddr uintptr) int32 {
  3894  	f := (*struct{ f func(*TLS, uintptr) uint32 })(unsafe.Pointer(&struct{ uintptr }{procAddr})).f
  3895  	var tAdp = ThreadAdapter{threadFunc: f, tls: NewTLS(), param: args}
  3896  	tAdp.token = addObject(&tAdp)
  3897  
  3898  	r0, _, err := syscall.Syscall6(procCreateThread.Addr(), 6, 0, uintptr(stack_sz),
  3899  		threadCallback, tAdp.token, uintptr(initf), thAddr)
  3900  	if r0 == 0 {
  3901  		t.setErrno(err)
  3902  	}
  3903  	return int32(r0)
  3904  }
  3905  
  3906  // DWORD GetCurrentThreadId();
  3907  func XGetCurrentThreadId(t *TLS) uint32 {
  3908  	r0, _, _ := syscall.Syscall(procGetCurrentThreadId.Addr(), 0, 0, 0, 0)
  3909  	return uint32(r0)
  3910  	//return uint32(t.ID)
  3911  }
  3912  
  3913  // BOOL GetExitCodeThread(
  3914  //
  3915  //	HANDLE  hThread,
  3916  //	LPDWORD lpExitCode
  3917  //
  3918  // );
  3919  func XGetExitCodeThread(t *TLS, hThread, lpExitCode uintptr) int32 {
  3920  	r0, _, _ := syscall.Syscall(procGetExitCodeThread.Addr(), 2, hThread, lpExitCode, 0)
  3921  	return int32(r0)
  3922  }
  3923  
  3924  // DWORD WaitForSingleObjectEx(
  3925  //
  3926  //	HANDLE hHandle,
  3927  //	DWORD  dwMilliseconds,
  3928  //	BOOL   bAlertable
  3929  //
  3930  // );
  3931  func XWaitForSingleObjectEx(t *TLS, hHandle uintptr, dwMilliseconds uint32, bAlertable int32) uint32 {
  3932  	rv, _, _ := syscall.Syscall(procWaitForSingleObjectEx.Addr(), 3, hHandle, uintptr(dwMilliseconds), uintptr(bAlertable))
  3933  	return uint32(rv)
  3934  }
  3935  
  3936  // DWORD MsgWaitForMultipleObjectsEx(
  3937  //
  3938  //	DWORD        nCount,
  3939  //	const HANDLE *pHandles,
  3940  //	DWORD        dwMilliseconds,
  3941  //	DWORD        dwWakeMask,
  3942  //	DWORD        dwFlags
  3943  //
  3944  // );
  3945  func XMsgWaitForMultipleObjectsEx(t *TLS, nCount uint32, pHandles uintptr, dwMilliseconds, dwWakeMask, dwFlags uint32) uint32 {
  3946  	r0, _, err := syscall.Syscall6(procMsgWaitForMultipleObjectsEx.Addr(), 5,
  3947  		uintptr(nCount),
  3948  		pHandles,
  3949  		uintptr(dwMilliseconds),
  3950  		uintptr(dwWakeMask),
  3951  		uintptr(dwFlags),
  3952  		0,
  3953  	)
  3954  	if err != 0 {
  3955  		t.setErrno(err)
  3956  	}
  3957  	return uint32(r0)
  3958  }
  3959  
  3960  func XMessageBoxW(t *TLS, _ ...interface{}) int32 {
  3961  	panic(todo(""))
  3962  }
  3963  
  3964  // DWORD GetModuleFileNameW(
  3965  //
  3966  //	HMODULE hModule,
  3967  //	LPWSTR  lpFileName,
  3968  //	DWORD   nSize
  3969  //
  3970  // );
  3971  func XGetModuleFileNameW(t *TLS, hModule, lpFileName uintptr, nSize uint32) uint32 {
  3972  	r0, _, err := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, hModule, lpFileName, uintptr(nSize))
  3973  	if r0 == 0 {
  3974  		t.setErrno(err)
  3975  	}
  3976  	return uint32(r0)
  3977  }
  3978  
  3979  // NET_API_STATUS NET_API_FUNCTION NetGetDCName(
  3980  //
  3981  //	LPCWSTR ServerName,
  3982  //	LPCWSTR DomainName,
  3983  //	LPBYTE  *Buffer
  3984  //
  3985  // );
  3986  func XNetGetDCName(t *TLS, ServerName, DomainName, Buffer uintptr) int32 {
  3987  	r0, _, err := syscall.Syscall(procNetGetDCName.Addr(), 3, ServerName, DomainName, Buffer)
  3988  	if err != 0 {
  3989  		t.setErrno(err)
  3990  	}
  3991  	return int32(r0)
  3992  }
  3993  
  3994  // NET_API_STATUS NET_API_FUNCTION NetUserGetInfo(
  3995  //
  3996  //	LPCWSTR servername,
  3997  //	LPCWSTR username,
  3998  //	DWORD   level,
  3999  //	LPBYTE  *bufptr
  4000  //
  4001  // );
  4002  func XNetUserGetInfo(t *TLS, servername, username uintptr, level uint32, bufptr uintptr) uint32 {
  4003  	r0, _, err := syscall.Syscall6(procNetUserGetInfo.Addr(), 4,
  4004  		servername,
  4005  		username,
  4006  		uintptr(level),
  4007  		bufptr,
  4008  		0,
  4009  		0,
  4010  	)
  4011  	if err != 0 {
  4012  		t.setErrno(err)
  4013  	}
  4014  	return uint32(r0)
  4015  }
  4016  
  4017  func XlstrlenW(t *TLS, _ ...interface{}) int32 {
  4018  	panic(todo(""))
  4019  }
  4020  
  4021  // USERENVAPI BOOL GetProfilesDirectoryW(
  4022  //
  4023  //	[out]     LPWSTR  lpProfileDir,
  4024  //	[in, out] LPDWORD lpcchSize
  4025  //
  4026  // );
  4027  func XGetProfilesDirectoryW(t *TLS, lpProfileDir, lpcchSize uintptr) int32 {
  4028  	r0, _, err := syscall.Syscall(procGetProfilesDirectoryW.Addr(), 2, lpProfileDir, lpcchSize, 0)
  4029  	if err != 0 {
  4030  		t.setErrno(err)
  4031  	}
  4032  	return int32(r0)
  4033  }
  4034  
  4035  func XNetApiBufferFree(t *TLS, _ ...interface{}) int32 {
  4036  	panic(todo(""))
  4037  }
  4038  
  4039  // DWORD GetPrivateProfileStringA(
  4040  //
  4041  //	LPCSTR lpAppName,
  4042  //	LPCSTR lpKeyName,
  4043  //	LPCSTR lpDefault,
  4044  //	LPSTR  lpReturnedString,
  4045  //	DWORD  nSize,
  4046  //	LPCSTR lpFileName
  4047  //
  4048  // );
  4049  func XGetPrivateProfileStringA(t *TLS, lpAppName, lpKeyName, lpDefault, lpReturnedString uintptr, nSize uint32, lpFileName uintptr) uint32 {
  4050  	r0, _, err := syscall.Syscall6(procGetPrivateProfileStringA.Addr(), 4,
  4051  		lpAppName,
  4052  		lpKeyName,
  4053  		lpDefault,
  4054  		lpReturnedString,
  4055  		uintptr(nSize),
  4056  		lpFileName,
  4057  	)
  4058  	if err != 0 {
  4059  		t.setErrno(0x02)
  4060  	}
  4061  	return uint32(r0)
  4062  }
  4063  
  4064  func XGetWindowsDirectoryA(t *TLS, _ ...interface{}) int32 {
  4065  	panic(todo(""))
  4066  }
  4067  
  4068  // BOOL GetFileSecurityW(
  4069  //
  4070  //	LPCSTR               lpFileName,
  4071  //	SECURITY_INFORMATION RequestedInformation,
  4072  //	PSECURITY_DESCRIPTOR pSecurityDescriptor,
  4073  //	DWORD                nLength,
  4074  //	LPDWORD              lpnLengthNeeded
  4075  //
  4076  // );
  4077  func XGetFileSecurityW(t *TLS, lpFileName uintptr, RequestedInformation uint32, pSecurityDescriptor uintptr, nLength uint32, lpnLengthNeeded uintptr) int32 {
  4078  	r0, _, err := syscall.Syscall6(procGetFileSecurityW.Addr(), 5, lpFileName, uintptr(RequestedInformation), pSecurityDescriptor, uintptr(nLength), lpnLengthNeeded, 0)
  4079  	if err != 0 {
  4080  		t.setErrno(err)
  4081  	}
  4082  	return int32(r0)
  4083  }
  4084  
  4085  // BOOL GetSecurityDescriptorOwner(
  4086  //
  4087  //	PSECURITY_DESCRIPTOR pSecurityDescriptor,
  4088  //	PSID                 *pOwner,
  4089  //	LPBOOL               lpbOwnerDefaulted
  4090  //
  4091  // );
  4092  func XGetSecurityDescriptorOwner(t *TLS, pSecurityDescriptor, pOwner, lpbOwnerDefaulted uintptr) int32 {
  4093  	r0, _, err := syscall.Syscall(procGetSecurityDescriptorOwner.Addr(), 3, pSecurityDescriptor, pOwner, lpbOwnerDefaulted)
  4094  	if err != 0 {
  4095  		t.setErrno(err)
  4096  	}
  4097  	return int32(r0)
  4098  
  4099  }
  4100  
  4101  // PSID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority(
  4102  //
  4103  //	PSID pSid
  4104  //
  4105  // );
  4106  func XGetSidIdentifierAuthority(t *TLS, pSid uintptr) uintptr {
  4107  	r0, _, err := syscall.Syscall(procGetSidIdentifierAuthority.Addr(), 1, pSid, 0, 0)
  4108  	if err != 0 {
  4109  		t.setErrno(err)
  4110  	}
  4111  	return r0
  4112  }
  4113  
  4114  // BOOL ImpersonateSelf(
  4115  //
  4116  //	SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
  4117  //
  4118  // );
  4119  func XImpersonateSelf(t *TLS, ImpersonationLevel int32) int32 {
  4120  	r0, _, err := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(ImpersonationLevel), 0, 0)
  4121  	if err != 0 {
  4122  		t.setErrno(err)
  4123  	}
  4124  	return int32(r0)
  4125  }
  4126  
  4127  // BOOL OpenThreadToken(
  4128  //
  4129  //	HANDLE  ThreadHandle,
  4130  //	DWORD   DesiredAccess,
  4131  //	BOOL    OpenAsSelf,
  4132  //	PHANDLE TokenHandle
  4133  //
  4134  // );
  4135  func XOpenThreadToken(t *TLS, ThreadHandle uintptr, DesiredAccess uint32, OpenAsSelf int32, TokenHandle uintptr) int32 {
  4136  	r0, _, err := syscall.Syscall6(procOpenThreadToken.Addr(), 4, ThreadHandle, uintptr(DesiredAccess), uintptr(OpenAsSelf), TokenHandle, 0, 0)
  4137  	if err != 0 {
  4138  		t.setErrno(err)
  4139  	}
  4140  	return int32(r0)
  4141  }
  4142  
  4143  // HANDLE GetCurrentThread();
  4144  func XGetCurrentThread(t *TLS) uintptr {
  4145  	r0, _, err := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0)
  4146  	if err != 0 {
  4147  		t.setErrno(err)
  4148  	}
  4149  	return r0
  4150  }
  4151  
  4152  // BOOL RevertToSelf();
  4153  func XRevertToSelf(t *TLS) int32 {
  4154  	r0, _, err := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0)
  4155  	if err != 0 {
  4156  		t.setErrno(err)
  4157  	}
  4158  	return int32(r0)
  4159  }
  4160  
  4161  // BOOL AccessCheck(
  4162  //
  4163  //	PSECURITY_DESCRIPTOR pSecurityDescriptor,
  4164  //	HANDLE               ClientToken,
  4165  //	DWORD                DesiredAccess,
  4166  //	PGENERIC_MAPPING     GenericMapping,
  4167  //	PPRIVILEGE_SET       PrivilegeSet,
  4168  //	LPDWORD              PrivilegeSetLength,
  4169  //	LPDWORD              GrantedAccess,
  4170  //	LPBOOL               AccessStatus
  4171  //
  4172  // );
  4173  func XAccessCheck(t *TLS, pSecurityDescriptor, ClientToken uintptr, DesiredAccess uint32, GenericMapping, PrivilegeSet, PrivilegeSetLength, GrantedAccess, AccessStatus uintptr) int32 {
  4174  	r0, _, err := syscall.Syscall9(procAccessCheck.Addr(), 8,
  4175  		pSecurityDescriptor,
  4176  		ClientToken,
  4177  		uintptr(DesiredAccess),
  4178  		GenericMapping,
  4179  		PrivilegeSet,
  4180  		PrivilegeSetLength,
  4181  		GrantedAccess,
  4182  		AccessStatus,
  4183  		0,
  4184  	)
  4185  	if err != 0 {
  4186  		t.setErrno(err)
  4187  	}
  4188  	return int32(r0)
  4189  }
  4190  
  4191  // int _wcsicmp(
  4192  //
  4193  //	const wchar_t *string1,
  4194  //	const wchar_t *string2
  4195  //
  4196  // );
  4197  func Xwcsicmp(t *TLS, string1, string2 uintptr) int32 {
  4198  	var s1 = strings.ToLower(goWideString(string1))
  4199  	var s2 = strings.ToLower(goWideString(string2))
  4200  	return int32(strings.Compare(s1, s2))
  4201  }
  4202  
  4203  // BOOL SetCurrentDirectoryW(
  4204  //
  4205  //	LPCTSTR lpPathName
  4206  //
  4207  // );
  4208  func XSetCurrentDirectoryW(t *TLS, lpPathName uintptr) int32 {
  4209  	err := syscall.SetCurrentDirectory((*uint16)(unsafe.Pointer(lpPathName)))
  4210  	if err != nil {
  4211  		t.setErrno(err)
  4212  		return 0
  4213  	}
  4214  	return 1
  4215  }
  4216  
  4217  // DWORD GetCurrentDirectory(
  4218  //
  4219  //	DWORD  nBufferLength,
  4220  //	LPWTSTR lpBuffer
  4221  //
  4222  // );
  4223  func XGetCurrentDirectoryW(t *TLS, nBufferLength uint32, lpBuffer uintptr) uint32 {
  4224  	n, err := syscall.GetCurrentDirectory(nBufferLength, (*uint16)(unsafe.Pointer(lpBuffer)))
  4225  	if err != nil {
  4226  		t.setErrno(err)
  4227  	}
  4228  	return n
  4229  }
  4230  
  4231  // BOOL GetFileInformationByHandle(
  4232  //
  4233  //	HANDLE                       hFile,
  4234  //	LPBY_HANDLE_FILE_INFORMATION lpFileInformation
  4235  //
  4236  // );
  4237  func XGetFileInformationByHandle(t *TLS, hFile, lpFileInformation uintptr) int32 {
  4238  	r1, _, e1 := syscall.Syscall(procGetFileInformationByHandle.Addr(), 2, hFile, lpFileInformation, 0)
  4239  	if r1 == 0 {
  4240  		if e1 != 0 {
  4241  			t.setErrno(e1)
  4242  		} else {
  4243  			t.setErrno(errno.EINVAL)
  4244  		}
  4245  	}
  4246  	return int32(r1)
  4247  }
  4248  
  4249  // BOOL GetVolumeInformationW(
  4250  //
  4251  //	LPCWSTR lpRootPathName,
  4252  //	LPWSTR  lpVolumeNameBuffer,
  4253  //	DWORD   nVolumeNameSize,
  4254  //	LPDWORD lpVolumeSerialNumber,
  4255  //	LPDWORD lpMaximumComponentLength,
  4256  //	LPDWORD lpFileSystemFlags,
  4257  //	LPWSTR  lpFileSystemNameBuffer,
  4258  //	DWORD   nFileSystemNameSize
  4259  //
  4260  // );
  4261  func XGetVolumeInformationW(t *TLS, lpRootPathName, lpVolumeNameBuffer uintptr, nVolumeNameSize uint32, lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer uintptr, nFileSystemNameSize uint32) int32 {
  4262  	r0, _, err := syscall.Syscall9(procGetVolumeInformationW.Addr(), 8,
  4263  		lpRootPathName,
  4264  		lpVolumeNameBuffer,
  4265  		uintptr(nVolumeNameSize),
  4266  		lpVolumeSerialNumber,
  4267  		lpMaximumComponentLength,
  4268  		lpFileSystemFlags,
  4269  		lpFileSystemNameBuffer,
  4270  		uintptr(nFileSystemNameSize),
  4271  		0,
  4272  	)
  4273  	if err != 0 {
  4274  		t.setErrno(err)
  4275  	}
  4276  	return int32(r0)
  4277  }
  4278  
  4279  // wchar_t *wcschr(
  4280  //
  4281  //	const wchar_t *str,
  4282  //	wchar_t c
  4283  //
  4284  // );
  4285  func Xwcschr(t *TLS, str uintptr, c wchar_t) uintptr {
  4286  	var source = str
  4287  	for {
  4288  		var buf = *(*uint16)(unsafe.Pointer(source))
  4289  		if buf == 0 {
  4290  			return 0
  4291  		}
  4292  		if buf == c {
  4293  			return source
  4294  		}
  4295  		// wchar_t = 2 bytes
  4296  		source++
  4297  		source++
  4298  	}
  4299  }
  4300  
  4301  // BOOL SetFileTime(
  4302  //
  4303  //	HANDLE         hFile,
  4304  //	const FILETIME *lpCreationTime,
  4305  //	const FILETIME *lpLastAccessTime,
  4306  //	const FILETIME *lpLastWriteTime
  4307  //
  4308  // );
  4309  func XSetFileTime(t *TLS, hFile uintptr, lpCreationTime, lpLastAccessTime, lpLastWriteTime uintptr) int32 {
  4310  	panic(todo(""))
  4311  }
  4312  
  4313  // DWORD GetNamedSecurityInfoW(
  4314  //
  4315  //	LPCWSTR              pObjectName,
  4316  //	SE_OBJECT_TYPE       ObjectType,
  4317  //	SECURITY_INFORMATION SecurityInfo,
  4318  //	PSID                 *ppsidOwner,
  4319  //	PSID                 *ppsidGroup,
  4320  //	PACL                 *ppDacl,
  4321  //	PACL                 *ppSacl,
  4322  //	PSECURITY_DESCRIPTOR *ppSecurityDescriptor
  4323  //
  4324  // );
  4325  func XGetNamedSecurityInfoW(t *TLS, pObjectName uintptr, ObjectType, SecurityInfo uint32, ppsidOwner, ppsidGroup, ppDacl, ppSacl, ppSecurityDescriptor uintptr) uint32 {
  4326  	panic(todo(""))
  4327  }
  4328  
  4329  // BOOL OpenProcessToken(
  4330  //
  4331  //	HANDLE  ProcessHandle,
  4332  //	DWORD   DesiredAccess,
  4333  //	PHANDLE TokenHandle
  4334  //
  4335  // );
  4336  func XOpenProcessToken(t *TLS, ProcessHandle uintptr, DesiredAccess uint32, TokenHandle uintptr) int32 {
  4337  	panic(todo(""))
  4338  }
  4339  
  4340  // BOOL GetTokenInformation(
  4341  //
  4342  //	HANDLE                  TokenHandle,
  4343  //	TOKEN_INFORMATION_CLASS TokenInformationClass,
  4344  //	LPVOID                  TokenInformation,
  4345  //	DWORD                   TokenInformationLength,
  4346  //	PDWORD                  ReturnLength
  4347  //
  4348  // );
  4349  func XGetTokenInformation(t *TLS, TokenHandle uintptr, TokenInformationClass uint32, TokenInformation uintptr, TokenInformationLength uint32, ReturnLength uintptr) int32 {
  4350  	panic(todo(""))
  4351  }
  4352  
  4353  // BOOL EqualSid(
  4354  //
  4355  //	PSID pSid1,
  4356  //	PSID pSid2
  4357  //
  4358  // );
  4359  func XEqualSid(t *TLS, pSid1, pSid2 uintptr) int32 {
  4360  	panic(todo(""))
  4361  }
  4362  
  4363  // int WSAStartup(
  4364  //
  4365  //	WORD      wVersionRequired,
  4366  //	LPWSADATA lpWSAData
  4367  //
  4368  // );
  4369  func XWSAStartup(t *TLS, wVersionRequired uint16, lpWSAData uintptr) int32 {
  4370  	r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(wVersionRequired), lpWSAData, 0)
  4371  	if r0 != 0 {
  4372  		t.setErrno(r0)
  4373  	}
  4374  	return int32(r0)
  4375  }
  4376  
  4377  // HMODULE GetModuleHandleA(LPCSTR lpModuleName);
  4378  func XGetModuleHandleA(t *TLS, lpModuleName uintptr) uintptr {
  4379  	r0, _, err := syscall.Syscall(procGetModuleHandleA.Addr(), 1, lpModuleName, 0, 0)
  4380  	if r0 == 0 {
  4381  		t.setErrno(err)
  4382  	}
  4383  	return r0
  4384  }
  4385  
  4386  // HMODULE GetModuleHandleW(
  4387  //
  4388  //	LPCWSTR lpModuleName
  4389  //
  4390  // );
  4391  func XGetModuleHandleW(t *TLS, lpModuleName uintptr) uintptr {
  4392  	r0, _, err := syscall.Syscall(procGetModuleHandleW.Addr(), 1, lpModuleName, 0, 0)
  4393  	if r0 == 0 {
  4394  		t.setErrno(err)
  4395  	}
  4396  	return r0
  4397  }
  4398  
  4399  // DWORD GetEnvironmentVariableW(
  4400  //
  4401  //	LPCWSTR lpName,
  4402  //	LPWSTR  lpBuffer,
  4403  //	DWORD   nSize
  4404  //
  4405  // );
  4406  func XGetEnvironmentVariableW(t *TLS, lpName, lpBuffer uintptr, nSize uint32) uint32 {
  4407  	r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableW.Addr(), 3, lpName, lpBuffer, uintptr(nSize))
  4408  	n := uint32(r0)
  4409  	if n == 0 {
  4410  		if e1 != 0 {
  4411  			t.setErrno(e1)
  4412  		} else {
  4413  			t.setErrno(errno.EINVAL)
  4414  		}
  4415  	}
  4416  	return n
  4417  }
  4418  
  4419  // int lstrcmpiA(
  4420  //
  4421  //	LPCSTR lpString1,
  4422  //	LPCSTR lpString2
  4423  //
  4424  // );
  4425  func XlstrcmpiA(t *TLS, lpString1, lpString2 uintptr) int32 {
  4426  	var s1 = strings.ToLower(GoString(lpString1))
  4427  	var s2 = strings.ToLower(GoString(lpString2))
  4428  	return int32(strings.Compare(s1, s2))
  4429  }
  4430  
  4431  func XGetModuleFileNameA(t *TLS, _ ...interface{}) int32 {
  4432  	panic(todo(""))
  4433  }
  4434  
  4435  // UINT GetACP();
  4436  func XGetACP(t *TLS) uint32 {
  4437  	r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0)
  4438  	return uint32(r0)
  4439  }
  4440  
  4441  // BOOL GetUserNameW(
  4442  //
  4443  //	LPWSTR  lpBuffer,
  4444  //	LPDWORD pcbBuffer
  4445  //
  4446  // );
  4447  func XGetUserNameW(t *TLS, lpBuffer, pcbBuffer uintptr) int32 {
  4448  	u, err := user.Current()
  4449  	if err != nil {
  4450  		panic(todo(""))
  4451  		return 0
  4452  	}
  4453  
  4454  	wcnt := *(*uint16)(unsafe.Pointer(pcbBuffer))
  4455  	s := utf16.Encode([]rune(u.Username))
  4456  	if len(s)+1 > int(wcnt) {
  4457  		panic(todo(""))
  4458  	}
  4459  
  4460  	*(*uint16)(unsafe.Pointer(pcbBuffer)) = uint16(len(s) + 1)
  4461  	for _, v := range s {
  4462  		*(*uint16)(unsafe.Pointer(lpBuffer)) = v
  4463  		lpBuffer += 2
  4464  	}
  4465  	return 1
  4466  }
  4467  
  4468  // HMODULE LoadLibraryExW(
  4469  //
  4470  //	LPCWSTR lpLibFileName,
  4471  //	HANDLE  hFile,
  4472  //	DWORD   dwFlags
  4473  //
  4474  // );
  4475  func XLoadLibraryExW(t *TLS, lpLibFileName, hFile uintptr, dwFlags uint32) uintptr {
  4476  	return 0 // If the function fails, the return value is NULL.
  4477  }
  4478  
  4479  // wchar_t *wcscpy(
  4480  //
  4481  //	wchar_t *strDestination,
  4482  //	const wchar_t *strSource
  4483  //
  4484  // );
  4485  func Xwcscpy(t *TLS, strDestination, strSource uintptr) uintptr {
  4486  	if strSource == 0 {
  4487  		return 0
  4488  	}
  4489  
  4490  	d := strDestination
  4491  	for {
  4492  		c := *(*uint16)(unsafe.Pointer(strSource))
  4493  		strSource += 2
  4494  		*(*uint16)(unsafe.Pointer(d)) = c
  4495  		d += 2
  4496  		if c == 0 {
  4497  			return strDestination
  4498  		}
  4499  	}
  4500  }
  4501  
  4502  func XwsprintfW(t *TLS, _ ...interface{}) int32 {
  4503  	panic(todo(""))
  4504  }
  4505  
  4506  // ATOM RegisterClassW(
  4507  //
  4508  //	const WNDCLASSW *lpWndClass
  4509  //
  4510  // );
  4511  func XRegisterClassW(t *TLS, lpWndClass uintptr) int32 {
  4512  	r0, _, err := syscall.Syscall(procRegisterClassW.Addr(), 1, lpWndClass, 0, 0)
  4513  	if r0 == 0 {
  4514  		t.setErrno(err)
  4515  	}
  4516  	return int32(r0)
  4517  }
  4518  
  4519  func XKillTimer(t *TLS, _ ...interface{}) int32 {
  4520  	panic(todo(""))
  4521  }
  4522  
  4523  func XDestroyWindow(t *TLS, _ ...interface{}) int32 {
  4524  	panic(todo(""))
  4525  }
  4526  
  4527  // BOOL UnregisterClassW(
  4528  //
  4529  //	LPCWSTR   lpClassName,
  4530  //	HINSTANCE hInstance
  4531  //
  4532  // );
  4533  func XUnregisterClassW(t *TLS, lpClassName, hInstance uintptr) int32 {
  4534  	r0, _, err := syscall.Syscall(procUnregisterClassW.Addr(), 2, lpClassName, hInstance, 0)
  4535  	if r0 == 0 {
  4536  		t.setErrno(err)
  4537  	}
  4538  	return int32(r0)
  4539  }
  4540  
  4541  func XPostMessageW(t *TLS, _ ...interface{}) int32 {
  4542  	panic(todo(""))
  4543  }
  4544  
  4545  func XSetTimer(t *TLS, _ ...interface{}) int32 {
  4546  	panic(todo(""))
  4547  }
  4548  
  4549  // HWND CreateWindowExW(
  4550  //
  4551  //	DWORD     dwExStyle,
  4552  //	LPCWSTR   lpClassName,
  4553  //	LPCWSTR   lpWindowName,
  4554  //	DWORD     dwStyle,
  4555  //	int       X,
  4556  //	int       Y,
  4557  //	int       nWidth,
  4558  //	int       nHeight,
  4559  //	HWND      hWndParent,
  4560  //	HMENU     hMenu,
  4561  //	HINSTANCE hInstance,
  4562  //	LPVOID    lpParam
  4563  //
  4564  // );
  4565  func XCreateWindowExW(t *TLS, dwExStyle uint32, lpClassName, lpWindowName uintptr, dwStyle uint32, x, y, nWidth, nHeight int32, hWndParent, hMenu, hInstance, lpParam uintptr) uintptr {
  4566  	r0, _, err := syscall.Syscall12(procCreateWindowExW.Addr(), 12,
  4567  		uintptr(dwExStyle),
  4568  		lpClassName,
  4569  		lpWindowName,
  4570  		uintptr(dwStyle),
  4571  		uintptr(x),
  4572  		uintptr(y),
  4573  		uintptr(nWidth),
  4574  		uintptr(nHeight),
  4575  		hWndParent,
  4576  		hMenu,
  4577  		hInstance,
  4578  		lpParam,
  4579  	)
  4580  	if err != 0 {
  4581  		t.setErrno(err)
  4582  	}
  4583  	return r0
  4584  }
  4585  
  4586  // BOOL PeekMessageW(
  4587  //
  4588  //	LPMSG lpMsg,
  4589  //	HWND  hWnd,
  4590  //	UINT  wMsgFilterMin,
  4591  //	UINT  wMsgFilterMax,
  4592  //	UINT  wRemoveMsg
  4593  //
  4594  // );
  4595  func XPeekMessageW(t *TLS, lpMsg, hWnd uintptr, wMsgFilterMin, wMsgFilterMax, wRemoveMsg uint32) int32 {
  4596  	r0, _, err := syscall.Syscall6(procPeekMessageW.Addr(), 5,
  4597  		lpMsg,
  4598  		hWnd,
  4599  		uintptr(wMsgFilterMin),
  4600  		uintptr(wMsgFilterMax),
  4601  		uintptr(wRemoveMsg),
  4602  		0,
  4603  	)
  4604  	if err != 0 {
  4605  		t.setErrno(err)
  4606  	}
  4607  	return int32(r0)
  4608  }
  4609  
  4610  func XGetMessageW(t *TLS, _ ...interface{}) int32 {
  4611  	panic(todo(""))
  4612  }
  4613  
  4614  func XPostQuitMessage(t *TLS, _ ...interface{}) int32 {
  4615  	panic(todo(""))
  4616  }
  4617  
  4618  func XTranslateMessage(t *TLS, _ ...interface{}) int32 {
  4619  	panic(todo(""))
  4620  }
  4621  
  4622  func XDispatchMessageW(t *TLS, _ ...interface{}) int32 {
  4623  	panic(todo(""))
  4624  }
  4625  
  4626  // DWORD SleepEx(
  4627  //
  4628  //	DWORD dwMilliseconds,
  4629  //	BOOL  bAlertable
  4630  //
  4631  // );
  4632  func XSleepEx(t *TLS, dwMilliseconds uint32, bAlertable int32) uint32 {
  4633  	r0, _, _ := syscall.Syscall(procSleepEx.Addr(), 2, uintptr(dwMilliseconds), uintptr(bAlertable), 0)
  4634  	return uint32(r0)
  4635  }
  4636  
  4637  // BOOL CreatePipe(
  4638  //
  4639  //	PHANDLE               hReadPipe,
  4640  //	PHANDLE               hWritePipe,
  4641  //	LPSECURITY_ATTRIBUTES lpPipeAttributes,
  4642  //	DWORD                 nSize
  4643  //
  4644  // );
  4645  func XCreatePipe(t *TLS, hReadPipe, hWritePipe, lpPipeAttributes uintptr, nSize uint32) int32 {
  4646  	r0, _, err := syscall.Syscall6(procCreatePipe.Addr(), 4, hReadPipe, hWritePipe, lpPipeAttributes, uintptr(nSize), 0, 0)
  4647  	if r0 == 0 {
  4648  		t.setErrno(err)
  4649  	}
  4650  	return int32(r0)
  4651  }
  4652  
  4653  // BOOL CreateProcessW(
  4654  //
  4655  //	LPCWSTR               lpApplicationName,
  4656  //	LPWSTR                lpCommandLine,
  4657  //	LPSECURITY_ATTRIBUTES lpProcessAttributes,
  4658  //	LPSECURITY_ATTRIBUTES lpThreadAttributes,
  4659  //	BOOL                  bInheritHandles,
  4660  //	DWORD                 dwCreationFlags,
  4661  //	LPVOID                lpEnvironment,
  4662  //	LPCWSTR               lpCurrentDirectory,
  4663  //	LPSTARTUPINFOW        lpStartupInfo,
  4664  //	LPPROCESS_INFORMATION lpProcessInformation
  4665  //
  4666  // );
  4667  func XCreateProcessW(t *TLS, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes uintptr, bInheritHandles int32, dwCreationFlags uint32,
  4668  	lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation uintptr) int32 {
  4669  
  4670  	r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
  4671  		uintptr(bInheritHandles), uintptr(dwCreationFlags), lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, 0, 0)
  4672  	if r1 == 0 {
  4673  		if e1 != 0 {
  4674  			t.setErrno(e1)
  4675  		} else {
  4676  			t.setErrno(errno.EINVAL)
  4677  		}
  4678  	}
  4679  
  4680  	return int32(r1)
  4681  }
  4682  
  4683  // DWORD WaitForInputIdle(
  4684  //
  4685  //	HANDLE hProcess,
  4686  //	DWORD  dwMilliseconds
  4687  //
  4688  // );
  4689  func XWaitForInputIdle(t *TLS, hProcess uintptr, dwMilliseconds uint32) int32 {
  4690  	r0, _, _ := syscall.Syscall(procWaitForInputIdle.Addr(), 2, hProcess, uintptr(dwMilliseconds), 0)
  4691  	return int32(r0)
  4692  }
  4693  
  4694  // DWORD SearchPathW(
  4695  //
  4696  //	LPCWSTR lpPath,
  4697  //	LPCWSTR lpFileName,
  4698  //	LPCWSTR lpExtension,
  4699  //	DWORD   nBufferLength,
  4700  //	LPWSTR  lpBuffer,
  4701  //	LPWSTR  *lpFilePart
  4702  //
  4703  // );
  4704  func XSearchPathW(t *TLS, lpPath, lpFileName, lpExtension uintptr, nBufferLength uint32, lpBuffer, lpFilePart uintptr) int32 {
  4705  	r0, _, err := syscall.Syscall6(procSearchPathW.Addr(), 6, lpPath, lpFileName, lpExtension, uintptr(nBufferLength), lpBuffer, lpFilePart)
  4706  	if r0 == 0 {
  4707  		t.setErrno(err)
  4708  	}
  4709  	return int32(r0)
  4710  }
  4711  
  4712  func XGetShortPathNameW(t *TLS, _ ...interface{}) int32 {
  4713  	panic(todo(""))
  4714  }
  4715  
  4716  // BOOL GetExitCodeProcess(
  4717  //
  4718  //	HANDLE  hProcess,
  4719  //	LPDWORD lpExitCode
  4720  //
  4721  // );
  4722  func XGetExitCodeProcess(t *TLS, hProcess, lpExitCode uintptr) int32 {
  4723  	r0, _, err := syscall.Syscall(procGetExitCodeProcess.Addr(), 2, hProcess, lpExitCode, 0)
  4724  	if r0 == 0 {
  4725  		t.setErrno(err)
  4726  	}
  4727  	return int32(r0)
  4728  }
  4729  
  4730  // BOOL PeekNamedPipe(
  4731  //
  4732  //	HANDLE  hNamedPipe,
  4733  //	LPVOID  lpBuffer,
  4734  //	DWORD   nBufferSize,
  4735  //	LPDWORD lpBytesRead,
  4736  //	LPDWORD lpTotalBytesAvail,
  4737  //	LPDWORD lpBytesLeftThisMessage
  4738  //
  4739  // );
  4740  func XPeekNamedPipe(t *TLS, hNamedPipe, lpBuffer uintptr, nBufferSize uint32, lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage uintptr) int32 {
  4741  	r0, _, err := syscall.Syscall6(procPeekNamedPipe.Addr(), 6, hNamedPipe, lpBuffer, uintptr(nBufferSize), lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage)
  4742  	if r0 == 0 {
  4743  		t.setErrno(err)
  4744  	}
  4745  	return int32(r0)
  4746  }
  4747  
  4748  // long _InterlockedExchange(
  4749  //
  4750  //	long volatile * Target,
  4751  //	long Value
  4752  //
  4753  // );
  4754  func X_InterlockedExchange(t *TLS, Target uintptr, Value long) long {
  4755  	old := atomic.SwapInt32((*int32)(unsafe.Pointer(Target)), Value)
  4756  	return old
  4757  }
  4758  
  4759  // BOOL TerminateThread(
  4760  //
  4761  //	[in, out] HANDLE hThread,
  4762  //	[in]      DWORD  dwExitCode
  4763  //
  4764  // );
  4765  func XTerminateThread(t *TLS, hThread uintptr, dwExitCode uint32) int32 {
  4766  	r0, _, err := syscall.Syscall(procTerminateThread.Addr(), 2, hThread, uintptr(dwExitCode), 0)
  4767  	if err != 0 {
  4768  		t.setErrno(err)
  4769  	}
  4770  	return int32(r0)
  4771  }
  4772  
  4773  // BOOL GetComputerNameW(
  4774  //
  4775  //	LPWSTR  lpBuffer,
  4776  //	LPDWORD nSize
  4777  //
  4778  // );
  4779  func XGetComputerNameW(t *TLS, lpBuffer, nSize uintptr) int32 {
  4780  	panic(todo(""))
  4781  }
  4782  
  4783  func Xgethostname(t *TLS, _ ...interface{}) int32 {
  4784  	panic(todo(""))
  4785  }
  4786  
  4787  func XSendMessageW(t *TLS, _ ...interface{}) int32 {
  4788  	panic(todo(""))
  4789  }
  4790  
  4791  func XWSAGetLastError(t *TLS, _ ...interface{}) int32 {
  4792  	panic(todo(""))
  4793  }
  4794  
  4795  func Xclosesocket(t *TLS, _ ...interface{}) int32 {
  4796  	panic(todo(""))
  4797  }
  4798  
  4799  func XWspiapiFreeAddrInfo(t *TLS, _ ...interface{}) int32 {
  4800  	panic(todo(""))
  4801  }
  4802  
  4803  func XWspiapiGetNameInfo(t *TLS, _ ...interface{}) int32 {
  4804  	panic(todo(""))
  4805  }
  4806  
  4807  func XIN6_ADDR_EQUAL(t *TLS, _ ...interface{}) int32 {
  4808  	panic(todo(""))
  4809  }
  4810  
  4811  func X__ccgo_in6addr_anyp(t *TLS, _ ...interface{}) int32 {
  4812  	panic(todo(""))
  4813  }
  4814  
  4815  func XIN6_IS_ADDR_V4MAPPED(t *TLS, _ ...interface{}) int32 {
  4816  	panic(todo(""))
  4817  }
  4818  
  4819  func XSetHandleInformation(t *TLS, _ ...interface{}) int32 {
  4820  	panic(todo(""))
  4821  }
  4822  
  4823  func Xioctlsocket(t *TLS, _ ...interface{}) int32 {
  4824  	panic(todo(""))
  4825  }
  4826  
  4827  func XGetWindowLongPtrW(t *TLS, _ ...interface{}) int32 {
  4828  	panic(todo(""))
  4829  }
  4830  
  4831  func XSetWindowLongPtrW(t *TLS, _ ...interface{}) int32 {
  4832  	panic(todo(""))
  4833  }
  4834  
  4835  func XWSAAsyncSelect(t *TLS, _ ...interface{}) int32 {
  4836  	panic(todo(""))
  4837  }
  4838  
  4839  func Xinet_ntoa(t *TLS, _ ...interface{}) uintptr {
  4840  	panic(todo(""))
  4841  }
  4842  
  4843  func X_controlfp(t *TLS, _ ...interface{}) uint32 {
  4844  	panic(todo(""))
  4845  }
  4846  
  4847  // BOOL QueryPerformanceFrequency(
  4848  //
  4849  //	LARGE_INTEGER *lpFrequency
  4850  //
  4851  // );
  4852  func XQueryPerformanceFrequency(t *TLS, lpFrequency uintptr) int32 {
  4853  
  4854  	r1, _, err := syscall.Syscall(procQueryPerformanceFrequency.Addr(), 1, lpFrequency, 0, 0)
  4855  	if r1 == 0 {
  4856  		t.setErrno(err)
  4857  		return 0
  4858  	}
  4859  	return int32(r1)
  4860  }
  4861  
  4862  func inDST(t gotime.Time) bool {
  4863  
  4864  	jan1st := gotime.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location()) // January 1st is always outside DST window
  4865  
  4866  	_, off1 := t.Zone()
  4867  	_, off2 := jan1st.Zone()
  4868  
  4869  	return off1 != off2
  4870  }
  4871  
  4872  // void _ftime( struct _timeb *timeptr );
  4873  func X_ftime(t *TLS, timeptr uintptr) {
  4874  	var tm = gotime.Now()
  4875  	var tPtr = (*time.X__timeb64)(unsafe.Pointer(timeptr))
  4876  	tPtr.Ftime = tm.Unix()
  4877  	tPtr.Fmillitm = uint16(gotime.Duration(tm.Nanosecond()) / gotime.Millisecond)
  4878  	if inDST(tm) {
  4879  		tPtr.Fdstflag = 1
  4880  	}
  4881  	_, offset := tm.Zone()
  4882  	tPtr.Ftimezone = int16(offset)
  4883  }
  4884  
  4885  func Xgmtime(t *TLS, _ ...interface{}) uintptr {
  4886  	panic(todo(""))
  4887  }
  4888  
  4889  func XDdeInitializeW(t *TLS, _ ...interface{}) uint32 {
  4890  	panic(todo(""))
  4891  }
  4892  
  4893  func XDdeCreateStringHandleW(t *TLS, _ ...interface{}) uintptr {
  4894  	panic(todo(""))
  4895  }
  4896  
  4897  func XDdeNameService(t *TLS, _ ...interface{}) int32 {
  4898  	panic(todo(""))
  4899  }
  4900  
  4901  func X_snwprintf(t *TLS, _ ...interface{}) int32 {
  4902  	panic(todo(""))
  4903  }
  4904  
  4905  func XDdeQueryStringW(t *TLS, _ ...interface{}) int32 {
  4906  	panic(todo(""))
  4907  }
  4908  
  4909  // int _wcsicmp(
  4910  //
  4911  //	const wchar_t *string1,
  4912  //	const wchar_t *string2
  4913  //
  4914  // );
  4915  func X_wcsicmp(t *TLS, string1, string2 uintptr) int32 {
  4916  	return Xwcsicmp(t, string1, string2)
  4917  }
  4918  
  4919  func XDdeCreateDataHandle(t *TLS, _ ...interface{}) uintptr {
  4920  	panic(todo(""))
  4921  }
  4922  
  4923  func XDdeAccessData(t *TLS, _ ...interface{}) uintptr {
  4924  	panic(todo(""))
  4925  }
  4926  
  4927  func XDdeUnaccessData(t *TLS, _ ...interface{}) int32 {
  4928  	panic(todo(""))
  4929  }
  4930  
  4931  func XDdeUninitialize(t *TLS, _ ...interface{}) int32 {
  4932  	panic(todo(""))
  4933  }
  4934  
  4935  func XDdeConnect(t *TLS, _ ...interface{}) uintptr {
  4936  	panic(todo(""))
  4937  }
  4938  
  4939  func XDdeFreeStringHandle(t *TLS, _ ...interface{}) int32 {
  4940  	panic(todo(""))
  4941  }
  4942  
  4943  func XRegisterClassExW(t *TLS, _ ...interface{}) int32 {
  4944  	panic(todo(""))
  4945  }
  4946  
  4947  func XGlobalGetAtomNameW(t *TLS, _ ...interface{}) int32 {
  4948  	panic(todo(""))
  4949  }
  4950  
  4951  func XGlobalAddAtomW(t *TLS, _ ...interface{}) uint16 {
  4952  	panic(todo(""))
  4953  }
  4954  
  4955  func XEnumWindows(t *TLS, _ ...interface{}) int32 {
  4956  	panic(todo(""))
  4957  }
  4958  
  4959  func XIsWindow(t *TLS, _ ...interface{}) int32 {
  4960  	panic(todo(""))
  4961  }
  4962  
  4963  func XGlobalDeleteAtom(t *TLS, _ ...interface{}) int32 {
  4964  	panic(todo(""))
  4965  }
  4966  
  4967  func XDdeGetLastError(t *TLS, _ ...interface{}) uint32 {
  4968  	panic(todo(""))
  4969  }
  4970  
  4971  // HDDEDATA DdeClientTransaction(
  4972  //
  4973  //	LPBYTE  pData,
  4974  //	DWORD   cbData,
  4975  //	HCONV   hConv,
  4976  //	HSZ     hszItem,
  4977  //	UINT    wFmt,
  4978  //	UINT    wType,
  4979  //	DWORD   dwTimeout,
  4980  //	LPDWORD pdwResult
  4981  //
  4982  // );
  4983  func XDdeClientTransaction(t *TLS, pData uintptr, cbData uint32, hConv uintptr, hszItem uintptr, wFmt, wType, dwTimeout uint32, pdwResult uintptr) uintptr {
  4984  	panic(todo(""))
  4985  }
  4986  
  4987  func XDdeAbandonTransaction(t *TLS, _ ...interface{}) int32 {
  4988  	panic(todo(""))
  4989  }
  4990  
  4991  func XDdeFreeDataHandle(t *TLS, _ ...interface{}) int32 {
  4992  	panic(todo(""))
  4993  }
  4994  
  4995  func XDdeGetData(t *TLS, _ ...interface{}) int32 {
  4996  	panic(todo(""))
  4997  }
  4998  
  4999  func XDdeDisconnect(t *TLS, _ ...interface{}) int32 {
  5000  	panic(todo(""))
  5001  }
  5002  
  5003  func XRegCloseKey(t *TLS, _ ...interface{}) int32 {
  5004  	panic(todo(""))
  5005  }
  5006  
  5007  func XRegDeleteValueW(t *TLS, _ ...interface{}) int32 {
  5008  	panic(todo(""))
  5009  }
  5010  
  5011  func XRegEnumKeyExW(t *TLS, _ ...interface{}) int32 {
  5012  	panic(todo(""))
  5013  }
  5014  
  5015  func XRegQueryValueExW(t *TLS, _ ...interface{}) int32 {
  5016  	panic(todo(""))
  5017  }
  5018  
  5019  func XRegEnumValueW(t *TLS, _ ...interface{}) int32 {
  5020  	panic(todo(""))
  5021  }
  5022  
  5023  func XRegConnectRegistryW(t *TLS, _ ...interface{}) int32 {
  5024  	panic(todo(""))
  5025  }
  5026  
  5027  func XRegCreateKeyExW(t *TLS, _ ...interface{}) int32 {
  5028  	panic(todo(""))
  5029  }
  5030  
  5031  func XRegOpenKeyExW(t *TLS, _ ...interface{}) int32 {
  5032  	panic(todo(""))
  5033  }
  5034  
  5035  func XRegDeleteKeyW(t *TLS, _ ...interface{}) int32 {
  5036  	panic(todo(""))
  5037  }
  5038  
  5039  func XRegSetValueExW(t *TLS, _ ...interface{}) int32 {
  5040  	panic(todo(""))
  5041  }
  5042  
  5043  // int _vsnwprintf(
  5044  //
  5045  //	wchar_t *buffer,
  5046  //	size_t count,
  5047  //	const wchar_t *format,
  5048  //	va_list argptr
  5049  //
  5050  // );
  5051  func X__mingw_vsnwprintf(t *TLS, buffer uintptr, count types.Size_t, format, va uintptr) int32 {
  5052  	panic(todo(""))
  5053  }
  5054  
  5055  // int vprintf(const char *format, va_list ap);
  5056  func X__mingw_vprintf(t *TLS, s, ap uintptr) int32 { return Xvprintf(t, s, ap) }
  5057  
  5058  // int vfscanf(FILE * restrict stream, const char * restrict format, va_list arg);
  5059  func X__mingw_vfscanf(t *TLS, stream, format, ap uintptr) int32 {
  5060  	panic(todo(""))
  5061  }
  5062  
  5063  // int vsscanf(const char *str, const char *format, va_list ap);
  5064  func X__mingw_vsscanf(t *TLS, str, format, ap uintptr) int32 {
  5065  	return Xsscanf(t, str, format, ap)
  5066  }
  5067  
  5068  // int vfprintf(FILE * restrict stream, const char * restrict format, va_list arg);
  5069  func X__mingw_vfprintf(t *TLS, f uintptr, format, va uintptr) int32 {
  5070  	return Xvfprintf(t, f, format, va)
  5071  }
  5072  
  5073  // int vsprintf(char * restrict s, const char * restrict format, va_list arg);
  5074  func X__mingw_vsprintf(t *TLS, s, format, ap uintptr) int32 {
  5075  	return Xvsprintf(t, s, format, ap)
  5076  }
  5077  
  5078  // int vsnprintf(char *str, size_t size, const char *format, va_list ap);
  5079  func X__mingw_vsnprintf(t *TLS, str uintptr, size types.Size_t, format, ap uintptr) int32 {
  5080  	panic(todo(""))
  5081  }
  5082  
  5083  // int putchar(int char)
  5084  func X_putchar(t *TLS, c int32) int32 {
  5085  	if _, err := fwrite(unistd.STDOUT_FILENO, []byte{byte(c)}); err != nil {
  5086  		return -1
  5087  	}
  5088  	return int32(byte(c))
  5089  }
  5090  
  5091  // int vfwscanf(FILE *stream, const wchar_t *format, va_list argptr;);
  5092  func X__mingw_vfwscanf(t *TLS, stream uintptr, format, ap uintptr) int32 {
  5093  	panic(todo(""))
  5094  }
  5095  
  5096  // int vswscanf(const wchar_t *buffer, const wchar_t *format, va_list arglist);
  5097  func X__mingw_vswscanf(t *TLS, stream uintptr, format, ap uintptr) int32 {
  5098  	panic(todo(""))
  5099  }
  5100  
  5101  // int vfwprintf(FILE * restrict stream, const wchar_t * restrict format, va_list arg);
  5102  func X__mingw_vfwprintf(t *TLS, stream, format, ap uintptr) int32 {
  5103  	panic(todo(""))
  5104  }
  5105  
  5106  // int putchar(int c);
  5107  func Xputchar(t *TLS, c int32) int32 {
  5108  	panic(todo(""))
  5109  }
  5110  
  5111  // void _assert(
  5112  //
  5113  //	char const* message,
  5114  //	char const* filename,
  5115  //	unsigned line
  5116  //
  5117  // );
  5118  func X_assert(t *TLS, message, filename uintptr, line uint32) {
  5119  	panic(todo(""))
  5120  }
  5121  
  5122  // char *strdup(const char *s);
  5123  func X_strdup(t *TLS, s uintptr) uintptr {
  5124  	panic(todo(""))
  5125  }
  5126  
  5127  // int _access(
  5128  //
  5129  //	const char *path,
  5130  //	int mode
  5131  //
  5132  // );
  5133  func X_access(t *TLS, pathname uintptr, mode int32) int32 {
  5134  
  5135  	var path = GoString(pathname)
  5136  
  5137  	info, err := os.Stat(path)
  5138  	if err != nil {
  5139  		// doesn't exist
  5140  		return errno.ENOENT
  5141  	}
  5142  
  5143  	switch mode {
  5144  	case 0:
  5145  		// exists
  5146  		return 0
  5147  	case 2:
  5148  		// write-only
  5149  		// Check if the user bit is enabled in file permission
  5150  		if info.Mode().Perm()&(1<<(uint(7))) == 1 {
  5151  			// write-able
  5152  			return 0
  5153  		}
  5154  	case 4:
  5155  		// read-only
  5156  		// Check if the user bit is enabled in file permission
  5157  		if info.Mode().Perm()&(1<<(uint(7))) == 0 {
  5158  			// not set, so read-only
  5159  			return 0
  5160  		}
  5161  	case 6:
  5162  		// r/w
  5163  		if info.Mode().Perm()&(1<<(uint(7))) == 1 {
  5164  			// write-able
  5165  			return 0
  5166  		}
  5167  	}
  5168  
  5169  	return errno.EACCES
  5170  
  5171  }
  5172  
  5173  // BOOL WINAPI SetConsoleCtrlHandler(
  5174  //
  5175  //	_In_opt_ PHANDLER_ROUTINE HandlerRoutine,
  5176  //	_In_     BOOL             Add
  5177  //
  5178  // );
  5179  func XSetConsoleCtrlHandler(t *TLS, HandlerRoutine uintptr, Add int32) int32 {
  5180  
  5181  	//var fcc = &struct {
  5182  	//	f func(*TLS, uint32) int32
  5183  	//}{}
  5184  	//fcc = (*struct{ f func(*TLS, uint32) int32 })(unsafe.Pointer(HandlerRoutine))
  5185  	//var hdlr = fcc.f
  5186  	//
  5187  	//_, _, err := procSetConsoleCtrlHandler.Call(
  5188  	//syscall.NewCallback(func(controlType uint) uint {
  5189  	//		return uint( hdlr(t, uint32(controlType)) )
  5190  	//	}), 1)
  5191  	//
  5192  	//if err != nil {
  5193  	//	panic("failed: SetConsoleCtrlHandler")
  5194  	//}
  5195  
  5196  	return 0
  5197  }
  5198  
  5199  // DebugBreak
  5200  func XDebugBreak(t *TLS) {
  5201  	panic(todo(""))
  5202  }
  5203  
  5204  // int _isatty( int fd );
  5205  func X_isatty(t *TLS, fd int32) int32 {
  5206  
  5207  	f, ok := fdToFile(fd)
  5208  	if !ok {
  5209  		t.setErrno(errno.EBADF)
  5210  		return 0
  5211  	}
  5212  
  5213  	if fd == unistd.STDOUT_FILENO ||
  5214  		fd == unistd.STDIN_FILENO ||
  5215  		fd == unistd.STDERR_FILENO {
  5216  		var mode uint32
  5217  		err := syscall.GetConsoleMode(f.Handle, &mode)
  5218  		if err != nil {
  5219  			t.setErrno(errno.EINVAL)
  5220  			return 0
  5221  		}
  5222  		// is console
  5223  		return 1
  5224  	}
  5225  
  5226  	return 0
  5227  }
  5228  
  5229  // BOOL WINAPI SetConsoleTextAttribute(
  5230  //
  5231  //	_In_ HANDLE hConsoleOutput,
  5232  //	_In_ WORD   wAttributes
  5233  //
  5234  // );
  5235  func XSetConsoleTextAttribute(t *TLS, hConsoleOutput uintptr, wAttributes uint16) int32 {
  5236  	r1, _, _ := syscall.Syscall(procSetConsoleTextAttribute.Addr(), 2, hConsoleOutput, uintptr(wAttributes), 0)
  5237  	return int32(r1)
  5238  }
  5239  
  5240  // BOOL WINAPI GetConsoleScreenBufferInfo(
  5241  //
  5242  //	_In_  HANDLE                      hConsoleOutput,
  5243  //	_Out_ PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
  5244  //
  5245  // );
  5246  func XGetConsoleScreenBufferInfo(t *TLS, hConsoleOutput, lpConsoleScreenBufferInfo uintptr) int32 {
  5247  	r1, _, _ := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, hConsoleOutput, lpConsoleScreenBufferInfo, 0)
  5248  	return int32(r1)
  5249  }
  5250  
  5251  // FILE *_popen(
  5252  //
  5253  //	const char *command,
  5254  //	const char *mode
  5255  //
  5256  // );
  5257  func X_popen(t *TLS, command, mode uintptr) uintptr {
  5258  	panic(todo(""))
  5259  }
  5260  
  5261  // int _wunlink(
  5262  //
  5263  //	const wchar_t *filename
  5264  //
  5265  // );
  5266  func X_wunlink(t *TLS, filename uintptr) int32 {
  5267  	panic(todo(""))
  5268  }
  5269  
  5270  func Xclosedir(tls *TLS, dir uintptr) int32 {
  5271  	panic(todo(""))
  5272  }
  5273  
  5274  func Xopendir(tls *TLS, name uintptr) uintptr {
  5275  	panic(todo(""))
  5276  }
  5277  
  5278  func Xreaddir(tls *TLS, dir uintptr) uintptr {
  5279  	panic(todo(""))
  5280  }
  5281  
  5282  // int _unlink(
  5283  //
  5284  //	const char *filename
  5285  //
  5286  // );
  5287  func X_unlink(t *TLS, filename uintptr) int32 {
  5288  	panic(todo(""))
  5289  }
  5290  
  5291  // int pclose(FILE *stream);
  5292  func X_pclose(t *TLS, stream uintptr) int32 {
  5293  	panic(todo(""))
  5294  }
  5295  
  5296  // int setmode (int fd, int mode);
  5297  func Xsetmode(t *TLS, fd, mode int32) int32 {
  5298  	return X_setmode(t, fd, mode)
  5299  }
  5300  
  5301  // int _setmode (int fd, int mode);
  5302  func X_setmode(t *TLS, fd, mode int32) int32 {
  5303  
  5304  	_, ok := fdToFile(fd)
  5305  	if !ok {
  5306  		t.setErrno(errno.EBADF)
  5307  		return -1
  5308  	}
  5309  
  5310  	// we're always in binary mode.
  5311  	// at least for now.
  5312  
  5313  	if mode == fcntl.O_BINARY {
  5314  		return fcntl.O_BINARY
  5315  	} else {
  5316  		t.setErrno(errno.EINVAL)
  5317  		return -1
  5318  	}
  5319  }
  5320  
  5321  // int _mkdir(const char *dirname);
  5322  func X_mkdir(t *TLS, dirname uintptr) int32 {
  5323  	panic(todo(""))
  5324  }
  5325  
  5326  // int _chmod( const char *filename, int pmode );
  5327  func X_chmod(t *TLS, filename uintptr, pmode int32) int32 {
  5328  	panic(todo(""))
  5329  }
  5330  
  5331  // int _fileno(FILE *stream);
  5332  func X_fileno(t *TLS, stream uintptr) int32 {
  5333  	f, ok := winGetObject(stream).(*file)
  5334  	if !ok {
  5335  		t.setErrno(errno.EBADF)
  5336  		return -1
  5337  	}
  5338  	return f._fd
  5339  }
  5340  
  5341  // void rewind(FILE *stream);
  5342  func Xrewind(t *TLS, stream uintptr) {
  5343  	Xfseek(t, stream, 0, unistd.SEEK_SET)
  5344  }
  5345  
  5346  // __atomic_load_n
  5347  func X__atomic_load_n(t *TLS) {
  5348  	panic(todo(""))
  5349  }
  5350  
  5351  // __atomic_store_n
  5352  func X__atomic_store_n(t *TLS, _ ...interface{}) int32 {
  5353  	panic(todo(""))
  5354  }
  5355  
  5356  // __builtin_add_overflow
  5357  func X__builtin_add_overflow(t *TLS) {
  5358  	panic(todo(""))
  5359  }
  5360  
  5361  // __builtin_mul_overflow
  5362  func X__builtin_mul_overflow(t *TLS) {
  5363  	panic(todo(""))
  5364  }
  5365  
  5366  // __builtin_sub_overflow
  5367  func X__builtin_sub_overflow(t *TLS) {
  5368  	panic(todo(""))
  5369  }
  5370  
  5371  func goWideBytes(p uintptr, n int) []uint16 {
  5372  	b := GoBytes(p, 2*n)
  5373  	var w []uint16
  5374  	for i := 0; i < len(b); i += 2 {
  5375  		w = append(w, *(*uint16)(unsafe.Pointer(&b[i])))
  5376  	}
  5377  	return w
  5378  }
  5379  
  5380  // This version does include the zero terminator in the returned Go string.
  5381  func goWideString(p uintptr) string {
  5382  	if p == 0 {
  5383  		return ""
  5384  	}
  5385  	var w []uint16
  5386  	var raw = (*RawMem)(unsafe.Pointer(p))
  5387  	var i = 0
  5388  	for {
  5389  		wc := *(*uint16)(unsafe.Pointer(&raw[i]))
  5390  		w = append(w, wc)
  5391  		// append until U0000
  5392  		if wc == 0 {
  5393  			break
  5394  		}
  5395  		i = i + 2
  5396  	}
  5397  	s := utf16.Decode(w)
  5398  	return string(s)
  5399  }
  5400  
  5401  func goWideStringN(p uintptr, n int) string {
  5402  	panic(todo(""))
  5403  }
  5404  
  5405  // This version does not include the zero terminator in the returned Go string.
  5406  func goWideStringNZ(p uintptr) string {
  5407  	if p == 0 {
  5408  		return ""
  5409  	}
  5410  
  5411  	var w []uint16
  5412  	var raw = (*RawMem)(unsafe.Pointer(p))
  5413  	var i = 0
  5414  	for {
  5415  		wc := *(*uint16)(unsafe.Pointer(&raw[i]))
  5416  		if wc == 0 {
  5417  			break
  5418  		}
  5419  
  5420  		w = append(w, wc)
  5421  		i = i + 2
  5422  	}
  5423  	s := utf16.Decode(w)
  5424  	return string(s)
  5425  }
  5426  
  5427  // LPWSTR GetCommandLineW();
  5428  func XGetCommandLineW(t *TLS) uintptr {
  5429  	return uintptr(unsafe.Pointer(syscall.GetCommandLine()))
  5430  }
  5431  
  5432  // BOOL AddAccessDeniedAce(
  5433  //
  5434  //	PACL  pAcl,
  5435  //	DWORD dwAceRevision,
  5436  //	DWORD AccessMask,
  5437  //	PSID  pSid
  5438  //
  5439  // );
  5440  func XAddAccessDeniedAce(t *TLS, pAcl uintptr, dwAceRevision, AccessMask uint32, pSid uintptr) int32 {
  5441  	panic(todo(""))
  5442  }
  5443  
  5444  // BOOL AddAce(
  5445  //
  5446  //	PACL   pAcl,
  5447  //	DWORD  dwAceRevision,
  5448  //	DWORD  dwStartingAceIndex,
  5449  //	LPVOID pAceList,
  5450  //	DWORD  nAceListLength
  5451  //
  5452  // );
  5453  func XAddAce(t *TLS, pAcl uintptr, dwAceRevision, dwStartingAceIndex uint32, pAceList uintptr, nAceListLength uint32) int32 {
  5454  	panic(todo(""))
  5455  }
  5456  
  5457  // BOOL GetAce(
  5458  //
  5459  //	PACL   pAcl,
  5460  //	DWORD  dwAceIndex,
  5461  //	LPVOID *pAce
  5462  //
  5463  // );
  5464  func XGetAce(t *TLS, pAcl uintptr, dwAceIndex uint32, pAce uintptr) int32 {
  5465  	panic(todo(""))
  5466  }
  5467  
  5468  // BOOL GetAclInformation(
  5469  //
  5470  //	PACL                  pAcl,
  5471  //	LPVOID                pAclInformation,
  5472  //	DWORD                 nAclInformationLength,
  5473  //	ACL_INFORMATION_CLASS dwAclInformationClass
  5474  //
  5475  // );
  5476  func XGetAclInformation(t *TLS, pAcl, pAclInformation uintptr, nAclInformationLength, dwAclInformationClass uint32) int32 {
  5477  	r0, _, err := syscall.Syscall6(procGetAclInformation.Addr(), 4,
  5478  		pAclInformation,
  5479  		pAclInformation,
  5480  		uintptr(nAclInformationLength),
  5481  		uintptr(dwAclInformationClass),
  5482  		0,
  5483  		0,
  5484  	)
  5485  	if err != 0 {
  5486  		t.setErrno(err)
  5487  	}
  5488  	return int32(r0)
  5489  }
  5490  
  5491  // BOOL GetFileSecurityA(
  5492  //
  5493  //	LPCSTR               lpFileName,
  5494  //	SECURITY_INFORMATION RequestedInformation,
  5495  //	PSECURITY_DESCRIPTOR pSecurityDescriptor,
  5496  //	DWORD                nLength,
  5497  //	LPDWORD              lpnLengthNeeded
  5498  //
  5499  // );
  5500  func XGetFileSecurityA(t *TLS, lpFileName uintptr, RequestedInformation uint32, pSecurityDescriptor uintptr, nLength uint32, lpnLengthNeeded uintptr) int32 {
  5501  	r0, _, err := syscall.Syscall6(procGetFileSecurityA.Addr(), 5,
  5502  		lpFileName,
  5503  		uintptr(RequestedInformation),
  5504  		pSecurityDescriptor,
  5505  		uintptr(nLength),
  5506  		lpnLengthNeeded,
  5507  		0,
  5508  	)
  5509  	if err != 0 {
  5510  		t.setErrno(err)
  5511  	}
  5512  	return int32(r0)
  5513  }
  5514  
  5515  // DWORD GetLengthSid(
  5516  //
  5517  //	PSID pSid
  5518  //
  5519  // );
  5520  func XGetLengthSid(t *TLS, pSid uintptr) uint32 {
  5521  	panic(todo(""))
  5522  }
  5523  
  5524  // BOOL GetSecurityDescriptorDacl(
  5525  //
  5526  //	PSECURITY_DESCRIPTOR pSecurityDescriptor,
  5527  //	LPBOOL               lpbDaclPresent,
  5528  //	PACL                 *pDacl,
  5529  //	LPBOOL               lpbDaclDefaulted
  5530  //
  5531  // );
  5532  func XGetSecurityDescriptorDacl(t *TLS, pSecurityDescriptor, lpbDaclPresent, pDacl, lpbDaclDefaulted uintptr) int32 {
  5533  	r0, _, err := syscall.Syscall6(procGetSecurityDescriptorDacl.Addr(), 4,
  5534  		pSecurityDescriptor,
  5535  		lpbDaclPresent,
  5536  		pDacl,
  5537  		lpbDaclDefaulted,
  5538  		0,
  5539  		0,
  5540  	)
  5541  	if err != 0 {
  5542  		t.setErrno(err)
  5543  	}
  5544  	return int32(r0)
  5545  }
  5546  
  5547  // DWORD GetSidLengthRequired(
  5548  //
  5549  //	UCHAR nSubAuthorityCount
  5550  //
  5551  // );
  5552  func XGetSidLengthRequired(t *TLS, nSubAuthorityCount uint8) int32 {
  5553  	r0, _, err := syscall.Syscall(procGetSidLengthRequired.Addr(), 1, uintptr(nSubAuthorityCount), 0, 0)
  5554  	if err != 0 {
  5555  		t.setErrno(err)
  5556  	}
  5557  	return int32(r0)
  5558  }
  5559  
  5560  // PDWORD GetSidSubAuthority(
  5561  //
  5562  //	PSID  pSid,
  5563  //	DWORD nSubAuthority
  5564  //
  5565  // );
  5566  func XGetSidSubAuthority(t *TLS, pSid uintptr, nSubAuthority uint32) uintptr {
  5567  	r0, _, err := syscall.Syscall(procGetSidSubAuthority.Addr(), 2, pSid, uintptr(nSubAuthority), 0)
  5568  	if err != 0 {
  5569  		t.setErrno(err)
  5570  	}
  5571  	return r0
  5572  }
  5573  
  5574  // BOOL InitializeAcl(
  5575  //
  5576  //	PACL  pAcl,
  5577  //	DWORD nAclLength,
  5578  //	DWORD dwAclRevision
  5579  //
  5580  // );
  5581  func XInitializeAcl(t *TLS, pAcl uintptr, nAclLength, dwAclRevision uint32) int32 {
  5582  	panic(todo(""))
  5583  }
  5584  
  5585  // BOOL InitializeSid(
  5586  //
  5587  //	PSID                      Sid,
  5588  //	PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
  5589  //	BYTE                      nSubAuthorityCount
  5590  //
  5591  // );
  5592  func XInitializeSid(t *TLS, Sid, pIdentifierAuthority uintptr, nSubAuthorityCount uint8) int32 {
  5593  	r0, _, err := syscall.Syscall(procInitializeSid.Addr(), 3, Sid, pIdentifierAuthority, uintptr(nSubAuthorityCount))
  5594  	if err != 0 {
  5595  		t.setErrno(err)
  5596  	}
  5597  	return int32(r0)
  5598  }
  5599  
  5600  // VOID RaiseException(
  5601  //
  5602  //	DWORD           dwExceptionCode,
  5603  //	DWORD           dwExceptionFlags,
  5604  //	DWORD           nNumberOfArguments,
  5605  //	const ULONG_PTR *lpArguments
  5606  //
  5607  // );
  5608  func XRaiseException(t *TLS, dwExceptionCode, dwExceptionFlags, nNumberOfArguments uint32, lpArguments uintptr) {
  5609  	panic(todo(""))
  5610  }
  5611  
  5612  // UINT SetErrorMode(
  5613  //
  5614  //	UINT uMode
  5615  //
  5616  // );
  5617  func XSetErrorMode(t *TLS, uMode uint32) int32 {
  5618  	panic(todo(""))
  5619  }
  5620  
  5621  // DWORD SetNamedSecurityInfoA(
  5622  //
  5623  //	LPSTR                pObjectName,
  5624  //	SE_OBJECT_TYPE       ObjectType,
  5625  //	SECURITY_INFORMATION SecurityInfo,
  5626  //	PSID                 psidOwner,
  5627  //	PSID                 psidGroup,
  5628  //	PACL                 pDacl,
  5629  //	PACL                 pSacl
  5630  //
  5631  // );
  5632  func XSetNamedSecurityInfoA(t *TLS, pObjectName uintptr, ObjectType, SecurityInfo uint32, psidOwner, psidGroup, pDacl, pSacl uintptr) uint32 {
  5633  	panic(todo(""))
  5634  }
  5635  
  5636  // BOOL CreateProcessA(
  5637  //
  5638  //	LPCSTR                lpApplicationName,
  5639  //	LPSTR                 lpCommandLine,
  5640  //	LPSECURITY_ATTRIBUTES lpProcessAttributes,
  5641  //	LPSECURITY_ATTRIBUTES lpThreadAttributes,
  5642  //	BOOL                  bInheritHandles,
  5643  //	DWORD                 dwCreationFlags,
  5644  //	LPVOID                lpEnvironment,
  5645  //	LPCSTR                lpCurrentDirectory,
  5646  //	LPSTARTUPINFOA        lpStartupInfo,
  5647  //	LPPROCESS_INFORMATION lpProcessInformation
  5648  //
  5649  // );
  5650  func XCreateProcessA(t *TLS, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes uintptr, bInheritHandles int32,
  5651  	dwCreationFlags uint32, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation uintptr) int32 {
  5652  	r1, _, err := syscall.Syscall12(procCreateProcessA.Addr(), 10, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
  5653  		uintptr(bInheritHandles), uintptr(dwCreationFlags), lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, 0, 0)
  5654  	if r1 == 0 {
  5655  		if err != 0 {
  5656  			t.setErrno(err)
  5657  		} else {
  5658  			t.setErrno(errno.EINVAL)
  5659  		}
  5660  	}
  5661  	return int32(r1)
  5662  }
  5663  
  5664  // unsigned int _set_abort_behavior(
  5665  //
  5666  //	unsigned int flags,
  5667  //	unsigned int mask
  5668  //
  5669  // );
  5670  func X_set_abort_behavior(t *TLS, _ ...interface{}) uint32 {
  5671  	panic(todo(""))
  5672  }
  5673  
  5674  // HANDLE OpenEventA(
  5675  //
  5676  //	DWORD  dwDesiredAccess,
  5677  //	BOOL   bInheritHandle,
  5678  //	LPCSTR lpName
  5679  //
  5680  // );
  5681  func XOpenEventA(t *TLS, dwDesiredAccess uint32, bInheritHandle uint32, lpName uintptr) uintptr {
  5682  	r0, _, err := syscall.Syscall(procOpenEventA.Addr(), 3, uintptr(dwDesiredAccess), uintptr(bInheritHandle), lpName)
  5683  	if r0 == 0 {
  5684  		t.setErrno(err)
  5685  	}
  5686  	return r0
  5687  }
  5688  
  5689  // size_t _msize(
  5690  //
  5691  //	void *memblock
  5692  //
  5693  // );
  5694  func X_msize(t *TLS, memblock uintptr) types.Size_t {
  5695  	return types.Size_t(UsableSize(memblock))
  5696  }
  5697  
  5698  // unsigned long _byteswap_ulong ( unsigned long val );
  5699  func X_byteswap_ulong(t *TLS, val ulong) ulong {
  5700  	return X__builtin_bswap32(t, val)
  5701  }
  5702  
  5703  // unsigned __int64 _byteswap_uint64 ( unsigned __int64 val );
  5704  func X_byteswap_uint64(t *TLS, val uint64) uint64 {
  5705  	return X__builtin_bswap64(t, val)
  5706  }
  5707  
  5708  // int _commit(
  5709  //
  5710  //	int fd
  5711  //
  5712  // );
  5713  func X_commit(t *TLS, fd int32) int32 {
  5714  	return Xfsync(t, fd)
  5715  }
  5716  
  5717  // int _stati64(
  5718  //
  5719  //	const char *path,
  5720  //	struct _stati64 *buffer
  5721  //
  5722  // );
  5723  func X_stati64(t *TLS, path, buffer uintptr) int32 {
  5724  	panic(todo(""))
  5725  }
  5726  
  5727  // int _fstati64(
  5728  //
  5729  //	int fd,
  5730  //	struct _stati64 *buffer
  5731  //
  5732  // );
  5733  func X_fstati64(t *TLS, fd int32, buffer uintptr) int32 {
  5734  	panic(todo(""))
  5735  }
  5736  
  5737  // int _findnext32(
  5738  //
  5739  //	intptr_t handle,
  5740  //	struct _finddata32_t *fileinfo
  5741  //
  5742  // );
  5743  func X_findnext32(t *TLS, handle types.Intptr_t, buffer uintptr) int32 {
  5744  	panic(todo(""))
  5745  }
  5746  
  5747  // intptr_t _findfirst32(
  5748  //
  5749  //	const char *filespec,
  5750  //	struct _finddata32_t *fileinfo
  5751  //
  5752  // );
  5753  func X_findfirst32(t *TLS, filespec, fileinfo uintptr) types.Intptr_t {
  5754  	panic(todo(""))
  5755  }
  5756  
  5757  /*-
  5758   * Copyright (c) 1990 The Regents of the University of California.
  5759   * All rights reserved.
  5760   *
  5761   * Redistribution and use in source and binary forms, with or without
  5762   * modification, are permitted provided that the following conditions
  5763   * are met:
  5764   * 1. Redistributions of source code must retain the above copyright
  5765   *    notice, this list of conditions and the following disclaimer.
  5766   * 2. Redistributions in binary form must reproduce the above copyright
  5767   *    notice, this list of conditions and the following disclaimer in the
  5768   *    documentation and/or other materials provided with the distribution.
  5769   * 3. Neither the name of the University nor the names of its contributors
  5770   *    may be used to endorse or promote products derived from this software
  5771   *    without specific prior written permission.
  5772   *
  5773   * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  5774   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  5775   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  5776   * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  5777   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  5778   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  5779   * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  5780   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  5781   * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  5782   * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  5783   * SUCH DAMAGE.
  5784   */
  5785  
  5786  // long strtol(const char *nptr, char **endptr, int base);
  5787  func Xstrtol(t *TLS, nptr, endptr uintptr, base int32) long {
  5788  
  5789  	var s uintptr = nptr
  5790  	var acc ulong
  5791  	var c byte
  5792  	var cutoff ulong
  5793  	var neg int32
  5794  	var any int32
  5795  	var cutlim int32
  5796  
  5797  	/*
  5798  	 * Skip white space and pick up leading +/- sign if any.
  5799  	 * If base is 0, allow 0x for hex and 0 for octal, else
  5800  	 * assume decimal; if base is already 16, allow 0x.
  5801  	 */
  5802  	for {
  5803  		c = *(*byte)(unsafe.Pointer(s))
  5804  		PostIncUintptr(&s, 1)
  5805  		var sp = strings.TrimSpace(string(c))
  5806  		if len(sp) > 0 {
  5807  			break
  5808  		}
  5809  	}
  5810  
  5811  	if c == '-' {
  5812  		neg = 1
  5813  		c = *(*byte)(unsafe.Pointer(s))
  5814  		PostIncUintptr(&s, 1)
  5815  	} else if c == '+' {
  5816  		c = *(*byte)(unsafe.Pointer(s))
  5817  		PostIncUintptr(&s, 1)
  5818  	}
  5819  
  5820  	sp := *(*byte)(unsafe.Pointer(s))
  5821  
  5822  	if (base == 0 || base == 16) &&
  5823  		c == '0' && (sp == 'x' || sp == 'X') {
  5824  		PostIncUintptr(&s, 1)
  5825  		c = *(*byte)(unsafe.Pointer(s)) //s[1];
  5826  		PostIncUintptr(&s, 1)
  5827  		base = 16
  5828  	}
  5829  	if base == 0 {
  5830  		if c == '0' {
  5831  			base = 0
  5832  		} else {
  5833  			base = 10
  5834  		}
  5835  	}
  5836  	/*
  5837  	 * Compute the cutoff value between legal numbers and illegal
  5838  	 * numbers.  That is the largest legal value, divided by the
  5839  	 * base.  An input number that is greater than this value, if
  5840  	 * followed by a legal input character, is too big.  One that
  5841  	 * is equal to this value may be valid or not; the limit
  5842  	 * between valid and invalid numbers is then based on the last
  5843  	 * digit.  For instance, if the range for longs is
  5844  	 * [-2147483648..2147483647] and the input base is 10,
  5845  	 * cutoff will be set to 214748364 and cutlim to either
  5846  	 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
  5847  	 * a value > 214748364, or equal but the next digit is > 7 (or 8),
  5848  	 * the number is too big, and we will return a range error.
  5849  	 *
  5850  	 * Set any if any `digits' consumed; make it negative to indicate
  5851  	 * overflow.
  5852  	 */
  5853  	var ULONG_MAX ulong = 0xFFFFFFFF
  5854  	var LONG_MAX long = long(ULONG_MAX >> 1)
  5855  	var LONG_MIN long = ^LONG_MAX
  5856  
  5857  	if neg == 1 {
  5858  		cutoff = ulong(-1 * LONG_MIN)
  5859  	} else {
  5860  		cutoff = ulong(LONG_MAX)
  5861  	}
  5862  	cutlim = int32(cutoff % ulong(base))
  5863  	cutoff = cutoff / ulong(base)
  5864  
  5865  	acc = 0
  5866  	any = 0
  5867  
  5868  	for {
  5869  		var cs = string(c)
  5870  		if unicode.IsDigit([]rune(cs)[0]) {
  5871  			c -= '0'
  5872  		} else if unicode.IsLetter([]rune(cs)[0]) {
  5873  			if unicode.IsUpper([]rune(cs)[0]) {
  5874  				c -= 'A' - 10
  5875  			} else {
  5876  				c -= 'a' - 10
  5877  			}
  5878  		} else {
  5879  			break
  5880  		}
  5881  
  5882  		if int32(c) >= base {
  5883  			break
  5884  		}
  5885  		if any < 0 || acc > cutoff || (acc == cutoff && int32(c) > cutlim) {
  5886  			any = -1
  5887  
  5888  		} else {
  5889  			any = 1
  5890  			acc *= ulong(base)
  5891  			acc += ulong(c)
  5892  		}
  5893  
  5894  		c = *(*byte)(unsafe.Pointer(s))
  5895  		PostIncUintptr(&s, 1)
  5896  	}
  5897  
  5898  	if any < 0 {
  5899  		if neg == 1 {
  5900  			acc = ulong(LONG_MIN)
  5901  		} else {
  5902  			acc = ulong(LONG_MAX)
  5903  		}
  5904  		t.setErrno(errno.ERANGE)
  5905  	} else if neg == 1 {
  5906  		acc = -acc
  5907  	}
  5908  
  5909  	if endptr != 0 {
  5910  		if any == 1 {
  5911  			PostDecUintptr(&s, 1)
  5912  			AssignPtrUintptr(endptr, s)
  5913  		} else {
  5914  			AssignPtrUintptr(endptr, nptr)
  5915  		}
  5916  	}
  5917  	return long(acc)
  5918  }
  5919  
  5920  // unsigned long int strtoul(const char *nptr, char **endptr, int base);
  5921  func Xstrtoul(t *TLS, nptr, endptr uintptr, base int32) ulong {
  5922  	var s uintptr = nptr
  5923  	var acc ulong
  5924  	var c byte
  5925  	var cutoff ulong
  5926  	var neg int32
  5927  	var any int32
  5928  	var cutlim int32
  5929  
  5930  	/*
  5931  	 * Skip white space and pick up leading +/- sign if any.
  5932  	 * If base is 0, allow 0x for hex and 0 for octal, else
  5933  	 * assume decimal; if base is already 16, allow 0x.
  5934  	 */
  5935  	for {
  5936  		c = *(*byte)(unsafe.Pointer(s))
  5937  		PostIncUintptr(&s, 1)
  5938  		var sp = strings.TrimSpace(string(c))
  5939  		if len(sp) > 0 {
  5940  			break
  5941  		}
  5942  	}
  5943  
  5944  	if c == '-' {
  5945  		neg = 1
  5946  		c = *(*byte)(unsafe.Pointer(s))
  5947  		PostIncUintptr(&s, 1)
  5948  	} else if c == '+' {
  5949  		c = *(*byte)(unsafe.Pointer(s))
  5950  		PostIncUintptr(&s, 1)
  5951  	}
  5952  
  5953  	sp := *(*byte)(unsafe.Pointer(s))
  5954  
  5955  	if (base == 0 || base == 16) &&
  5956  		c == '0' && (sp == 'x' || sp == 'X') {
  5957  		PostIncUintptr(&s, 1)
  5958  		c = *(*byte)(unsafe.Pointer(s)) //s[1];
  5959  		PostIncUintptr(&s, 1)
  5960  		base = 16
  5961  	}
  5962  	if base == 0 {
  5963  		if c == '0' {
  5964  			base = 0
  5965  		} else {
  5966  			base = 10
  5967  		}
  5968  	}
  5969  	var ULONG_MAX ulong = 0xFFFFFFFF
  5970  
  5971  	cutoff = ULONG_MAX / ulong(base)
  5972  	cutlim = int32(ULONG_MAX % ulong(base))
  5973  
  5974  	acc = 0
  5975  	any = 0
  5976  
  5977  	for {
  5978  		var cs = string(c)
  5979  		if unicode.IsDigit([]rune(cs)[0]) {
  5980  			c -= '0'
  5981  		} else if unicode.IsLetter([]rune(cs)[0]) {
  5982  			if unicode.IsUpper([]rune(cs)[0]) {
  5983  				c -= 'A' - 10
  5984  			} else {
  5985  				c -= 'a' - 10
  5986  			}
  5987  		} else {
  5988  			break
  5989  		}
  5990  
  5991  		if int32(c) >= base {
  5992  			break
  5993  		}
  5994  		if any < 0 || acc > cutoff || (acc == cutoff && int32(c) > cutlim) {
  5995  			any = -1
  5996  
  5997  		} else {
  5998  			any = 1
  5999  			acc *= ulong(base)
  6000  			acc += ulong(c)
  6001  		}
  6002  
  6003  		c = *(*byte)(unsafe.Pointer(s))
  6004  		PostIncUintptr(&s, 1)
  6005  	}
  6006  
  6007  	if any < 0 {
  6008  		acc = ULONG_MAX
  6009  		t.setErrno(errno.ERANGE)
  6010  	} else if neg == 1 {
  6011  		acc = -acc
  6012  	}
  6013  
  6014  	if endptr != 0 {
  6015  		if any == 1 {
  6016  			PostDecUintptr(&s, 1)
  6017  			AssignPtrUintptr(endptr, s)
  6018  		} else {
  6019  			AssignPtrUintptr(endptr, nptr)
  6020  		}
  6021  	}
  6022  	return acc
  6023  }
  6024  
  6025  // int __isoc99_sscanf(const char *str, const char *format, ...);
  6026  func X__isoc99_sscanf(t *TLS, str, format, va uintptr) int32 {
  6027  	r := scanf(strings.NewReader(GoString(str)), format, va)
  6028  	// if dmesgs {
  6029  	// 	dmesg("%v: %q %q: %d", origin(1), GoString(str), GoString(format), r)
  6030  	// }
  6031  	return r
  6032  }
  6033  
  6034  // int sscanf(const char *str, const char *format, ...);
  6035  func Xsscanf(t *TLS, str, format, va uintptr) int32 {
  6036  	r := scanf(strings.NewReader(GoString(str)), format, va)
  6037  	// if dmesgs {
  6038  	// 	dmesg("%v: %q %q: %d", origin(1), GoString(str), GoString(format), r)
  6039  	// }
  6040  	return r
  6041  }
  6042  
  6043  func Xstrtod(tls *TLS, s uintptr, p uintptr) float64 { /* strtod.c:22:8: */
  6044  	panic(todo(""))
  6045  }
  6046  
  6047  func Xrint(tls *TLS, x float64) float64 {
  6048  	switch {
  6049  	case x == 0: // also +0 and -0
  6050  		return 0
  6051  	case math.IsInf(x, 0), math.IsNaN(x):
  6052  		return x
  6053  	case x >= math.MinInt64 && x <= math.MaxInt64 && float64(int64(x)) == x:
  6054  		return x
  6055  	case x >= 0:
  6056  		return math.Floor(x + 0.5)
  6057  	default:
  6058  		return math.Ceil(x - 0.5)
  6059  	}
  6060  }
  6061  
  6062  // FILE *fdopen(int fd, const char *mode);
  6063  func Xfdopen(t *TLS, fd int32, mode uintptr) uintptr {
  6064  	panic(todo(""))
  6065  }
  6066  
  6067  // struct tm *_gmtime64( const __time64_t *sourceTime );
  6068  func X_gmtime64(t *TLS, sourceTime uintptr) uintptr {
  6069  	panic(todo(""))
  6070  }
  6071  
  6072  // __time64_t _mktime64(struct tm *timeptr);
  6073  func X_mktime64(t *TLS, timeptr uintptr) time.X__time64_t {
  6074  	return time.X__time64_t(Xmktime(t, timeptr))
  6075  }
  6076  
  6077  // char * gai_strerrorA(int ecode);
  6078  func Xgai_strerrorA(t *TLS, ecode int32) uintptr {
  6079  	panic(todo(""))
  6080  }
  6081  
  6082  // https://github.com/Alexpux/mingw-w64/blob/master/mingw-w64-headers/crt/sys/timeb.h#L69
  6083  //
  6084  // struct __timeb64 {
  6085  //     __time64_t time;
  6086  //     unsigned short millitm;
  6087  //     short timezone;
  6088  //     short dstflag;
  6089  //   };
  6090  
  6091  type __timeb64 struct {
  6092  	time     types.X__time64_t
  6093  	millitm  uint32
  6094  	timezone int16
  6095  	dstflag  int16
  6096  }
  6097  
  6098  // void _ftime64( struct __timeb64 *timeptr );
  6099  func X_ftime64(t *TLS, timeptr uintptr) {
  6100  	tm := gotime.Now()
  6101  	(*__timeb64)(unsafe.Pointer(timeptr)).time = types.X__time64_t(tm.Unix())
  6102  
  6103  	//TODO When Go 1.16 is no more supported
  6104  	// (*__timeb64)(unsafe.Pointer(timeptr)).millitm = uint32(tm.UnixMilli() % 1000)
  6105  
  6106  	(*__timeb64)(unsafe.Pointer(timeptr)).millitm = uint32(int64(tm.Nanosecond()) / 1e6)
  6107  }
  6108  
  6109  func X__ccgo_getMutexType(tls *TLS, m uintptr) int32 { /* pthread_mutex_lock.c:3:5: */
  6110  	return *(*int32)(unsafe.Pointer(m)) & 15
  6111  }
  6112  
  6113  func X__ccgo_pthreadAttrGetDetachState(tls *TLS, a uintptr) int32 { /* pthread_attr_get.c:3:5: */
  6114  	return *(*int32)(unsafe.Pointer(a))
  6115  }
  6116  
  6117  func X__ccgo_pthreadMutexattrGettype(tls *TLS, a uintptr) int32 { /* pthread_attr_get.c:93:5: */
  6118  	return *(*int32)(unsafe.Pointer(a)) & int32(3)
  6119  }
  6120  
  6121  func Xchmod(t *TLS, pathname uintptr, mode int32) int32 {
  6122  	panic(todo("%q %#o", GoString(pathname), mode))
  6123  }
  6124  
  6125  // typedef enum _COMPUTER_NAME_FORMAT {
  6126  //   ComputerNameNetBIOS,
  6127  //   ComputerNameDnsHostname,
  6128  //   ComputerNameDnsDomain,
  6129  //   ComputerNameDnsFullyQualified,
  6130  //   ComputerNamePhysicalNetBIOS,
  6131  //   ComputerNamePhysicalDnsHostname,
  6132  //   ComputerNamePhysicalDnsDomain,
  6133  //   ComputerNamePhysicalDnsFullyQualified,
  6134  //   ComputerNameMax
  6135  // } COMPUTER_NAME_FORMAT;
  6136  
  6137  // BOOL GetComputerNameExW(
  6138  //
  6139  //	[in]      COMPUTER_NAME_FORMAT NameType,
  6140  //	[out]     LPWSTR               lpBuffer,
  6141  //	[in, out] LPDWORD              nSize
  6142  //
  6143  // );
  6144  func XGetComputerNameExW(t *TLS, nameType int32, lpBuffer, nSize uintptr) int32 {
  6145  	r0, _, err := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nameType), lpBuffer, nSize)
  6146  	if err != 0 {
  6147  		t.setErrno(err)
  6148  	}
  6149  	return int32(r0)
  6150  }
  6151  
  6152  // double _copysign(
  6153  //
  6154  //	double x,
  6155  //	double y
  6156  //
  6157  // );
  6158  func X_copysign(t *TLS, x, y float64) float64 { return Xcopysign(t, x, y) }
  6159  
  6160  // int _wtoi(
  6161  //
  6162  //	const wchar_t *str
  6163  //
  6164  // );
  6165  func X_wtoi(t *TLS, str uintptr) int32 {
  6166  	panic(todo(""))
  6167  }
  6168  
  6169  func allocW(t *TLS, v string) (r uintptr) {
  6170  	s := utf16.Encode([]rune(v))
  6171  	p := Xcalloc(t, types.Size_t(len(s)+1), 2)
  6172  	if p == 0 {
  6173  		panic(todo(""))
  6174  	}
  6175  
  6176  	r = p
  6177  	for _, v := range s {
  6178  		*(*uint16)(unsafe.Pointer(p)) = v
  6179  		p += 2
  6180  	}
  6181  	return r
  6182  }
  6183  
  6184  // wchar_t *_wgetenv(
  6185  //
  6186  //	const wchar_t *varname
  6187  //
  6188  // );
  6189  func X_wgetenv(t *TLS, varname uintptr) uintptr {
  6190  	if !wenvValid {
  6191  		bootWinEnviron(t)
  6192  	}
  6193  	k := strings.ToLower(goWideStringNZ(varname))
  6194  	for _, v := range winEnviron[:len(winEnviron)-1] {
  6195  		s := strings.ToLower(goWideStringNZ(v))
  6196  		x := strings.IndexByte(s, '=')
  6197  		if s[:x] == k {
  6198  			// trc("%v: %q -> %q", origin(1), goWideStringNZ(varname), goWideStringNZ(v))
  6199  			return v
  6200  		}
  6201  	}
  6202  
  6203  	// trc("%v: %q -> %q", origin(1), goWideStringNZ(varname), "")
  6204  	return 0
  6205  }
  6206  
  6207  // int _wputenv(
  6208  //
  6209  //	const wchar_t *envstring
  6210  //
  6211  // );
  6212  func X_wputenv(t *TLS, envstring uintptr) int32 {
  6213  	if !wenvValid {
  6214  		bootWinEnviron(t)
  6215  	}
  6216  	s0 := goWideStringNZ(envstring)
  6217  	s := strings.ToLower(s0)
  6218  	x := strings.IndexByte(s, '=')
  6219  	k := s[:x]
  6220  	for i, v := range winEnviron[:len(winEnviron)-1] {
  6221  		s2 := strings.ToLower(goWideStringNZ(v))
  6222  		x := strings.IndexByte(s2, '=')
  6223  		if s2[:x] == k {
  6224  			Xfree(t, v)
  6225  			winEnviron[i] = allocW(t, s0)
  6226  			return 0
  6227  		}
  6228  	}
  6229  
  6230  	np := allocW(t, s0)
  6231  	winEnviron = winEnviron[:len(winEnviron)-1]
  6232  	winEnviron = append(winEnviron, np, 0)
  6233  	wenviron = uintptr(unsafe.Pointer(&winEnviron[0]))
  6234  	return 0
  6235  }
  6236  
  6237  func bootWinEnviron(t *TLS) {
  6238  	winEnviron = winEnviron[:0]
  6239  	p := Environ()
  6240  	for {
  6241  		q := *(*uintptr)(unsafe.Pointer(p))
  6242  		p += unsafe.Sizeof(uintptr(0))
  6243  		if q == 0 {
  6244  			break
  6245  		}
  6246  
  6247  		s := GoString(q)
  6248  		// trc("%v: %q", origin(1), s)
  6249  		r := allocW(t, s)
  6250  		winEnviron = append(winEnviron, r)
  6251  	}
  6252  	wenviron = uintptr(unsafe.Pointer(&winEnviron[0]))
  6253  	wenvValid = true
  6254  }
  6255  
  6256  func Xfabsl(t *TLS, x float64) float64 { return math.Abs(x) }
  6257  
  6258  func X__stdio_common_vfprintf(t *TLS, args ...interface{}) int32     { panic("TODO") }
  6259  func X__stdio_common_vfprintf_p(t *TLS, args ...interface{}) int32   { panic("TODO") }
  6260  func X__stdio_common_vfprintf_s(t *TLS, args ...interface{}) int32   { panic("TODO") }
  6261  func X__stdio_common_vfscanf(t *TLS, args ...interface{}) int32      { panic("TODO") }
  6262  func X__stdio_common_vfwprintf_s(t *TLS, args ...interface{}) int32  { panic("TODO") }
  6263  func X__stdio_common_vfwscanf(t *TLS, args ...interface{}) int32     { panic("TODO") }
  6264  func X__stdio_common_vsnprintf_s(t *TLS, args ...interface{}) int32  { panic("TODO") }
  6265  func X__stdio_common_vsnwprintf_s(t *TLS, args ...interface{}) int32 { panic("TODO") }
  6266  func X__stdio_common_vsprintf(t *TLS, args ...interface{}) int32     { panic("TODO") }
  6267  func X__stdio_common_vsprintf_p(t *TLS, args ...interface{}) int32   { panic("TODO") }
  6268  func X__stdio_common_vsprintf_s(t *TLS, args ...interface{}) int32   { panic("TODO") }
  6269  func X__stdio_common_vsscanf(t *TLS, args ...interface{}) int32      { panic("TODO") }
  6270  func X__stdio_common_vswprintf(t *TLS, args ...interface{}) int32    { panic("TODO") }
  6271  func X__stdio_common_vswprintf_s(t *TLS, args ...interface{}) int32  { panic("TODO") }
  6272  func X__stdio_common_vswscanf(t *TLS, args ...interface{}) int32     { panic("TODO") }