A lightweight mechanism to provide an *instant kickstart* to a Go web server instance upon changing any Go source files under the project directory (and its subdirectories).

syscall_windows.go 36KB

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