syscall_windows.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 os_overloads
  6. import (
  7. "syscall"
  8. "unsafe"
  9. "golang.org/x/sys/windows"
  10. )
  11. // windows api calls
  12. //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
  13. func makeInheritSa() *syscall.SecurityAttributes {
  14. var sa syscall.SecurityAttributes
  15. sa.Length = uint32(unsafe.Sizeof(sa))
  16. sa.InheritHandle = 1
  17. return &sa
  18. }
  19. // opens the
  20. func Open(path string, mode int, perm uint32, setToTempAndDelete bool) (fd syscall.Handle, err error) {
  21. if len(path) == 0 {
  22. return syscall.InvalidHandle, windows.ERROR_FILE_NOT_FOUND
  23. }
  24. pathp, err := syscall.UTF16PtrFromString(path)
  25. if err != nil {
  26. return syscall.InvalidHandle, err
  27. }
  28. var access uint32
  29. switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) {
  30. case windows.O_RDONLY:
  31. access = windows.GENERIC_READ
  32. case windows.O_WRONLY:
  33. access = windows.GENERIC_WRITE
  34. case windows.O_RDWR:
  35. access = windows.GENERIC_READ | windows.GENERIC_WRITE
  36. }
  37. if mode&windows.O_CREAT != 0 {
  38. access |= windows.GENERIC_WRITE
  39. }
  40. if mode&windows.O_APPEND != 0 {
  41. access &^= windows.GENERIC_WRITE
  42. access |= windows.FILE_APPEND_DATA
  43. }
  44. sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE)
  45. var sa *syscall.SecurityAttributes
  46. if mode&windows.O_CLOEXEC == 0 {
  47. sa = makeInheritSa()
  48. }
  49. var createmode uint32
  50. switch {
  51. case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL):
  52. createmode = windows.CREATE_NEW
  53. case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC):
  54. createmode = windows.CREATE_ALWAYS
  55. case mode&windows.O_CREAT == windows.O_CREAT:
  56. createmode = windows.OPEN_ALWAYS
  57. case mode&windows.O_TRUNC == windows.O_TRUNC:
  58. createmode = windows.TRUNCATE_EXISTING
  59. default:
  60. createmode = windows.OPEN_EXISTING
  61. }
  62. var h syscall.Handle
  63. var e error
  64. if setToTempAndDelete {
  65. h, e = syscall.CreateFile(pathp, access, sharemode, sa, createmode, (windows.FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE), 0)
  66. } else {
  67. h, e = syscall.CreateFile(pathp, access, sharemode, sa, createmode, windows.FILE_ATTRIBUTE_NORMAL, 0)
  68. }
  69. return h, e
  70. }