syscall_windows.go 46 KB

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