syscall_windows.go 36 KB

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