syscall_windows_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Copyright 2012 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. package windows_test
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "syscall"
  13. "testing"
  14. "golang.org/x/sys/windows"
  15. )
  16. func TestWin32finddata(t *testing.T) {
  17. dir, err := ioutil.TempDir("", "go-build")
  18. if err != nil {
  19. t.Fatalf("failed to create temp directory: %v", err)
  20. }
  21. defer os.RemoveAll(dir)
  22. path := filepath.Join(dir, "long_name.and_extension")
  23. f, err := os.Create(path)
  24. if err != nil {
  25. t.Fatalf("failed to create %v: %v", path, err)
  26. }
  27. f.Close()
  28. type X struct {
  29. fd windows.Win32finddata
  30. got byte
  31. pad [10]byte // to protect ourselves
  32. }
  33. var want byte = 2 // it is unlikely to have this character in the filename
  34. x := X{got: want}
  35. pathp, _ := windows.UTF16PtrFromString(path)
  36. h, err := windows.FindFirstFile(pathp, &(x.fd))
  37. if err != nil {
  38. t.Fatalf("FindFirstFile failed: %v", err)
  39. }
  40. err = windows.FindClose(h)
  41. if err != nil {
  42. t.Fatalf("FindClose failed: %v", err)
  43. }
  44. if x.got != want {
  45. t.Fatalf("memory corruption: want=%d got=%d", want, x.got)
  46. }
  47. }
  48. func TestFormatMessage(t *testing.T) {
  49. dll := windows.MustLoadDLL("netevent.dll")
  50. const TITLE_SC_MESSAGE_BOX uint32 = 0xC0001B75
  51. const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS
  52. buf := make([]uint16, 300)
  53. _, err := windows.FormatMessage(flags, uintptr(dll.Handle), TITLE_SC_MESSAGE_BOX, 0, buf, nil)
  54. if err != nil {
  55. t.Fatalf("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, TITLE_SC_MESSAGE_BOX, err)
  56. }
  57. }
  58. func abort(funcname string, err error) {
  59. panic(funcname + " failed: " + err.Error())
  60. }
  61. func ExampleLoadLibrary() {
  62. h, err := windows.LoadLibrary("kernel32.dll")
  63. if err != nil {
  64. abort("LoadLibrary", err)
  65. }
  66. defer windows.FreeLibrary(h)
  67. proc, err := windows.GetProcAddress(h, "GetVersion")
  68. if err != nil {
  69. abort("GetProcAddress", err)
  70. }
  71. r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0)
  72. major := byte(r)
  73. minor := uint8(r >> 8)
  74. build := uint16(r >> 16)
  75. print("windows version ", major, ".", minor, " (Build ", build, ")\n")
  76. }
  77. func TestTOKEN_ALL_ACCESS(t *testing.T) {
  78. if windows.TOKEN_ALL_ACCESS != 0xF01FF {
  79. t.Errorf("TOKEN_ALL_ACCESS = %x, want 0xF01FF", windows.TOKEN_ALL_ACCESS)
  80. }
  81. }
  82. func TestCreateWellKnownSid(t *testing.T) {
  83. sid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
  84. if err != nil {
  85. t.Fatalf("Unable to create well known sid for administrators: %v", err)
  86. }
  87. if got, want := sid.String(), "S-1-5-32-544"; got != want {
  88. t.Fatalf("Builtin Administrators SID = %s, want %s", got, want)
  89. }
  90. }
  91. func TestPseudoTokens(t *testing.T) {
  92. version, err := windows.GetVersion()
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. if ((version&0xffff)>>8)|((version&0xff)<<8) < 0x0602 {
  97. return
  98. }
  99. realProcessToken, err := windows.OpenCurrentProcessToken()
  100. if err != nil {
  101. t.Fatal(err)
  102. }
  103. defer realProcessToken.Close()
  104. realProcessUser, err := realProcessToken.GetTokenUser()
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. pseudoProcessToken := windows.GetCurrentProcessToken()
  109. pseudoProcessUser, err := pseudoProcessToken.GetTokenUser()
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if !windows.EqualSid(realProcessUser.User.Sid, pseudoProcessUser.User.Sid) {
  114. t.Fatal("The real process token does not have the same as the pseudo process token")
  115. }
  116. runtime.LockOSThread()
  117. defer runtime.UnlockOSThread()
  118. err = windows.RevertToSelf()
  119. if err != nil {
  120. t.Fatal(err)
  121. }
  122. pseudoThreadToken := windows.GetCurrentThreadToken()
  123. _, err = pseudoThreadToken.GetTokenUser()
  124. if err != windows.ERROR_NO_TOKEN {
  125. t.Fatal("Expected an empty thread token")
  126. }
  127. pseudoThreadEffectiveToken := windows.GetCurrentThreadEffectiveToken()
  128. pseudoThreadEffectiveUser, err := pseudoThreadEffectiveToken.GetTokenUser()
  129. if err != nil {
  130. t.Fatal(nil)
  131. }
  132. if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadEffectiveUser.User.Sid) {
  133. t.Fatal("The real process token does not have the same as the pseudo thread effective token, even though we aren't impersonating")
  134. }
  135. err = windows.ImpersonateSelf(windows.SecurityImpersonation)
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. defer windows.RevertToSelf()
  140. pseudoThreadUser, err := pseudoThreadToken.GetTokenUser()
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadUser.User.Sid) {
  145. t.Fatal("The real process token does not have the same as the pseudo thread token after impersonating self")
  146. }
  147. }
  148. func TestGUID(t *testing.T) {
  149. guid, err := windows.GenerateGUID()
  150. if err != nil {
  151. t.Fatal(err)
  152. }
  153. if guid.Data1 == 0 && guid.Data2 == 0 && guid.Data3 == 0 && guid.Data4 == [8]byte{} {
  154. t.Fatal("Got an all zero GUID, which is overwhelmingly unlikely")
  155. }
  156. want := fmt.Sprintf("{%08X-%04X-%04X-%04X-%012X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[:2], guid.Data4[2:])
  157. got := guid.String()
  158. if got != want {
  159. t.Fatalf("String = %q; want %q", got, want)
  160. }
  161. guid2, err := windows.GUIDFromString(got)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. if guid2 != guid {
  166. t.Fatalf("Did not parse string back to original GUID = %q; want %q", guid2, guid)
  167. }
  168. _, err = windows.GUIDFromString("not-a-real-guid")
  169. if err != syscall.Errno(windows.CO_E_CLASSSTRING) {
  170. t.Fatalf("Bad GUID string error = %v; want CO_E_CLASSSTRING", err)
  171. }
  172. }
  173. func TestKnownFolderPath(t *testing.T) {
  174. token, err := windows.OpenCurrentProcessToken()
  175. if err != nil {
  176. t.Fatal(err)
  177. }
  178. defer token.Close()
  179. profileDir, err := token.GetUserProfileDirectory()
  180. if err != nil {
  181. t.Fatal(err)
  182. }
  183. want := filepath.Join(profileDir, "Desktop")
  184. got, err := windows.KnownFolderPath(windows.FOLDERID_Desktop, windows.KF_FLAG_DEFAULT)
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. if want != got {
  189. t.Fatalf("Path = %q; want %q", got, want)
  190. }
  191. }
  192. func TestRtlGetVersion(t *testing.T) {
  193. version := windows.RtlGetVersion()
  194. major, minor, build := windows.RtlGetNtVersionNumbers()
  195. // Go is not explictly added to the application compatibility database, so
  196. // these two functions should return the same thing.
  197. if version.MajorVersion != major || version.MinorVersion != minor || version.BuildNumber != build {
  198. t.Fatalf("%d.%d.%d != %d.%d.%d", version.MajorVersion, version.MinorVersion, version.BuildNumber, major, minor, build)
  199. }
  200. }
  201. func TestGetNamedSecurityInfo(t *testing.T) {
  202. path, err := windows.GetSystemDirectory()
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
  207. if err != nil {
  208. t.Fatal(err)
  209. }
  210. if !sd.IsValid() {
  211. t.Fatal("Invalid security descriptor")
  212. }
  213. sdOwner, _, err := sd.Owner()
  214. if err != nil {
  215. t.Fatal(err)
  216. }
  217. if !sdOwner.IsValid() {
  218. t.Fatal("Invalid security descriptor owner")
  219. }
  220. }
  221. func TestGetSecurityInfo(t *testing.T) {
  222. sd, err := windows.GetSecurityInfo(windows.CurrentProcess(), windows.SE_KERNEL_OBJECT, windows.DACL_SECURITY_INFORMATION)
  223. if err != nil {
  224. t.Fatal(err)
  225. }
  226. if !sd.IsValid() {
  227. t.Fatal("Invalid security descriptor")
  228. }
  229. sdStr := sd.String()
  230. if !strings.HasPrefix(sdStr, "D:(A;") {
  231. t.Fatalf("DACL = %q; want D:(A;...", sdStr)
  232. }
  233. }
  234. func TestSddlConversion(t *testing.T) {
  235. sd, err := windows.SecurityDescriptorFromString("O:BA")
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. if !sd.IsValid() {
  240. t.Fatal("Invalid security descriptor")
  241. }
  242. sdOwner, _, err := sd.Owner()
  243. if err != nil {
  244. t.Fatal(err)
  245. }
  246. if !sdOwner.IsValid() {
  247. t.Fatal("Invalid security descriptor owner")
  248. }
  249. if !sdOwner.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
  250. t.Fatalf("Owner = %q; want S-1-5-32-544", sdOwner)
  251. }
  252. }
  253. func TestBuildSecurityDescriptor(t *testing.T) {
  254. const want = "O:SYD:(A;;GA;;;BA)"
  255. adminSid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. systemSid, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
  260. if err != nil {
  261. t.Fatal(err)
  262. }
  263. access := []windows.EXPLICIT_ACCESS{{
  264. AccessPermissions: windows.GENERIC_ALL,
  265. AccessMode: windows.GRANT_ACCESS,
  266. Trustee: windows.TRUSTEE{
  267. TrusteeForm: windows.TRUSTEE_IS_SID,
  268. TrusteeType: windows.TRUSTEE_IS_GROUP,
  269. TrusteeValue: windows.TrusteeValueFromSID(adminSid),
  270. },
  271. }}
  272. owner := &windows.TRUSTEE{
  273. TrusteeForm: windows.TRUSTEE_IS_SID,
  274. TrusteeType: windows.TRUSTEE_IS_USER,
  275. TrusteeValue: windows.TrusteeValueFromSID(systemSid),
  276. }
  277. sd, err := windows.BuildSecurityDescriptor(owner, nil, access, nil, nil)
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. sd, err = sd.ToAbsolute()
  282. if err != nil {
  283. t.Fatal(err)
  284. }
  285. err = sd.SetSACL(nil, false, false)
  286. if err != nil {
  287. t.Fatal(err)
  288. }
  289. if got := sd.String(); got != want {
  290. t.Fatalf("SD = %q; want %q", got, want)
  291. }
  292. sd, err = sd.ToSelfRelative()
  293. if err != nil {
  294. t.Fatal(err)
  295. }
  296. if got := sd.String(); got != want {
  297. t.Fatalf("SD = %q; want %q", got, want)
  298. }
  299. sd, err = windows.NewSecurityDescriptor()
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. acl, err := windows.ACLFromEntries(access, nil)
  304. if err != nil {
  305. t.Fatal(err)
  306. }
  307. err = sd.SetDACL(acl, true, false)
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. err = sd.SetOwner(systemSid, false)
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. if got := sd.String(); got != want {
  316. t.Fatalf("SD = %q; want %q", got, want)
  317. }
  318. sd, err = sd.ToSelfRelative()
  319. if err != nil {
  320. t.Fatal(err)
  321. }
  322. if got := sd.String(); got != want {
  323. t.Fatalf("SD = %q; want %q", got, want)
  324. }
  325. }
  326. func TestGetDiskFreeSpaceEx(t *testing.T) {
  327. cwd, err := windows.UTF16PtrFromString(".")
  328. if err != nil {
  329. t.Fatalf(`failed to call UTF16PtrFromString("."): %v`, err)
  330. }
  331. var freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes uint64
  332. if err := windows.GetDiskFreeSpaceEx(cwd, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes); err != nil {
  333. t.Fatalf("failed to call GetDiskFreeSpaceEx: %v", err)
  334. }
  335. if freeBytesAvailableToCaller == 0 {
  336. t.Errorf("freeBytesAvailableToCaller: got 0; want > 0")
  337. }
  338. if totalNumberOfBytes == 0 {
  339. t.Errorf("totalNumberOfBytes: got 0; want > 0")
  340. }
  341. if totalNumberOfFreeBytes == 0 {
  342. t.Errorf("totalNumberOfFreeBytes: got 0; want > 0")
  343. }
  344. }