...
Run Format

Source file src/syscall/syscall_windows.go

Documentation: syscall

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Windows system calls.
     6  
     7  package syscall
     8  
     9  import (
    10  	errorspkg "errors"
    11  	"internal/race"
    12  	"sync"
    13  	"unicode/utf16"
    14  	"unsafe"
    15  )
    16  
    17  type Handle uintptr
    18  
    19  const InvalidHandle = ^Handle(0)
    20  
    21  // StringToUTF16 returns the UTF-16 encoding of the UTF-8 string s,
    22  // with a terminating NUL added. If s contains a NUL byte this
    23  // function panics instead of returning an error.
    24  //
    25  // Deprecated: Use UTF16FromString instead.
    26  func StringToUTF16(s string) []uint16 {
    27  	a, err := UTF16FromString(s)
    28  	if err != nil {
    29  		panic("syscall: string with NUL passed to StringToUTF16")
    30  	}
    31  	return a
    32  }
    33  
    34  // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
    35  // s, with a terminating NUL added. If s contains a NUL byte at any
    36  // location, it returns (nil, EINVAL).
    37  func UTF16FromString(s string) ([]uint16, error) {
    38  	for i := 0; i < len(s); i++ {
    39  		if s[i] == 0 {
    40  			return nil, EINVAL
    41  		}
    42  	}
    43  	return utf16.Encode([]rune(s + "\x00")), nil
    44  }
    45  
    46  // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
    47  // with a terminating NUL removed.
    48  func UTF16ToString(s []uint16) string {
    49  	for i, v := range s {
    50  		if v == 0 {
    51  			s = s[0:i]
    52  			break
    53  		}
    54  	}
    55  	return string(utf16.Decode(s))
    56  }
    57  
    58  // StringToUTF16Ptr returns pointer to the UTF-16 encoding of
    59  // the UTF-8 string s, with a terminating NUL added. If s
    60  // contains a NUL byte this function panics instead of
    61  // returning an error.
    62  //
    63  // Deprecated: Use UTF16PtrFromString instead.
    64  func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
    65  
    66  // UTF16PtrFromString returns pointer to the UTF-16 encoding of
    67  // the UTF-8 string s, with a terminating NUL added. If s
    68  // contains a NUL byte at any location, it returns (nil, EINVAL).
    69  func UTF16PtrFromString(s string) (*uint16, error) {
    70  	a, err := UTF16FromString(s)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	return &a[0], nil
    75  }
    76  
    77  // Errno is the Windows error number.
    78  type Errno uintptr
    79  
    80  func langid(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) }
    81  
    82  // FormatMessage is deprecated (msgsrc should be uintptr, not uint32, but can
    83  // not be changed due to the Go 1 compatibility guarantee).
    84  //
    85  // Deprecated: Use FormatMessage from golang.org/x/sys/windows instead.
    86  func FormatMessage(flags uint32, msgsrc uint32, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) {
    87  	return formatMessage(flags, uintptr(msgsrc), msgid, langid, buf, args)
    88  }
    89  
    90  func (e Errno) Error() string {
    91  	// deal with special go errors
    92  	idx := int(e - APPLICATION_ERROR)
    93  	if 0 <= idx && idx < len(errors) {
    94  		return errors[idx]
    95  	}
    96  	// ask windows for the remaining errors
    97  	var flags uint32 = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_IGNORE_INSERTS
    98  	b := make([]uint16, 300)
    99  	n, err := formatMessage(flags, 0, uint32(e), langid(LANG_ENGLISH, SUBLANG_ENGLISH_US), b, nil)
   100  	if err != nil {
   101  		n, err = formatMessage(flags, 0, uint32(e), 0, b, nil)
   102  		if err != nil {
   103  			return "winapi error #" + itoa(int(e))
   104  		}
   105  	}
   106  	// trim terminating \r and \n
   107  	for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
   108  	}
   109  	return string(utf16.Decode(b[:n]))
   110  }
   111  
   112  func (e Errno) Temporary() bool {
   113  	return e == EINTR || e == EMFILE || e.Timeout()
   114  }
   115  
   116  func (e Errno) Timeout() bool {
   117  	return e == EAGAIN || e == EWOULDBLOCK || e == ETIMEDOUT
   118  }
   119  
   120  // Implemented in runtime/syscall_windows.go.
   121  func compileCallback(fn interface{}, cleanstack bool) uintptr
   122  
   123  // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
   124  // This is useful when interoperating with Windows code requiring callbacks.
   125  // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   126  func NewCallback(fn interface{}) uintptr {
   127  	return compileCallback(fn, true)
   128  }
   129  
   130  // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
   131  // This is useful when interoperating with Windows code requiring callbacks.
   132  // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   133  func NewCallbackCDecl(fn interface{}) uintptr {
   134  	return compileCallback(fn, false)
   135  }
   136  
   137  // windows api calls
   138  
   139  //sys	GetLastError() (lasterr error)
   140  //sys	LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
   141  //sys	FreeLibrary(handle Handle) (err error)
   142  //sys	GetProcAddress(module Handle, procname string) (proc uintptr, err error)
   143  //sys	GetVersion() (ver uint32, err error)
   144  //sys	formatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
   145  //sys	ExitProcess(exitcode uint32)
   146  //sys	CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
   147  //sys	ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
   148  //sys	WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
   149  //sys	SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
   150  //sys	CloseHandle(handle Handle) (err error)
   151  //sys	GetStdHandle(stdhandle int) (handle Handle, err error) [failretval==InvalidHandle]
   152  //sys	findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
   153  //sys	findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
   154  //sys	FindClose(handle Handle) (err error)
   155  //sys	GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
   156  //sys	GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
   157  //sys	SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
   158  //sys	CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
   159  //sys	RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
   160  //sys	DeleteFile(path *uint16) (err error) = DeleteFileW
   161  //sys	MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
   162  //sys	GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
   163  //sys	SetEndOfFile(handle Handle) (err error)
   164  //sys	GetSystemTimeAsFileTime(time *Filetime)
   165  //sys	GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
   166  //sys	CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error)
   167  //sys	GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error)
   168  //sys	PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error)
   169  //sys	CancelIo(s Handle) (err error)
   170  //sys	CancelIoEx(s Handle, o *Overlapped) (err error)
   171  //sys	CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW
   172  //sys	CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = advapi32.CreateProcessAsUserW
   173  //sys	OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error)
   174  //sys	TerminateProcess(handle Handle, exitcode uint32) (err error)
   175  //sys	GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
   176  //sys	GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW
   177  //sys	GetCurrentProcess() (pseudoHandle Handle, err error)
   178  //sys	GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
   179  //sys	DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
   180  //sys	WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
   181  //sys	GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
   182  //sys	CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
   183  //sys	GetFileType(filehandle Handle) (n uint32, err error)
   184  //sys	CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
   185  //sys	CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
   186  //sys	CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
   187  //sys	GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
   188  //sys	FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
   189  //sys	GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
   190  //sys	SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
   191  //sys	SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
   192  //sys	GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
   193  //sys	SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
   194  //sys	GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
   195  //sys	GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
   196  //sys	CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
   197  //sys	LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
   198  //sys	SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
   199  //sys	FlushFileBuffers(handle Handle) (err error)
   200  //sys	GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
   201  //sys	GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
   202  //sys	GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
   203  //sys	CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW
   204  //sys	MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
   205  //sys	UnmapViewOfFile(addr uintptr) (err error)
   206  //sys	FlushViewOfFile(addr uintptr, length uintptr) (err error)
   207  //sys	VirtualLock(addr uintptr, length uintptr) (err error)
   208  //sys	VirtualUnlock(addr uintptr, length uintptr) (err error)
   209  //sys	TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
   210  //sys	ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
   211  //sys	CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
   212  //sys   CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore
   213  //sys	CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
   214  //sys   CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
   215  //sys	CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
   216  //sys   CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
   217  //sys   CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
   218  //sys   CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
   219  //sys   CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
   220  //sys   CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
   221  //sys	RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
   222  //sys	RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
   223  //sys	RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW
   224  //sys	RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
   225  //sys	RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
   226  //sys	getCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
   227  //sys	GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
   228  //sys	WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
   229  //sys	ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
   230  //sys	CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
   231  //sys	Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
   232  //sys	Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
   233  //sys	DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
   234  // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
   235  //sys	CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
   236  //sys	CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
   237  
   238  // syscall interface implementation for other packages
   239  
   240  func makeInheritSa() *SecurityAttributes {
   241  	var sa SecurityAttributes
   242  	sa.Length = uint32(unsafe.Sizeof(sa))
   243  	sa.InheritHandle = 1
   244  	return &sa
   245  }
   246  
   247  func Open(path string, mode int, perm uint32) (fd Handle, err error) {
   248  	if len(path) == 0 {
   249  		return InvalidHandle, ERROR_FILE_NOT_FOUND
   250  	}
   251  	pathp, err := UTF16PtrFromString(path)
   252  	if err != nil {
   253  		return InvalidHandle, err
   254  	}
   255  	var access uint32
   256  	switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
   257  	case O_RDONLY:
   258  		access = GENERIC_READ
   259  	case O_WRONLY:
   260  		access = GENERIC_WRITE
   261  	case O_RDWR:
   262  		access = GENERIC_READ | GENERIC_WRITE
   263  	}
   264  	if mode&O_CREAT != 0 {
   265  		access |= GENERIC_WRITE
   266  	}
   267  	if mode&O_APPEND != 0 {
   268  		access &^= GENERIC_WRITE
   269  		access |= FILE_APPEND_DATA
   270  	}
   271  	sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
   272  	var sa *SecurityAttributes
   273  	if mode&O_CLOEXEC == 0 {
   274  		sa = makeInheritSa()
   275  	}
   276  	var createmode uint32
   277  	switch {
   278  	case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
   279  		createmode = CREATE_NEW
   280  	case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
   281  		createmode = CREATE_ALWAYS
   282  	case mode&O_CREAT == O_CREAT:
   283  		createmode = OPEN_ALWAYS
   284  	case mode&O_TRUNC == O_TRUNC:
   285  		createmode = TRUNCATE_EXISTING
   286  	default:
   287  		createmode = OPEN_EXISTING
   288  	}
   289  	h, e := CreateFile(pathp, access, sharemode, sa, createmode, FILE_ATTRIBUTE_NORMAL, 0)
   290  	return h, e
   291  }
   292  
   293  func Read(fd Handle, p []byte) (n int, err error) {
   294  	var done uint32
   295  	e := ReadFile(fd, p, &done, nil)
   296  	if e != nil {
   297  		if e == ERROR_BROKEN_PIPE {
   298  			// NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
   299  			return 0, nil
   300  		}
   301  		return 0, e
   302  	}
   303  	if race.Enabled {
   304  		if done > 0 {
   305  			race.WriteRange(unsafe.Pointer(&p[0]), int(done))
   306  		}
   307  		race.Acquire(unsafe.Pointer(&ioSync))
   308  	}
   309  	if msanenabled && done > 0 {
   310  		msanWrite(unsafe.Pointer(&p[0]), int(done))
   311  	}
   312  	return int(done), nil
   313  }
   314  
   315  func Write(fd Handle, p []byte) (n int, err error) {
   316  	if race.Enabled {
   317  		race.ReleaseMerge(unsafe.Pointer(&ioSync))
   318  	}
   319  	var done uint32
   320  	e := WriteFile(fd, p, &done, nil)
   321  	if e != nil {
   322  		return 0, e
   323  	}
   324  	if race.Enabled && done > 0 {
   325  		race.ReadRange(unsafe.Pointer(&p[0]), int(done))
   326  	}
   327  	if msanenabled && done > 0 {
   328  		msanRead(unsafe.Pointer(&p[0]), int(done))
   329  	}
   330  	return int(done), nil
   331  }
   332  
   333  var ioSync int64
   334  
   335  var procSetFilePointerEx = modkernel32.NewProc("SetFilePointerEx")
   336  
   337  const ptrSize = unsafe.Sizeof(uintptr(0))
   338  
   339  // setFilePointerEx calls SetFilePointerEx.
   340  // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365542(v=vs.85).aspx
   341  func setFilePointerEx(handle Handle, distToMove int64, newFilePointer *int64, whence uint32) error {
   342  	var e1 Errno
   343  	if ptrSize == 8 {
   344  		_, _, e1 = Syscall6(procSetFilePointerEx.Addr(), 4, uintptr(handle), uintptr(distToMove), uintptr(unsafe.Pointer(newFilePointer)), uintptr(whence), 0, 0)
   345  	} else {
   346  		// distToMove is a LARGE_INTEGER:
   347  		// https://msdn.microsoft.com/en-us/library/windows/desktop/aa383713(v=vs.85).aspx
   348  		_, _, e1 = Syscall6(procSetFilePointerEx.Addr(), 5, uintptr(handle), uintptr(distToMove), uintptr(distToMove>>32), uintptr(unsafe.Pointer(newFilePointer)), uintptr(whence), 0)
   349  	}
   350  	if e1 != 0 {
   351  		return errnoErr(e1)
   352  	}
   353  	return nil
   354  }
   355  
   356  func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
   357  	var w uint32
   358  	switch whence {
   359  	case 0:
   360  		w = FILE_BEGIN
   361  	case 1:
   362  		w = FILE_CURRENT
   363  	case 2:
   364  		w = FILE_END
   365  	}
   366  	// use GetFileType to check pipe, pipe can't do seek
   367  	ft, _ := GetFileType(fd)
   368  	if ft == FILE_TYPE_PIPE {
   369  		return 0, ESPIPE
   370  	}
   371  	err = setFilePointerEx(fd, offset, &newoffset, w)
   372  	return
   373  }
   374  
   375  func Close(fd Handle) (err error) {
   376  	return CloseHandle(fd)
   377  }
   378  
   379  var (
   380  	Stdin  = getStdHandle(STD_INPUT_HANDLE)
   381  	Stdout = getStdHandle(STD_OUTPUT_HANDLE)
   382  	Stderr = getStdHandle(STD_ERROR_HANDLE)
   383  )
   384  
   385  func getStdHandle(h int) (fd Handle) {
   386  	r, _ := GetStdHandle(h)
   387  	CloseOnExec(r)
   388  	return r
   389  }
   390  
   391  const ImplementsGetwd = true
   392  
   393  func Getwd() (wd string, err error) {
   394  	b := make([]uint16, 300)
   395  	n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
   396  	if e != nil {
   397  		return "", e
   398  	}
   399  	return string(utf16.Decode(b[0:n])), nil
   400  }
   401  
   402  func Chdir(path string) (err error) {
   403  	pathp, err := UTF16PtrFromString(path)
   404  	if err != nil {
   405  		return err
   406  	}
   407  	return SetCurrentDirectory(pathp)
   408  }
   409  
   410  func Mkdir(path string, mode uint32) (err error) {
   411  	pathp, err := UTF16PtrFromString(path)
   412  	if err != nil {
   413  		return err
   414  	}
   415  	return CreateDirectory(pathp, nil)
   416  }
   417  
   418  func Rmdir(path string) (err error) {
   419  	pathp, err := UTF16PtrFromString(path)
   420  	if err != nil {
   421  		return err
   422  	}
   423  	return RemoveDirectory(pathp)
   424  }
   425  
   426  func Unlink(path string) (err error) {
   427  	pathp, err := UTF16PtrFromString(path)
   428  	if err != nil {
   429  		return err
   430  	}
   431  	return DeleteFile(pathp)
   432  }
   433  
   434  func Rename(oldpath, newpath string) (err error) {
   435  	from, err := UTF16PtrFromString(oldpath)
   436  	if err != nil {
   437  		return err
   438  	}
   439  	to, err := UTF16PtrFromString(newpath)
   440  	if err != nil {
   441  		return err
   442  	}
   443  	return MoveFile(from, to)
   444  }
   445  
   446  func ComputerName() (name string, err error) {
   447  	var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
   448  	b := make([]uint16, n)
   449  	e := GetComputerName(&b[0], &n)
   450  	if e != nil {
   451  		return "", e
   452  	}
   453  	return string(utf16.Decode(b[0:n])), nil
   454  }
   455  
   456  func Ftruncate(fd Handle, length int64) (err error) {
   457  	curoffset, e := Seek(fd, 0, 1)
   458  	if e != nil {
   459  		return e
   460  	}
   461  	defer Seek(fd, curoffset, 0)
   462  	_, e = Seek(fd, length, 0)
   463  	if e != nil {
   464  		return e
   465  	}
   466  	e = SetEndOfFile(fd)
   467  	if e != nil {
   468  		return e
   469  	}
   470  	return nil
   471  }
   472  
   473  func Gettimeofday(tv *Timeval) (err error) {
   474  	var ft Filetime
   475  	GetSystemTimeAsFileTime(&ft)
   476  	*tv = NsecToTimeval(ft.Nanoseconds())
   477  	return nil
   478  }
   479  
   480  func Pipe(p []Handle) (err error) {
   481  	if len(p) != 2 {
   482  		return EINVAL
   483  	}
   484  	var r, w Handle
   485  	e := CreatePipe(&r, &w, makeInheritSa(), 0)
   486  	if e != nil {
   487  		return e
   488  	}
   489  	p[0] = r
   490  	p[1] = w
   491  	return nil
   492  }
   493  
   494  func Utimes(path string, tv []Timeval) (err error) {
   495  	if len(tv) != 2 {
   496  		return EINVAL
   497  	}
   498  	pathp, e := UTF16PtrFromString(path)
   499  	if e != nil {
   500  		return e
   501  	}
   502  	h, e := CreateFile(pathp,
   503  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   504  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   505  	if e != nil {
   506  		return e
   507  	}
   508  	defer Close(h)
   509  	a := NsecToFiletime(tv[0].Nanoseconds())
   510  	w := NsecToFiletime(tv[1].Nanoseconds())
   511  	return SetFileTime(h, nil, &a, &w)
   512  }
   513  
   514  func UtimesNano(path string, ts []Timespec) (err error) {
   515  	if len(ts) != 2 {
   516  		return EINVAL
   517  	}
   518  	pathp, e := UTF16PtrFromString(path)
   519  	if e != nil {
   520  		return e
   521  	}
   522  	h, e := CreateFile(pathp,
   523  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   524  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   525  	if e != nil {
   526  		return e
   527  	}
   528  	defer Close(h)
   529  	a := NsecToFiletime(TimespecToNsec(ts[0]))
   530  	w := NsecToFiletime(TimespecToNsec(ts[1]))
   531  	return SetFileTime(h, nil, &a, &w)
   532  }
   533  
   534  func Fsync(fd Handle) (err error) {
   535  	return FlushFileBuffers(fd)
   536  }
   537  
   538  func Chmod(path string, mode uint32) (err error) {
   539  	if mode == 0 {
   540  		return EINVAL
   541  	}
   542  	p, e := UTF16PtrFromString(path)
   543  	if e != nil {
   544  		return e
   545  	}
   546  	attrs, e := GetFileAttributes(p)
   547  	if e != nil {
   548  		return e
   549  	}
   550  	if mode&S_IWRITE != 0 {
   551  		attrs &^= FILE_ATTRIBUTE_READONLY
   552  	} else {
   553  		attrs |= FILE_ATTRIBUTE_READONLY
   554  	}
   555  	return SetFileAttributes(p, attrs)
   556  }
   557  
   558  func LoadCancelIoEx() error {
   559  	return procCancelIoEx.Find()
   560  }
   561  
   562  func LoadSetFileCompletionNotificationModes() error {
   563  	return procSetFileCompletionNotificationModes.Find()
   564  }
   565  
   566  // net api calls
   567  
   568  const socket_error = uintptr(^uint32(0))
   569  
   570  //sys	WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
   571  //sys	WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
   572  //sys	WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl
   573  //sys	socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
   574  //sys	Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
   575  //sys	Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
   576  //sys	bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
   577  //sys	connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
   578  //sys	getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
   579  //sys	getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
   580  //sys	listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
   581  //sys	shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
   582  //sys	Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
   583  //sys	AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
   584  //sys	GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
   585  //sys	WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
   586  //sys	WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
   587  //sys	WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32,  from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom
   588  //sys	WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32,  overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo
   589  //sys	GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
   590  //sys	GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
   591  //sys	Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
   592  //sys	GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
   593  //sys	DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
   594  //sys	DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
   595  //sys	DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
   596  //sys	GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
   597  //sys	FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
   598  //sys	GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
   599  //sys	GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
   600  //sys	SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
   601  //sys	WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
   602  
   603  // For testing: clients can set this flag to force
   604  // creation of IPv6 sockets to return EAFNOSUPPORT.
   605  var SocketDisableIPv6 bool
   606  
   607  type RawSockaddrInet4 struct {
   608  	Family uint16
   609  	Port   uint16
   610  	Addr   [4]byte /* in_addr */
   611  	Zero   [8]uint8
   612  }
   613  
   614  type RawSockaddrInet6 struct {
   615  	Family   uint16
   616  	Port     uint16
   617  	Flowinfo uint32
   618  	Addr     [16]byte /* in6_addr */
   619  	Scope_id uint32
   620  }
   621  
   622  type RawSockaddr struct {
   623  	Family uint16
   624  	Data   [14]int8
   625  }
   626  
   627  type RawSockaddrAny struct {
   628  	Addr RawSockaddr
   629  	Pad  [96]int8
   630  }
   631  
   632  type Sockaddr interface {
   633  	sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
   634  }
   635  
   636  type SockaddrInet4 struct {
   637  	Port int
   638  	Addr [4]byte
   639  	raw  RawSockaddrInet4
   640  }
   641  
   642  func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
   643  	if sa.Port < 0 || sa.Port > 0xFFFF {
   644  		return nil, 0, EINVAL
   645  	}
   646  	sa.raw.Family = AF_INET
   647  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   648  	p[0] = byte(sa.Port >> 8)
   649  	p[1] = byte(sa.Port)
   650  	for i := 0; i < len(sa.Addr); i++ {
   651  		sa.raw.Addr[i] = sa.Addr[i]
   652  	}
   653  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   654  }
   655  
   656  type SockaddrInet6 struct {
   657  	Port   int
   658  	ZoneId uint32
   659  	Addr   [16]byte
   660  	raw    RawSockaddrInet6
   661  }
   662  
   663  func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
   664  	if sa.Port < 0 || sa.Port > 0xFFFF {
   665  		return nil, 0, EINVAL
   666  	}
   667  	sa.raw.Family = AF_INET6
   668  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   669  	p[0] = byte(sa.Port >> 8)
   670  	p[1] = byte(sa.Port)
   671  	sa.raw.Scope_id = sa.ZoneId
   672  	for i := 0; i < len(sa.Addr); i++ {
   673  		sa.raw.Addr[i] = sa.Addr[i]
   674  	}
   675  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   676  }
   677  
   678  type SockaddrUnix struct {
   679  	Name string
   680  }
   681  
   682  func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
   683  	// TODO(brainman): implement SockaddrUnix.sockaddr()
   684  	return nil, 0, EWINDOWS
   685  }
   686  
   687  func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
   688  	switch rsa.Addr.Family {
   689  	case AF_UNIX:
   690  		return nil, EWINDOWS
   691  
   692  	case AF_INET:
   693  		pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
   694  		sa := new(SockaddrInet4)
   695  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   696  		sa.Port = int(p[0])<<8 + int(p[1])
   697  		for i := 0; i < len(sa.Addr); i++ {
   698  			sa.Addr[i] = pp.Addr[i]
   699  		}
   700  		return sa, nil
   701  
   702  	case AF_INET6:
   703  		pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
   704  		sa := new(SockaddrInet6)
   705  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   706  		sa.Port = int(p[0])<<8 + int(p[1])
   707  		sa.ZoneId = pp.Scope_id
   708  		for i := 0; i < len(sa.Addr); i++ {
   709  			sa.Addr[i] = pp.Addr[i]
   710  		}
   711  		return sa, nil
   712  	}
   713  	return nil, EAFNOSUPPORT
   714  }
   715  
   716  func Socket(domain, typ, proto int) (fd Handle, err error) {
   717  	if domain == AF_INET6 && SocketDisableIPv6 {
   718  		return InvalidHandle, EAFNOSUPPORT
   719  	}
   720  	return socket(int32(domain), int32(typ), int32(proto))
   721  }
   722  
   723  func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
   724  	v := int32(value)
   725  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
   726  }
   727  
   728  func Bind(fd Handle, sa Sockaddr) (err error) {
   729  	ptr, n, err := sa.sockaddr()
   730  	if err != nil {
   731  		return err
   732  	}
   733  	return bind(fd, ptr, n)
   734  }
   735  
   736  func Connect(fd Handle, sa Sockaddr) (err error) {
   737  	ptr, n, err := sa.sockaddr()
   738  	if err != nil {
   739  		return err
   740  	}
   741  	return connect(fd, ptr, n)
   742  }
   743  
   744  func Getsockname(fd Handle) (sa Sockaddr, err error) {
   745  	var rsa RawSockaddrAny
   746  	l := int32(unsafe.Sizeof(rsa))
   747  	if err = getsockname(fd, &rsa, &l); err != nil {
   748  		return
   749  	}
   750  	return rsa.Sockaddr()
   751  }
   752  
   753  func Getpeername(fd Handle) (sa Sockaddr, err error) {
   754  	var rsa RawSockaddrAny
   755  	l := int32(unsafe.Sizeof(rsa))
   756  	if err = getpeername(fd, &rsa, &l); err != nil {
   757  		return
   758  	}
   759  	return rsa.Sockaddr()
   760  }
   761  
   762  func Listen(s Handle, n int) (err error) {
   763  	return listen(s, int32(n))
   764  }
   765  
   766  func Shutdown(fd Handle, how int) (err error) {
   767  	return shutdown(fd, int32(how))
   768  }
   769  
   770  func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
   771  	rsa, l, err := to.sockaddr()
   772  	if err != nil {
   773  		return err
   774  	}
   775  	return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)
   776  }
   777  
   778  func LoadGetAddrInfo() error {
   779  	return procGetAddrInfoW.Find()
   780  }
   781  
   782  var connectExFunc struct {
   783  	once sync.Once
   784  	addr uintptr
   785  	err  error
   786  }
   787  
   788  func LoadConnectEx() error {
   789  	connectExFunc.once.Do(func() {
   790  		var s Handle
   791  		s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
   792  		if connectExFunc.err != nil {
   793  			return
   794  		}
   795  		defer CloseHandle(s)
   796  		var n uint32
   797  		connectExFunc.err = WSAIoctl(s,
   798  			SIO_GET_EXTENSION_FUNCTION_POINTER,
   799  			(*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
   800  			uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
   801  			(*byte)(unsafe.Pointer(&connectExFunc.addr)),
   802  			uint32(unsafe.Sizeof(connectExFunc.addr)),
   803  			&n, nil, 0)
   804  	})
   805  	return connectExFunc.err
   806  }
   807  
   808  func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
   809  	r1, _, e1 := Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0)
   810  	if r1 == 0 {
   811  		if e1 != 0 {
   812  			err = error(e1)
   813  		} else {
   814  			err = EINVAL
   815  		}
   816  	}
   817  	return
   818  }
   819  
   820  func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
   821  	err := LoadConnectEx()
   822  	if err != nil {
   823  		return errorspkg.New("failed to find ConnectEx: " + err.Error())
   824  	}
   825  	ptr, n, err := sa.sockaddr()
   826  	if err != nil {
   827  		return err
   828  	}
   829  	return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
   830  }
   831  
   832  // Invented structures to support what package os expects.
   833  type Rusage struct {
   834  	CreationTime Filetime
   835  	ExitTime     Filetime
   836  	KernelTime   Filetime
   837  	UserTime     Filetime
   838  }
   839  
   840  type WaitStatus struct {
   841  	ExitCode uint32
   842  }
   843  
   844  func (w WaitStatus) Exited() bool { return true }
   845  
   846  func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
   847  
   848  func (w WaitStatus) Signal() Signal { return -1 }
   849  
   850  func (w WaitStatus) CoreDump() bool { return false }
   851  
   852  func (w WaitStatus) Stopped() bool { return false }
   853  
   854  func (w WaitStatus) Continued() bool { return false }
   855  
   856  func (w WaitStatus) StopSignal() Signal { return -1 }
   857  
   858  func (w WaitStatus) Signaled() bool { return false }
   859  
   860  func (w WaitStatus) TrapCause() int { return -1 }
   861  
   862  // Timespec is an invented structure on Windows, but here for
   863  // consistency with the syscall package for other operating systems.
   864  type Timespec struct {
   865  	Sec  int64
   866  	Nsec int64
   867  }
   868  
   869  func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
   870  
   871  func NsecToTimespec(nsec int64) (ts Timespec) {
   872  	ts.Sec = nsec / 1e9
   873  	ts.Nsec = nsec % 1e9
   874  	return
   875  }
   876  
   877  // TODO(brainman): fix all needed for net
   878  
   879  func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, EWINDOWS }
   880  func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
   881  	return 0, nil, EWINDOWS
   882  }
   883  func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error)       { return EWINDOWS }
   884  func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return EWINDOWS }
   885  
   886  // The Linger struct is wrong but we only noticed after Go 1.
   887  // sysLinger is the real system call structure.
   888  
   889  // BUG(brainman): The definition of Linger is not appropriate for direct use
   890  // with Setsockopt and Getsockopt.
   891  // Use SetsockoptLinger instead.
   892  
   893  type Linger struct {
   894  	Onoff  int32
   895  	Linger int32
   896  }
   897  
   898  type sysLinger struct {
   899  	Onoff  uint16
   900  	Linger uint16
   901  }
   902  
   903  type IPMreq struct {
   904  	Multiaddr [4]byte /* in_addr */
   905  	Interface [4]byte /* in_addr */
   906  }
   907  
   908  type IPv6Mreq struct {
   909  	Multiaddr [16]byte /* in6_addr */
   910  	Interface uint32
   911  }
   912  
   913  func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, EWINDOWS }
   914  
   915  func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
   916  	sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
   917  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
   918  }
   919  
   920  func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
   921  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
   922  }
   923  func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
   924  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
   925  }
   926  func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return EWINDOWS }
   927  
   928  func Getpid() (pid int) { return int(getCurrentProcessId()) }
   929  
   930  func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
   931  	// NOTE(rsc): The Win32finddata struct is wrong for the system call:
   932  	// the two paths are each one uint16 short. Use the correct struct,
   933  	// a win32finddata1, and then copy the results out.
   934  	// There is no loss of expressivity here, because the final
   935  	// uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
   936  	// For Go 1.1, we might avoid the allocation of win32finddata1 here
   937  	// by adding a final Bug [2]uint16 field to the struct and then
   938  	// adjusting the fields in the result directly.
   939  	var data1 win32finddata1
   940  	handle, err = findFirstFile1(name, &data1)
   941  	if err == nil {
   942  		copyFindData(data, &data1)
   943  	}
   944  	return
   945  }
   946  
   947  func FindNextFile(handle Handle, data *Win32finddata) (err error) {
   948  	var data1 win32finddata1
   949  	err = findNextFile1(handle, &data1)
   950  	if err == nil {
   951  		copyFindData(data, &data1)
   952  	}
   953  	return
   954  }
   955  
   956  func getProcessEntry(pid int) (*ProcessEntry32, error) {
   957  	snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
   958  	if err != nil {
   959  		return nil, err
   960  	}
   961  	defer CloseHandle(snapshot)
   962  	var procEntry ProcessEntry32
   963  	procEntry.Size = uint32(unsafe.Sizeof(procEntry))
   964  	if err = Process32First(snapshot, &procEntry); err != nil {
   965  		return nil, err
   966  	}
   967  	for {
   968  		if procEntry.ProcessID == uint32(pid) {
   969  			return &procEntry, nil
   970  		}
   971  		err = Process32Next(snapshot, &procEntry)
   972  		if err != nil {
   973  			return nil, err
   974  		}
   975  	}
   976  }
   977  
   978  func Getppid() (ppid int) {
   979  	pe, err := getProcessEntry(Getpid())
   980  	if err != nil {
   981  		return -1
   982  	}
   983  	return int(pe.ParentProcessID)
   984  }
   985  
   986  // TODO(brainman): fix all needed for os
   987  func Fchdir(fd Handle) (err error)             { return EWINDOWS }
   988  func Link(oldpath, newpath string) (err error) { return EWINDOWS }
   989  func Symlink(path, link string) (err error)    { return EWINDOWS }
   990  
   991  func Fchmod(fd Handle, mode uint32) (err error)        { return EWINDOWS }
   992  func Chown(path string, uid int, gid int) (err error)  { return EWINDOWS }
   993  func Lchown(path string, uid int, gid int) (err error) { return EWINDOWS }
   994  func Fchown(fd Handle, uid int, gid int) (err error)   { return EWINDOWS }
   995  
   996  func Getuid() (uid int)                  { return -1 }
   997  func Geteuid() (euid int)                { return -1 }
   998  func Getgid() (gid int)                  { return -1 }
   999  func Getegid() (egid int)                { return -1 }
  1000  func Getgroups() (gids []int, err error) { return nil, EWINDOWS }
  1001  
  1002  type Signal int
  1003  
  1004  func (s Signal) Signal() {}
  1005  
  1006  func (s Signal) String() string {
  1007  	if 0 <= s && int(s) < len(signals) {
  1008  		str := signals[s]
  1009  		if str != "" {
  1010  			return str
  1011  		}
  1012  	}
  1013  	return "signal " + itoa(int(s))
  1014  }
  1015  
  1016  func LoadCreateSymbolicLink() error {
  1017  	return procCreateSymbolicLinkW.Find()
  1018  }
  1019  
  1020  // Readlink returns the destination of the named symbolic link.
  1021  func Readlink(path string, buf []byte) (n int, err error) {
  1022  	fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
  1023  		FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
  1024  	if err != nil {
  1025  		return -1, err
  1026  	}
  1027  	defer CloseHandle(fd)
  1028  
  1029  	rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  1030  	var bytesReturned uint32
  1031  	err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
  1032  	if err != nil {
  1033  		return -1, err
  1034  	}
  1035  
  1036  	rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
  1037  	var s string
  1038  	switch rdb.ReparseTag {
  1039  	case IO_REPARSE_TAG_SYMLINK:
  1040  		data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1041  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1042  		s = UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
  1043  		if data.Flags&_SYMLINK_FLAG_RELATIVE == 0 {
  1044  			if len(s) >= 4 && s[:4] == `\??\` {
  1045  				s = s[4:]
  1046  				switch {
  1047  				case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar
  1048  					// do nothing
  1049  				case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar
  1050  					s = `\\` + s[4:]
  1051  				default:
  1052  					// unexpected; do nothing
  1053  				}
  1054  			} else {
  1055  				// unexpected; do nothing
  1056  			}
  1057  		}
  1058  	case _IO_REPARSE_TAG_MOUNT_POINT:
  1059  		data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1060  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1061  		s = UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
  1062  		if len(s) >= 4 && s[:4] == `\??\` { // \??\C:\foo\bar
  1063  			s = s[4:]
  1064  		} else {
  1065  			// unexpected; do nothing
  1066  		}
  1067  	default:
  1068  		// the path is not a symlink or junction but another type of reparse
  1069  		// point
  1070  		return -1, ENOENT
  1071  	}
  1072  	n = copy(buf, []byte(s))
  1073  
  1074  	return n, nil
  1075  }
  1076  

View as plain text