Debian Codegraph @

windows/syscall_windows_test.go

raw
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
5 package windows_test
6
7 import (
8 "bufio"
9 "bytes"
10 "debug/pe"
11 "errors"
12 "fmt"
13 "math"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "runtime"
18 "strconv"
19 "strings"
20 "syscall"
21 "testing"
22 "time"
23 "unicode/utf8"
24 "unsafe"
25
26 "golang.org/x/sys/windows"
27 )
28
29 func TestWin32finddata(t *testing.T) {
30 path := filepath.Join(t.TempDir(), "long_name.and_extension")
31 f, err := os.Create(path)
32 if err != nil {
33 t.Fatalf("failed to create %v: %v", path, err)
34 }
35 f.Close()
36
37 type X struct {
38 fd windows.Win32finddata
39 got byte
40 pad [10]byte // to protect ourselves
41
42 }
43 var want byte = 2 // it is unlikely to have this character in the filename
44 x := X{got: want}
45
46 pathp, _ := windows.UTF16PtrFromString(path)
47 h, err := windows.FindFirstFile(pathp, &(x.fd))
48 if err != nil {
49 t.Fatalf("FindFirstFile failed: %v", err)
50 }
51 err = windows.FindClose(h)
52 if err != nil {
53 t.Fatalf("FindClose failed: %v", err)
54 }
55
56 if x.got != want {
57 t.Fatalf("memory corruption: want=%d got=%d", want, x.got)
58 }
59 }
60
61 func TestFormatMessage(t *testing.T) {
62 dll := windows.MustLoadDLL("netevent.dll")
63
64 const TITLE_SC_MESSAGE_BOX uint32 = 0xC0001B75
65 const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS
66 buf := make([]uint16, 300)
67 _, err := windows.FormatMessage(flags, uintptr(dll.Handle), TITLE_SC_MESSAGE_BOX, 0, buf, nil)
68 if err != nil {
69 t.Fatalf("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, TITLE_SC_MESSAGE_BOX, err)
70 }
71 }
72
73 func abort(funcname string, err error) {
74 panic(funcname + " failed: " + err.Error())
75 }
76
77 func ExampleLoadLibrary() {
78 h, err := windows.LoadLibrary("kernel32.dll")
79 if err != nil {
80 abort("LoadLibrary", err)
81 }
82 defer windows.FreeLibrary(h)
83 proc, err := windows.GetProcAddress(h, "GetVersion")
84 if err != nil {
85 abort("GetProcAddress", err)
86 }
87 r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0)
88 major := byte(r)
89 minor := uint8(r >> 8)
90 build := uint16(r >> 16)
91 print("windows version ", major, ".", minor, " (Build ", build, ")\n")
92 }
93
94 func TestTOKEN_ALL_ACCESS(t *testing.T) {
95 if windows.TOKEN_ALL_ACCESS != 0xF01FF {
96 t.Errorf("TOKEN_ALL_ACCESS = %x, want 0xF01FF", windows.TOKEN_ALL_ACCESS)
97 }
98 }
99
100 func TestCreateWellKnownSid(t *testing.T) {
101 sid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
102 if err != nil {
103 t.Fatalf("Unable to create well known sid for administrators: %v", err)
104 }
105 if got, want := sid.String(), "S-1-5-32-544"; got != want {
106 t.Fatalf("Builtin Administrators SID = %s, want %s", got, want)
107 }
108 }
109
110 func TestPseudoTokens(t *testing.T) {
111 version, err := windows.GetVersion()
112 if err != nil {
113 t.Fatal(err)
114 }
115 if ((version&0xffff)>>8)|((version&0xff)<<8) < 0x0602 {
116 return
117 }
118
119 realProcessToken, err := windows.OpenCurrentProcessToken()
120 if err != nil {
121 t.Fatal(err)
122 }
123 defer realProcessToken.Close()
124 realProcessUser, err := realProcessToken.GetTokenUser()
125 if err != nil {
126 t.Fatal(err)
127 }
128
129 pseudoProcessToken := windows.GetCurrentProcessToken()
130 pseudoProcessUser, err := pseudoProcessToken.GetTokenUser()
131 if err != nil {
132 t.Fatal(err)
133 }
134 if !windows.EqualSid(realProcessUser.User.Sid, pseudoProcessUser.User.Sid) {
135 t.Fatal("The real process token does not have the same as the pseudo process token")
136 }
137
138 runtime.LockOSThread()
139 defer runtime.UnlockOSThread()
140
141 err = windows.RevertToSelf()
142 if err != nil {
143 t.Fatal(err)
144 }
145
146 pseudoThreadToken := windows.GetCurrentThreadToken()
147 _, err = pseudoThreadToken.GetTokenUser()
148 if err != windows.ERROR_NO_TOKEN {
149 t.Fatal("Expected an empty thread token")
150 }
151 pseudoThreadEffectiveToken := windows.GetCurrentThreadEffectiveToken()
152 pseudoThreadEffectiveUser, err := pseudoThreadEffectiveToken.GetTokenUser()
153 if err != nil {
154 t.Fatal(nil)
155 }
156 if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadEffectiveUser.User.Sid) {
157 t.Fatal("The real process token does not have the same as the pseudo thread effective token, even though we aren't impersonating")
158 }
159
160 err = windows.ImpersonateSelf(windows.SecurityImpersonation)
161 if err != nil {
162 t.Fatal(err)
163 }
164 defer windows.RevertToSelf()
165 pseudoThreadUser, err := pseudoThreadToken.GetTokenUser()
166 if err != nil {
167 t.Fatal(err)
168 }
169 if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadUser.User.Sid) {
170 t.Fatal("The real process token does not have the same as the pseudo thread token after impersonating self")
171 }
172 }
173
174 func TestGUID(t *testing.T) {
175 guid, err := windows.GenerateGUID()
176 if err != nil {
177 t.Fatal(err)
178 }
179 if guid.Data1 == 0 && guid.Data2 == 0 && guid.Data3 == 0 && guid.Data4 == [8]byte{} {
180 t.Fatal("Got an all zero GUID, which is overwhelmingly unlikely")
181 }
182 want := fmt.Sprintf("{%08X-%04X-%04X-%04X-%012X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[:2], guid.Data4[2:])
183 got := guid.String()
184 if got != want {
185 t.Fatalf("String = %q; want %q", got, want)
186 }
187 guid2, err := windows.GUIDFromString(got)
188 if err != nil {
189 t.Fatal(err)
190 }
191 if guid2 != guid {
192 t.Fatalf("Did not parse string back to original GUID = %q; want %q", guid2, guid)
193 }
194 _, err = windows.GUIDFromString("not-a-real-guid")
195 if err != syscall.Errno(windows.CO_E_CLASSSTRING) {
196 t.Fatalf("Bad GUID string error = %v; want CO_E_CLASSSTRING", err)
197 }
198 }
199
200 func TestKnownFolderPath(t *testing.T) {
201 token, err := windows.OpenCurrentProcessToken()
202 if err != nil {
203 t.Fatal(err)
204 }
205 defer token.Close()
206 profileDir, err := token.GetUserProfileDirectory()
207 if err != nil {
208 t.Fatal(err)
209 }
210 want := filepath.Join(profileDir, "Desktop")
211 got, err := windows.KnownFolderPath(windows.FOLDERID_Desktop, windows.KF_FLAG_DEFAULT)
212 if err != nil {
213 t.Fatal(err)
214 }
215 if want != got {
216 t.Fatalf("Path = %q; want %q", got, want)
217 }
218 }
219
220 func TestRtlGetVersion(t *testing.T) {
221 version := windows.RtlGetVersion()
222 major, minor, build := windows.RtlGetNtVersionNumbers()
223 // Go is not explicitly added to the application compatibility database, so
224 // these two functions should return the same thing.
225 if version.MajorVersion != major || version.MinorVersion != minor || version.BuildNumber != build {
226 t.Fatalf("%d.%d.%d != %d.%d.%d", version.MajorVersion, version.MinorVersion, version.BuildNumber, major, minor, build)
227 }
228 }
229
230 func TestGetNamedSecurityInfo(t *testing.T) {
231 path, err := windows.GetSystemDirectory()
232 if err != nil {
233 t.Fatal(err)
234 }
235 sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
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 }
250
251 func TestGetSecurityInfo(t *testing.T) {
252 sd, err := windows.GetSecurityInfo(windows.CurrentProcess(), windows.SE_KERNEL_OBJECT, windows.DACL_SECURITY_INFORMATION)
253 if err != nil {
254 t.Fatal(err)
255 }
256 if !sd.IsValid() {
257 t.Fatal("Invalid security descriptor")
258 }
259 sdStr := sd.String()
260 if !strings.HasPrefix(sdStr, "D:(A;") {
261 t.Fatalf("DACL = %q; want D:(A;...", sdStr)
262 }
263 }
264
265 func TestSddlConversion(t *testing.T) {
266 sd, err := windows.SecurityDescriptorFromString("O:BA")
267 if err != nil {
268 t.Fatal(err)
269 }
270 if !sd.IsValid() {
271 t.Fatal("Invalid security descriptor")
272 }
273 sdOwner, _, err := sd.Owner()
274 if err != nil {
275 t.Fatal(err)
276 }
277 if !sdOwner.IsValid() {
278 t.Fatal("Invalid security descriptor owner")
279 }
280 if !sdOwner.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
281 t.Fatalf("Owner = %q; want S-1-5-32-544", sdOwner)
282 }
283 }
284
285 func TestBuildSecurityDescriptor(t *testing.T) {
286 const want = "O:SYD:(A;;GA;;;BA)"
287
288 adminSid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
289 if err != nil {
290 t.Fatal(err)
291 }
292 systemSid, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
293 if err != nil {
294 t.Fatal(err)
295 }
296
297 var pinner runtime.Pinner
298 defer pinner.Unpin()
299 pinner.Pin(adminSid)
300 pinner.Pin(systemSid)
301
302 access := []windows.EXPLICIT_ACCESS{{
303 AccessPermissions: windows.GENERIC_ALL,
304 AccessMode: windows.GRANT_ACCESS,
305 Trustee: windows.TRUSTEE{
306 TrusteeForm: windows.TRUSTEE_IS_SID,
307 TrusteeType: windows.TRUSTEE_IS_GROUP,
308 TrusteeValue: windows.TrusteeValueFromSID(adminSid),
309 },
310 }}
311 owner := &windows.TRUSTEE{
312 TrusteeForm: windows.TRUSTEE_IS_SID,
313 TrusteeType: windows.TRUSTEE_IS_USER,
314 TrusteeValue: windows.TrusteeValueFromSID(systemSid),
315 }
316
317 sd, err := windows.BuildSecurityDescriptor(owner, nil, access, nil, nil)
318 if err != nil {
319 t.Fatal(err)
320 }
321 sd, err = sd.ToAbsolute()
322 if err != nil {
323 t.Fatal(err)
324 }
325 err = sd.SetSACL(nil, false, false)
326 if err != nil {
327 t.Fatal(err)
328 }
329 if got := sd.String(); got != want {
330 t.Fatalf("SD = %q; want %q", got, want)
331 }
332 sd, err = sd.ToSelfRelative()
333 if err != nil {
334 t.Fatal(err)
335 }
336 if got := sd.String(); got != want {
337 t.Fatalf("SD = %q; want %q", got, want)
338 }
339
340 sd, err = windows.NewSecurityDescriptor()
341 if err != nil {
342 t.Fatal(err)
343 }
344 acl, err := windows.ACLFromEntries(access, nil)
345 if err != nil {
346 t.Fatal(err)
347 }
348 err = sd.SetDACL(acl, true, false)
349 if err != nil {
350 t.Fatal(err)
351 }
352 err = sd.SetOwner(systemSid, false)
353 if err != nil {
354 t.Fatal(err)
355 }
356 if got := sd.String(); got != want {
357 t.Fatalf("SD = %q; want %q", got, want)
358 }
359 sd, err = sd.ToSelfRelative()
360 if err != nil {
361 t.Fatal(err)
362 }
363 if got := sd.String(); got != want {
364 t.Fatalf("SD = %q; want %q", got, want)
365 }
366 }
367
368 // getEntriesFromACL returns a list of explicit access control entries associated with the given ACL.
369 func getEntriesFromACL(acl *windows.ACL) (aces []*windows.ACCESS_ALLOWED_ACE, err error) {
370 aces = make([]*windows.ACCESS_ALLOWED_ACE, acl.AceCount)
371
372 for i := uint16(0); i < acl.AceCount; i++ {
373 err = windows.GetAce(acl, uint32(i), &aces[i])
374 if err != nil {
375 return nil, err
376 }
377 }
378
379 return aces, nil
380 }
381
382 func TestGetACEsFromACL(t *testing.T) {
383 // Create a temporary file to set ACLs on and test getting the ACEs from the ACL.
384 f, err := os.CreateTemp("", "foo.lish")
385 defer os.Remove(f.Name())
386
387 if err = f.Close(); err != nil {
388 t.Fatal(err)
389 }
390
391 // Well-known SID Strings:
392 // https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
393 ownerSid, err := windows.StringToSid("S-1-3-2")
394 if err != nil {
395 t.Fatal(err)
396 }
397 groupSid, err := windows.StringToSid("S-1-3-3")
398 if err != nil {
399 t.Fatal(err)
400 }
401 worldSid, err := windows.StringToSid("S-1-1-0")
402 if err != nil {
403 t.Fatal(err)
404 }
405
406 ownerPermissions := windows.ACCESS_MASK(windows.GENERIC_ALL)
407 groupPermissions := windows.ACCESS_MASK(windows.GENERIC_READ | windows.GENERIC_EXECUTE)
408 worldPermissions := windows.ACCESS_MASK(windows.GENERIC_READ)
409
410 access := []windows.EXPLICIT_ACCESS{
411 {
412 AccessPermissions: ownerPermissions,
413 AccessMode: windows.GRANT_ACCESS,
414 Trustee: windows.TRUSTEE{
415 TrusteeForm: windows.TRUSTEE_IS_SID,
416 TrusteeValue: windows.TrusteeValueFromSID(ownerSid),
417 },
418 },
419 {
420 AccessPermissions: groupPermissions,
421 AccessMode: windows.GRANT_ACCESS,
422 Trustee: windows.TRUSTEE{
423 TrusteeForm: windows.TRUSTEE_IS_SID,
424 TrusteeType: windows.TRUSTEE_IS_GROUP,
425 TrusteeValue: windows.TrusteeValueFromSID(groupSid),
426 },
427 },
428 {
429 AccessPermissions: worldPermissions,
430 AccessMode: windows.GRANT_ACCESS,
431 Trustee: windows.TRUSTEE{
432 TrusteeForm: windows.TRUSTEE_IS_SID,
433 TrusteeType: windows.TRUSTEE_IS_GROUP,
434 TrusteeValue: windows.TrusteeValueFromSID(worldSid),
435 },
436 },
437 }
438
439 acl, err := windows.ACLFromEntries(access, nil)
440 if err != nil {
441 t.Fatal(err)
442 }
443
444 // Set new ACL.
445 err = windows.SetNamedSecurityInfo(
446 f.Name(),
447 windows.SE_FILE_OBJECT,
448 windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION,
449 nil,
450 nil,
451 acl,
452 nil,
453 )
454 if err != nil {
455 t.Fatal(err)
456 }
457
458 descriptor, err := windows.GetNamedSecurityInfo(
459 f.Name(),
460 windows.SE_FILE_OBJECT,
461 windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION|windows.OWNER_SECURITY_INFORMATION|windows.GROUP_SECURITY_INFORMATION,
462 )
463 if err != nil {
464 t.Fatal(err)
465 }
466
467 dacl, _, err := descriptor.DACL()
468 if err != nil {
469 t.Fatal(err)
470 }
471
472 owner, _, err := descriptor.Owner()
473 if err != nil {
474 t.Fatal(err)
475 }
476
477 group, _, err := descriptor.Group()
478 if err != nil {
479 t.Fatal(err)
480 }
481
482 entries, err := getEntriesFromACL(dacl)
483 if err != nil {
484 t.Fatal(err)
485 }
486
487 if len(entries) != 3 {
488 t.Fatalf("Expected newly set ACL to only have 3 entries.")
489 }
490
491 // https://docs.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants
492 read := uint32(windows.FILE_READ_DATA | windows.FILE_READ_ATTRIBUTES)
493 write := uint32(windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_ATTRIBUTES | windows.FILE_WRITE_EA)
494 execute := uint32(windows.FILE_READ_DATA | windows.FILE_EXECUTE)
495
496 // Check the set ACEs. We should have the equivalent of 754.
497 for _, entry := range entries {
498 mask := uint32(entry.Mask)
499 actual := 0
500
501 if mask&read == read {
502 actual |= 4
503 }
504 if mask&write == write {
505 actual |= 2
506 }
507 if mask&execute == execute {
508 actual |= 1
509 }
510
511 entrySid := (*windows.SID)(unsafe.Pointer(&entry.SidStart))
512 if owner.Equals(entrySid) {
513 if actual != 7 {
514 t.Fatalf("Expected owner to have FullAccess permissions.")
515 }
516 } else if group.Equals(entrySid) {
517 if actual != 5 {
518 t.Fatalf("Expected group to have only Read and Execute permissions.")
519 }
520 } else if worldSid.Equals(entrySid) {
521 if actual != 4 {
522 t.Fatalf("Expected the World to have only Read permissions.")
523 }
524 } else {
525 t.Fatalf("Unexpected SID in ACEs: %s", entrySid.String())
526 }
527 }
528 }
529
530 func TestGetDiskFreeSpaceEx(t *testing.T) {
531 cwd, err := windows.UTF16PtrFromString(".")
532 if err != nil {
533 t.Fatalf(`failed to call UTF16PtrFromString("."): %v`, err)
534 }
535 var freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes uint64
536 if err := windows.GetDiskFreeSpaceEx(cwd, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes); err != nil {
537 t.Fatalf("failed to call GetDiskFreeSpaceEx: %v", err)
538 }
539
540 if freeBytesAvailableToCaller == 0 {
541 t.Errorf("freeBytesAvailableToCaller: got 0; want > 0")
542 }
543 if totalNumberOfBytes == 0 {
544 t.Errorf("totalNumberOfBytes: got 0; want > 0")
545 }
546 if totalNumberOfFreeBytes == 0 {
547 t.Errorf("totalNumberOfFreeBytes: got 0; want > 0")
548 }
549 }
550
551 func TestGetPreferredUILanguages(t *testing.T) {
552 tab := map[string]func(flags uint32) ([]string, error){
553 "GetProcessPreferredUILanguages": windows.GetProcessPreferredUILanguages,
554 "GetThreadPreferredUILanguages": windows.GetThreadPreferredUILanguages,
555 "GetUserPreferredUILanguages": windows.GetUserPreferredUILanguages,
556 "GetSystemPreferredUILanguages": windows.GetSystemPreferredUILanguages,
557 }
558 for fName, f := range tab {
559 lang, err := f(windows.MUI_LANGUAGE_ID)
560 if err != nil {
561 t.Errorf(`failed to call %v(MUI_LANGUAGE_ID): %v`, fName, err)
562 }
563 for _, l := range lang {
564 _, err := strconv.ParseUint(l, 16, 16)
565 if err != nil {
566 t.Errorf(`%v(MUI_LANGUAGE_ID) returned unexpected LANGID: %v`, fName, l)
567 }
568 }
569
570 lang, err = f(windows.MUI_LANGUAGE_NAME)
571 if err != nil {
572 t.Errorf(`failed to call %v(MUI_LANGUAGE_NAME): %v`, fName, err)
573 }
574 }
575 }
576
577 func TestProcessWorkingSetSizeEx(t *testing.T) {
578 // Grab a handle to the current process
579 hProcess := windows.CurrentProcess()
580
581 // Allocate memory to store the result of the query
582 var minimumWorkingSetSize, maximumWorkingSetSize uintptr
583
584 // Make the system-call
585 var flag uint32
586 windows.GetProcessWorkingSetSizeEx(hProcess, &minimumWorkingSetSize, &maximumWorkingSetSize, &flag)
587
588 // Set the new limits to the current ones
589 if err := windows.SetProcessWorkingSetSizeEx(hProcess, minimumWorkingSetSize, maximumWorkingSetSize, flag); err != nil {
590 t.Error(err)
591 }
592 }
593
594 func TestJobObjectInfo(t *testing.T) {
595 jo, err := windows.CreateJobObject(nil, nil)
596 if err != nil {
597 t.Fatalf("CreateJobObject failed: %v", err)
598 }
599 defer windows.CloseHandle(jo)
600
601 var info windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION
602
603 err = windows.QueryInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
604 uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)), nil)
605 if err != nil {
606 t.Fatalf("QueryInformationJobObject failed: %v", err)
607 }
608
609 const wantMemLimit = 4 * 1024
610
611 info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_PROCESS_MEMORY
612 info.ProcessMemoryLimit = wantMemLimit
613 _, err = windows.SetInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
614 uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)))
615 if err != nil {
616 t.Fatalf("SetInformationJobObject failed: %v", err)
617 }
618
619 err = windows.QueryInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
620 uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)), nil)
621 if err != nil {
622 t.Fatalf("QueryInformationJobObject failed: %v", err)
623 }
624
625 if have := info.ProcessMemoryLimit; wantMemLimit != have {
626 t.Errorf("ProcessMemoryLimit is wrong: want %v have %v", wantMemLimit, have)
627 }
628 }
629
630 func TestIsWow64Process2(t *testing.T) {
631 var processMachine, nativeMachine uint16
632 err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine)
633 if errors.Is(err, windows.ERROR_PROC_NOT_FOUND) {
634 maj, min, build := windows.RtlGetNtVersionNumbers()
635 if maj < 10 || (maj == 10 && min == 0 && build < 17763) {
636 t.Skip("not available on older versions of Windows")
637 return
638 }
639 }
640 if err != nil {
641 t.Fatalf("IsWow64Process2 failed: %v", err)
642 }
643 if processMachine == pe.IMAGE_FILE_MACHINE_UNKNOWN {
644 processMachine = nativeMachine
645 }
646 switch {
647 case processMachine == pe.IMAGE_FILE_MACHINE_AMD64 && runtime.GOARCH == "amd64":
648 case processMachine == pe.IMAGE_FILE_MACHINE_I386 && runtime.GOARCH == "386":
649 case processMachine == pe.IMAGE_FILE_MACHINE_ARMNT && runtime.GOARCH == "arm":
650 case processMachine == pe.IMAGE_FILE_MACHINE_ARM64 && runtime.GOARCH == "arm64":
651 default:
652 t.Errorf("IsWow64Process2 is wrong: want %v have %v", runtime.GOARCH, processMachine)
653 }
654 }
655
656 func TestNTStatusString(t *testing.T) {
657 want := "The name limit for the local computer network adapter card was exceeded."
658 got := windows.STATUS_TOO_MANY_NAMES.Error()
659 if want != got {
660 t.Errorf("NTStatus.Error did not return an expected error string - want %q; got %q", want, got)
661 }
662 }
663
664 func TestNTStatusConversion(t *testing.T) {
665 want := windows.ERROR_TOO_MANY_NAMES
666 got := windows.STATUS_TOO_MANY_NAMES.Errno()
667 if want != got {
668 t.Errorf("NTStatus.Errno = %q (0x%x); want %q (0x%x)", got.Error(), got, want.Error(), want)
669 }
670 }
671
672 func TestPEBFilePath(t *testing.T) {
673 peb := windows.RtlGetCurrentPeb()
674 if peb == nil || peb.Ldr == nil {
675 t.Error("unable to retrieve PEB with valid Ldr")
676 }
677 var entry *windows.LDR_DATA_TABLE_ENTRY
678 for cur := peb.Ldr.InMemoryOrderModuleList.Flink; cur != &peb.Ldr.InMemoryOrderModuleList; cur = cur.Flink {
679 e := (*windows.LDR_DATA_TABLE_ENTRY)(unsafe.Pointer(uintptr(unsafe.Pointer(cur)) - unsafe.Offsetof(windows.LDR_DATA_TABLE_ENTRY{}.InMemoryOrderLinks)))
680 if e.DllBase == peb.ImageBaseAddress {
681 entry = e
682 break
683 }
684 }
685 if entry == nil {
686 t.Error("unable to find Ldr entry for current process")
687 }
688 osPath, err := os.Executable()
689 if err != nil {
690 t.Errorf("unable to get path to current executable: %v", err)
691 }
692 pebPath := entry.FullDllName.String()
693 if osPath != pebPath {
694 t.Errorf("peb.Ldr.{entry}.FullDllName = %#q; want %#q", pebPath, osPath)
695 }
696 paramPath := peb.ProcessParameters.ImagePathName.String()
697 if osPath != paramPath {
698 t.Errorf("peb.ProcessParameters.ImagePathName.{entry}.ImagePathName = %#q; want %#q", paramPath, osPath)
699 }
700 osCwd, err := os.Getwd()
701 if err != nil {
702 t.Errorf("unable to get working directory: %v", err)
703 }
704 osCwd = filepath.Clean(osCwd)
705 paramCwd := filepath.Clean(peb.ProcessParameters.CurrentDirectory.DosPath.String())
706 if paramCwd != osCwd {
707 t.Errorf("peb.ProcessParameters.CurrentDirectory.DosPath = %#q; want %#q", paramCwd, osCwd)
708 }
709 }
710
711 func TestResourceExtraction(t *testing.T) {
712 system32, err := windows.GetSystemDirectory()
713 if err != nil {
714 t.Errorf("unable to find system32 directory: %v", err)
715 }
716 cmd, err := windows.LoadLibrary(filepath.Join(system32, "cmd.exe"))
717 if err != nil {
718 t.Errorf("unable to load cmd.exe: %v", err)
719 }
720 defer windows.FreeLibrary(cmd)
721 rsrc, err := windows.FindResource(cmd, windows.CREATEPROCESS_MANIFEST_RESOURCE_ID, windows.RT_MANIFEST)
722 if err != nil {
723 t.Errorf("unable to find cmd.exe manifest resource: %v", err)
724 }
725 manifest, err := windows.LoadResourceData(cmd, rsrc)
726 if err != nil {
727 t.Errorf("unable to load cmd.exe manifest resource data: %v", err)
728 }
729 if !bytes.Contains(manifest, []byte("</assembly>")) {
730 t.Errorf("did not find </assembly> in manifest")
731 }
732 }
733
734 func FuzzComposeCommandLine(f *testing.F) {
735 f.Add(`C:\foo.exe /bar /baz "-bag qux"`)
736 f.Add(`"C:\Program Files\Go\bin\go.exe" env`)
737 f.Add(`C:\"Program Files"\Go\bin\go.exe env`)
738 f.Add(`C:\"Program Files"\Go\bin\go.exe env`)
739 f.Add(`C:\"Pro"gram Files\Go\bin\go.exe env`)
740 f.Add(``)
741 f.Add(` `)
742 f.Add(`W\"0`)
743 f.Add("\"\f")
744 f.Add("\f")
745 f.Add("\x16")
746 f.Add(`"" ` + strings.Repeat("a", 8193))
747 f.Add(strings.Repeat(`"" `, 8193))
748
749 f.Add("\x00abcd")
750 f.Add("ab\x00cd")
751 f.Add("abcd\x00")
752 f.Add("\x00abcd\x00")
753 f.Add("\x00ab\x00cd\x00")
754 f.Add("\x00\x00\x00")
755 f.Add("\x16\x00\x16")
756 f.Add(`C:\Program Files\Go\bin\go.exe` + "\x00env")
757 f.Add(`"C:\Program Files\Go\bin\go.exe"` + "\x00env")
758 f.Add(`C:\"Program Files"\Go\bin\go.exe` + "\x00env")
759 f.Add(`C:\"Pro"gram Files\Go\bin\go.exe` + "\x00env")
760 f.Add("\x00" + strings.Repeat("a", 8192))
761 f.Add("\x00" + strings.Repeat("a", 8193))
762 f.Add(strings.Repeat("\x00"+strings.Repeat("a", 8192), 4))
763
764 f.Fuzz(func(t *testing.T, s string) {
765 // DecomposeCommandLine is the “control” for our experiment:
766 // if it returns a particular list of arguments, then we know
767 // it must be possible to create an input string that produces
768 // exactly those arguments.
769 //
770 // However, DecomposeCommandLine returns an error if the string
771 // contains a NUL byte. In that case, we will fall back to
772 // strings.Split, and be a bit more permissive about the results.
773 args, err := windows.DecomposeCommandLine(s)
774 argsFromSplit := false
775
776 if err == nil {
777 if testing.Verbose() {
778 t.Logf("DecomposeCommandLine(%#q) = %#q", s, args)
779 }
780 } else {
781 t.Logf("DecomposeCommandLine: %v", err)
782 if !strings.Contains(s, "\x00") {
783 // The documentation for CommandLineToArgv takes for granted that
784 // the first argument is a valid file path, and doesn't describe any
785 // specific behavior for malformed arguments. Empirically it seems to
786 // tolerate anything we throw at it, but if we discover cases where it
787 // actually returns an error we might need to relax this check.
788 t.Fatal("(error unexpected)")
789 }
790
791 // Since DecomposeCommandLine can't handle this string,
792 // interpret it as the raw arguments to ComposeCommandLine.
793 args = strings.Split(s, "\x00")
794 argsFromSplit = true
795 for i, arg := range args {
796 if !utf8.ValidString(arg) {
797 // We need to encode the arguments as UTF-16 to pass them to
798 // CommandLineToArgvW, so skip inputs that are not valid: they might
799 // have one or more runes converted to replacement characters.
800 t.Skipf("skipping: input %d is not valid UTF-8", i)
801 }
802 }
803 if testing.Verbose() {
804 t.Logf("using input: %#q", args)
805 }
806 }
807
808 // It's ok if we compose a different command line than what was read.
809 // Just check that we are able to compose something that round-trips
810 // to the same results as the original.
811 commandLine := windows.ComposeCommandLine(args)
812 t.Logf("ComposeCommandLine(_) = %#q", commandLine)
813
814 got, err := windows.DecomposeCommandLine(commandLine)
815 if err != nil {
816 t.Fatalf("DecomposeCommandLine: unexpected error: %v", err)
817 }
818 if testing.Verbose() {
819 t.Logf("DecomposeCommandLine(_) = %#q", got)
820 }
821
822 var badMatches []int
823 for i := range args {
824 if i >= len(got) {
825 badMatches = append(badMatches, i)
826 continue
827 }
828 want := args[i]
829 if got[i] != want {
830 if i == 0 && argsFromSplit {
831 // It is possible that args[0] cannot be encoded exactly, because
832 // CommandLineToArgvW doesn't unescape that argument in the same way
833 // as the others: since the first argument is assumed to be the name
834 // of the program itself, we only have the option of quoted or not.
835 //
836 // If args[0] contains a space or control character, we must quote it
837 // to avoid it being split into multiple arguments.
838 // If args[0] already starts with a quote character, we have no way
839 // to indicate that character is part of the literal argument.
840 // In either case, if the string already contains a quote character
841 // we must avoid misinterpreting that character as the end of the
842 // quoted argument string.
843 //
844 // Unfortunately, ComposeCommandLine does not return an error, so we
845 // can't report existing quote characters as errors.
846 // Instead, we strip out the problematic quote characters from the
847 // argument, and quote the remainder.
848 // For paths like C:\"Program Files"\Go\bin\go.exe that is arguably
849 // what the caller intended anyway, and for other strings it seems
850 // less harmful than corrupting the subsequent arguments.
851 if got[i] == strings.ReplaceAll(want, `"`, ``) {
852 continue
853 }
854 }
855 badMatches = append(badMatches, i)
856 }
857 }
858 if len(badMatches) != 0 {
859 t.Errorf("Incorrect decomposition at indices: %v", badMatches)
860 }
861 })
862 }
863
864 func TestWinVerifyTrust(t *testing.T) {
865 evsignedfile := `.\testdata\ev-signed-file.exe`
866 evsignedfile16, err := windows.UTF16PtrFromString(evsignedfile)
867 if err != nil {
868 t.Fatalf("unable to get utf16 of %s: %v", evsignedfile, err)
869 }
870 data := &windows.WinTrustData{
871 Size: uint32(unsafe.Sizeof(windows.WinTrustData{})),
872 UIChoice: windows.WTD_UI_NONE,
873 RevocationChecks: windows.WTD_REVOKE_NONE, // No revocation checking, in case the tests don't have network connectivity.
874 UnionChoice: windows.WTD_CHOICE_FILE,
875 StateAction: windows.WTD_STATEACTION_VERIFY,
876 FileOrCatalogOrBlobOrSgnrOrCert: unsafe.Pointer(&windows.WinTrustFileInfo{
877 Size: uint32(unsafe.Sizeof(windows.WinTrustFileInfo{})),
878 FilePath: evsignedfile16,
879 }),
880 }
881 verifyErr := windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
882 data.StateAction = windows.WTD_STATEACTION_CLOSE
883 closeErr := windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
884 if verifyErr != nil {
885 t.Errorf("%s did not verify: %v", evsignedfile, verifyErr)
886 }
887 if closeErr != nil {
888 t.Errorf("unable to free verification resources: %v", closeErr)
889 }
890
891 // Now that we've verified the legitimate file verifies, let's corrupt it and see if it correctly fails.
892
893 corruptedEvsignedfile := filepath.Join(t.TempDir(), "corrupted-file")
894 evsignedfileBytes, err := os.ReadFile(evsignedfile)
895 if err != nil {
896 t.Fatalf("unable to read %s bytes: %v", evsignedfile, err)
897 }
898 if len(evsignedfileBytes) > 0 {
899 evsignedfileBytes[len(evsignedfileBytes)/2-1]++
900 }
901 err = os.WriteFile(corruptedEvsignedfile, evsignedfileBytes, 0755)
902 if err != nil {
903 t.Fatalf("unable to write corrupted ntoskrnl.exe bytes: %v", err)
904 }
905 evsignedfile16, err = windows.UTF16PtrFromString(corruptedEvsignedfile)
906 if err != nil {
907 t.Fatalf("unable to get utf16 of ntoskrnl.exe: %v", err)
908 }
909 data = &windows.WinTrustData{
910 Size: uint32(unsafe.Sizeof(windows.WinTrustData{})),
911 UIChoice: windows.WTD_UI_NONE,
912 RevocationChecks: windows.WTD_REVOKE_NONE, // No revocation checking, in case the tests don't have network connectivity.
913 UnionChoice: windows.WTD_CHOICE_FILE,
914 StateAction: windows.WTD_STATEACTION_VERIFY,
915 FileOrCatalogOrBlobOrSgnrOrCert: unsafe.Pointer(&windows.WinTrustFileInfo{
916 Size: uint32(unsafe.Sizeof(windows.WinTrustFileInfo{})),
917 FilePath: evsignedfile16,
918 }),
919 }
920 verifyErr = windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
921 data.StateAction = windows.WTD_STATEACTION_CLOSE
922 closeErr = windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
923 if verifyErr != windows.Errno(windows.TRUST_E_BAD_DIGEST) {
924 t.Errorf("%s did not fail to verify as expected: %v", corruptedEvsignedfile, verifyErr)
925 }
926 if closeErr != nil {
927 t.Errorf("unable to free verification resources: %v", closeErr)
928 }
929
930 }
931
932 func TestEnumProcesses(t *testing.T) {
933 var (
934 pids [2]uint32
935 outSize uint32
936 )
937 err := windows.EnumProcesses(pids[:], &outSize)
938 if err != nil {
939 t.Fatalf("unable to enumerate processes: %v", err)
940 }
941
942 // Regression check for go.dev/issue/60223
943 if outSize != 8 {
944 t.Errorf("unexpected bytes returned: %d", outSize)
945 }
946 // Most likely, this should be [0, 4].
947 // 0 is the system idle pseudo-process. 4 is the initial system process ID.
948 // This test expects that at least one of the PIDs is not 0.
949 if pids[0] == 0 && pids[1] == 0 {
950 t.Errorf("all PIDs are 0")
951 }
952 }
953
954 func TestProcessModules(t *testing.T) {
955 process, err := windows.GetCurrentProcess()
956 if err != nil {
957 t.Fatalf("unable to get current process: %v", err)
958 }
959 // NB: Assume that we're always the first module. This technically isn't documented anywhere (that I could find), but seems to always hold.
960 var module windows.Handle
961 var cbNeeded uint32
962 err = windows.EnumProcessModules(process, &module, uint32(unsafe.Sizeof(module)), &cbNeeded)
963 if err != nil {
964 t.Fatalf("EnumProcessModules failed: %v", err)
965 }
966
967 var moduleEx windows.Handle
968 err = windows.EnumProcessModulesEx(process, &moduleEx, uint32(unsafe.Sizeof(moduleEx)), &cbNeeded, windows.LIST_MODULES_DEFAULT)
969 if err != nil {
970 t.Fatalf("EnumProcessModulesEx failed: %v", err)
971 }
972 if module != moduleEx {
973 t.Fatalf("module from EnumProcessModules does not match EnumProcessModulesEx: %v != %v", module, moduleEx)
974 }
975
976 exePath, err := os.Executable()
977 if err != nil {
978 t.Fatalf("unable to get current executable path: %v", err)
979 }
980
981 modulePathUTF16 := make([]uint16, len(exePath)+1)
982 err = windows.GetModuleFileNameEx(process, module, &modulePathUTF16[0], uint32(len(modulePathUTF16)))
983 if err != nil {
984 t.Fatalf("GetModuleFileNameEx failed: %v", err)
985 }
986
987 modulePath := windows.UTF16ToString(modulePathUTF16)
988 if modulePath != exePath {
989 t.Fatalf("module does not match executable for GetModuleFileNameEx: %s != %s", modulePath, exePath)
990 }
991
992 err = windows.GetModuleBaseName(process, module, &modulePathUTF16[0], uint32(len(modulePathUTF16)))
993 if err != nil {
994 t.Fatalf("GetModuleBaseName failed: %v", err)
995 }
996
997 modulePath = windows.UTF16ToString(modulePathUTF16)
998 baseExePath := filepath.Base(exePath)
999 if modulePath != baseExePath {
1000 t.Fatalf("module does not match executable for GetModuleBaseName: %s != %s", modulePath, baseExePath)
1001 }
1002
1003 var moduleInfo windows.ModuleInfo
1004 err = windows.GetModuleInformation(process, module, &moduleInfo, uint32(unsafe.Sizeof(moduleInfo)))
1005 if err != nil {
1006 t.Fatalf("GetModuleInformation failed: %v", err)
1007 }
1008
1009 peFile, err := pe.Open(exePath)
1010 if err != nil {
1011 t.Fatalf("unable to open current executable: %v", err)
1012 }
1013 defer peFile.Close()
1014
1015 var peSizeOfImage uint32
1016 switch runtime.GOARCH {
1017 case "amd64", "arm64":
1018 peSizeOfImage = peFile.OptionalHeader.(*pe.OptionalHeader64).SizeOfImage
1019 case "386", "arm":
1020 peSizeOfImage = peFile.OptionalHeader.(*pe.OptionalHeader32).SizeOfImage
1021 default:
1022 t.Fatalf("unable to test GetModuleInformation on arch %v", runtime.GOARCH)
1023 }
1024
1025 if moduleInfo.SizeOfImage != peSizeOfImage {
1026 t.Fatalf("module size does not match executable: %v != %v", moduleInfo.SizeOfImage, peSizeOfImage)
1027 }
1028 }
1029
1030 func TestQueryWorkingSetEx(t *testing.T) {
1031 var a int
1032
1033 process := windows.CurrentProcess()
1034 information := windows.PSAPI_WORKING_SET_EX_INFORMATION{
1035 VirtualAddress: windows.Pointer(unsafe.Pointer(&a)),
1036 }
1037 infos := []windows.PSAPI_WORKING_SET_EX_INFORMATION{information}
1038
1039 cb := uint32(uintptr(len(infos)) * unsafe.Sizeof(infos[0]))
1040 if err := windows.QueryWorkingSetEx(process, uintptr(unsafe.Pointer(&infos[0])), cb); err != nil {
1041 t.Fatalf("%+v", err)
1042 }
1043
1044 if !infos[0].VirtualAttributes.Valid() {
1045 t.Errorf("memory location not valid")
1046 }
1047 }
1048
1049 func TestReadWriteProcessMemory(t *testing.T) {
1050 testBuffer := []byte{0xBA, 0xAD, 0xF0, 0x0D}
1051
1052 process, err := windows.GetCurrentProcess()
1053 if err != nil {
1054 t.Fatalf("unable to get current process: %v", err)
1055 }
1056
1057 buffer := make([]byte, len(testBuffer))
1058 err = windows.ReadProcessMemory(process, uintptr(unsafe.Pointer(&testBuffer[0])), &buffer[0], uintptr(len(buffer)), nil)
1059 if err != nil {
1060 t.Errorf("ReadProcessMemory failed: %v", err)
1061 }
1062 if !bytes.Equal(testBuffer, buffer) {
1063 t.Errorf("bytes read does not match buffer: 0x%X != 0x%X", testBuffer, buffer)
1064 }
1065
1066 buffer = []byte{0xDE, 0xAD, 0xBE, 0xEF}
1067 err = windows.WriteProcessMemory(process, uintptr(unsafe.Pointer(&testBuffer[0])), &buffer[0], uintptr(len(buffer)), nil)
1068 if err != nil {
1069 t.Errorf("WriteProcessMemory failed: %v", err)
1070 }
1071 if !bytes.Equal(testBuffer, buffer) {
1072 t.Errorf("bytes written does not match buffer: 0x%X != 0x%X", testBuffer, buffer)
1073 }
1074 }
1075
1076 func TestSystemModuleVersions(t *testing.T) {
1077 var modules []windows.RTL_PROCESS_MODULE_INFORMATION
1078 for bufferSize := uint32(128 * 1024); ; {
1079 moduleBuffer := make([]byte, bufferSize)
1080 err := windows.NtQuerySystemInformation(windows.SystemModuleInformation, unsafe.Pointer(&moduleBuffer[0]), bufferSize, &bufferSize)
1081 switch err {
1082 case windows.STATUS_INFO_LENGTH_MISMATCH:
1083 continue
1084 case nil:
1085 break
1086 default:
1087 t.Error(err)
1088 return
1089 }
1090 mods := (*windows.RTL_PROCESS_MODULES)(unsafe.Pointer(&moduleBuffer[0]))
1091 modules = unsafe.Slice(&mods.Modules[0], int(mods.NumberOfModules))
1092 break
1093 }
1094 for i := range modules {
1095 moduleName := windows.ByteSliceToString(modules[i].FullPathName[modules[i].OffsetToFileName:])
1096 driverPath := `\\?\GLOBALROOT` + windows.ByteSliceToString(modules[i].FullPathName[:])
1097 var zero windows.Handle
1098 infoSize, err := windows.GetFileVersionInfoSize(driverPath, &zero)
1099 if err != nil {
1100 if err != windows.ERROR_FILE_NOT_FOUND && err != windows.ERROR_RESOURCE_TYPE_NOT_FOUND {
1101 t.Errorf("%v: %v", moduleName, err)
1102 }
1103 continue
1104 }
1105 versionInfo := make([]byte, infoSize)
1106 if err = windows.GetFileVersionInfo(driverPath, 0, infoSize, unsafe.Pointer(&versionInfo[0])); err != nil {
1107 t.Errorf("%v: %v", moduleName, err)
1108 continue
1109 }
1110 var fixedInfo *windows.VS_FIXEDFILEINFO
1111 fixedInfoLen := uint32(unsafe.Sizeof(*fixedInfo))
1112 err = windows.VerQueryValue(unsafe.Pointer(&versionInfo[0]), `\`, (unsafe.Pointer)(&fixedInfo), &fixedInfoLen)
1113 if err != nil {
1114 t.Errorf("%v: %v", moduleName, err)
1115 continue
1116 }
1117 t.Logf("%s: v%d.%d.%d.%d", moduleName,
1118 (fixedInfo.FileVersionMS>>16)&0xff,
1119 (fixedInfo.FileVersionMS>>0)&0xff,
1120 (fixedInfo.FileVersionLS>>16)&0xff,
1121 (fixedInfo.FileVersionLS>>0)&0xff)
1122 }
1123 }
1124
1125 type fileRenameInformation struct {
1126 ReplaceIfExists uint32
1127 RootDirectory windows.Handle
1128 FileNameLength uint32
1129 FileName [1]uint16
1130 }
1131
1132 func TestNtCreateFileAndNtSetInformationFile(t *testing.T) {
1133 var iosb windows.IO_STATUS_BLOCK
1134 var allocSize int64 = 0
1135 // Open test directory with NtCreateFile.
1136 testDirPath := t.TempDir()
1137 objectName, err := windows.NewNTUnicodeString("\\??\\" + testDirPath)
1138 if err != nil {
1139 t.Fatal(err)
1140 }
1141 oa := &windows.OBJECT_ATTRIBUTES{
1142 ObjectName: objectName,
1143 }
1144 oa.Length = uint32(unsafe.Sizeof(*oa))
1145 var testDirHandle windows.Handle
1146 err = windows.NtCreateFile(&testDirHandle, windows.FILE_GENERIC_READ|windows.FILE_GENERIC_WRITE, oa, &iosb,
1147 &allocSize, 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, windows.FILE_OPEN,
1148 windows.FILE_DIRECTORY_FILE, 0, 0)
1149 if err != nil {
1150 t.Fatalf("NtCreateFile(%v) failed: %v", testDirPath, err)
1151 }
1152 defer windows.CloseHandle(testDirHandle)
1153 // Create a file in test directory with NtCreateFile.
1154 fileName := "filename"
1155 filePath := filepath.Join(testDirPath, fileName)
1156 objectName, err = windows.NewNTUnicodeString(fileName)
1157 if err != nil {
1158 t.Fatal(err)
1159 }
1160 oa.RootDirectory = testDirHandle
1161 oa.ObjectName = objectName
1162 var fileHandle windows.Handle
1163 err = windows.NtCreateFile(&fileHandle, windows.FILE_GENERIC_READ|windows.FILE_GENERIC_WRITE|windows.DELETE, oa, &iosb,
1164 &allocSize, 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, windows.FILE_CREATE,
1165 0, 0, 0)
1166 if err != nil {
1167 t.Fatalf("NtCreateFile(%v) failed: %v", filePath, err)
1168 }
1169 defer windows.CloseHandle(fileHandle)
1170 _, err = os.Stat(filePath)
1171 if err != nil {
1172 t.Fatalf("cannot stat file created with NtCreatefile: %v", err)
1173 }
1174 // Rename file with NtSetInformationFile.
1175 newName := "newname"
1176 newPath := filepath.Join(testDirPath, newName)
1177 newNameUTF16, err := windows.UTF16FromString(newName)
1178 if err != nil {
1179 t.Fatal(err)
1180 }
1181 fileNameLen := len(newNameUTF16)*2 - 2
1182 var dummyFileRenameInfo fileRenameInformation
1183 bufferSize := int(unsafe.Offsetof(dummyFileRenameInfo.FileName)) + fileNameLen
1184 buffer := make([]byte, bufferSize)
1185 typedBufferPtr := (*fileRenameInformation)(unsafe.Pointer(&buffer[0]))
1186 typedBufferPtr.ReplaceIfExists = windows.FILE_RENAME_REPLACE_IF_EXISTS | windows.FILE_RENAME_POSIX_SEMANTICS
1187 typedBufferPtr.FileNameLength = uint32(fileNameLen)
1188 copy((*[windows.MAX_LONG_PATH]uint16)(unsafe.Pointer(&typedBufferPtr.FileName[0]))[:fileNameLen/2:fileNameLen/2], newNameUTF16)
1189 err = windows.NtSetInformationFile(fileHandle, &iosb, &buffer[0], uint32(bufferSize), windows.FileRenameInformation)
1190 if err != nil {
1191 t.Fatalf("NtSetInformationFile(%v) failed: %v", newPath, err)
1192 }
1193 _, err = os.Stat(newPath)
1194 if err != nil {
1195 t.Fatalf("cannot stat rename target %v: %v", newPath, err)
1196 }
1197 }
1198
1199 var deviceClassNetGUID = &windows.GUID{0x4d36e972, 0xe325, 0x11ce, [8]byte{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}}
1200 var deviceInterfaceNetGUID = &windows.GUID{0xcac88484, 0x7515, 0x4c03, [8]byte{0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61}}
1201
1202 func TestListLoadedNetworkDevices(t *testing.T) {
1203 devInfo, err := windows.SetupDiGetClassDevsEx(deviceClassNetGUID, "", 0, windows.DIGCF_PRESENT, 0, "")
1204 if err != nil {
1205 t.Fatal(err)
1206 }
1207 defer devInfo.Close()
1208 for i := 0; ; i++ {
1209 devInfoData, err := devInfo.EnumDeviceInfo(i)
1210 if err != nil {
1211 if err == windows.ERROR_NO_MORE_ITEMS {
1212 break
1213 }
1214 continue
1215 }
1216 friendlyName, err := devInfo.DeviceRegistryProperty(devInfoData, windows.SPDRP_DEVICEDESC)
1217 if err != nil {
1218 t.Fatal(err)
1219 }
1220 var status, problemCode uint32
1221 err = windows.CM_Get_DevNode_Status(&status, &problemCode, devInfoData.DevInst, 0)
1222 if err != nil || (status&windows.DN_DRIVER_LOADED|windows.DN_STARTED) != windows.DN_DRIVER_LOADED|windows.DN_STARTED {
1223 continue
1224 }
1225 instanceId, err := devInfo.DeviceInstanceID(devInfoData)
1226 if err != nil {
1227 t.Fatal(err)
1228 }
1229 interfaces, err := windows.CM_Get_Device_Interface_List(instanceId, deviceInterfaceNetGUID, windows.CM_GET_DEVICE_INTERFACE_LIST_PRESENT)
1230 if err != nil || len(interfaces) == 0 {
1231 continue
1232 }
1233 t.Logf("%s - %s", friendlyName, interfaces[0])
1234 }
1235 }
1236
1237 func TestListWireGuardDrivers(t *testing.T) {
1238 devInfo, err := windows.SetupDiCreateDeviceInfoListEx(deviceClassNetGUID, 0, "")
1239 if err != nil {
1240 t.Fatal(err)
1241 }
1242 defer devInfo.Close()
1243 devInfoData, err := devInfo.CreateDeviceInfo("WireGuard", deviceClassNetGUID, "", 0, windows.DICD_GENERATE_ID)
1244 if err != nil {
1245 t.Fatal(err)
1246 }
1247 err = devInfo.SetDeviceRegistryProperty(devInfoData, windows.SPDRP_HARDWAREID, []byte("W\x00i\x00r\x00e\x00G\x00u\x00a\x00r\x00d\x00\x00\x00\x00\x00"))
1248 if err != nil {
1249 t.Fatal(err)
1250 }
1251 err = devInfo.BuildDriverInfoList(devInfoData, windows.SPDIT_COMPATDRIVER)
1252 if err != nil {
1253 t.Fatal(err)
1254 }
1255 defer devInfo.DestroyDriverInfoList(devInfoData, windows.SPDIT_COMPATDRIVER)
1256 for i := 0; ; i++ {
1257 drvInfoData, err := devInfo.EnumDriverInfo(devInfoData, windows.SPDIT_COMPATDRIVER, i)
1258 if err != nil {
1259 if err == windows.ERROR_NO_MORE_ITEMS {
1260 break
1261 }
1262 continue
1263 }
1264 drvInfoDetailData, err := devInfo.DriverInfoDetail(devInfoData, drvInfoData)
1265 if err != nil {
1266 t.Error(err)
1267 continue
1268 }
1269 t.Logf("%s - %s", drvInfoData.Description(), drvInfoDetailData.InfFileName())
1270 }
1271 }
1272
1273 func TestProcThreadAttributeHandleList(t *testing.T) {
1274 const sentinel = "the gopher dance"
1275 system32, err := windows.GetSystemDirectory()
1276 if err != nil {
1277 t.Fatal(err)
1278 }
1279 executable16, err := windows.UTF16PtrFromString(filepath.Join(system32, "cmd.exe"))
1280 if err != nil {
1281 t.Fatal(err)
1282 }
1283 args16, err := windows.UTF16PtrFromString(windows.ComposeCommandLine([]string{"/c", "echo " + sentinel}))
1284 if err != nil {
1285 t.Fatal(err)
1286 }
1287 attributeList, err := windows.NewProcThreadAttributeList(1)
1288 if err != nil {
1289 t.Fatal(err)
1290 }
1291 defer attributeList.Delete()
1292 si := &windows.StartupInfoEx{
1293 StartupInfo: windows.StartupInfo{Cb: uint32(unsafe.Sizeof(windows.StartupInfoEx{}))},
1294 ProcThreadAttributeList: attributeList.List(),
1295 }
1296 pipeR, pipeW, err := os.Pipe()
1297 if err != nil {
1298 t.Fatal(err)
1299 }
1300 defer pipeR.Close()
1301 defer pipeW.Close()
1302 func() {
1303 // We allocate handles in a closure to provoke a UaF in the case of attributeList.Update being buggy.
1304 handles := []windows.Handle{windows.Handle(pipeW.Fd())}
1305 attributeList.Update(windows.PROC_THREAD_ATTRIBUTE_HANDLE_LIST, unsafe.Pointer(&handles[0]), uintptr(len(handles))*unsafe.Sizeof(handles[0]))
1306 si.Flags |= windows.STARTF_USESTDHANDLES
1307 si.StdOutput = handles[0]
1308 // Go 1.16's pipe handles aren't inheritable, so mark it explicitly as such here.
1309 windows.SetHandleInformation(handles[0], windows.HANDLE_FLAG_INHERIT, windows.HANDLE_FLAG_INHERIT)
1310 }()
1311 pi := new(windows.ProcessInformation)
1312 err = windows.CreateProcess(executable16, args16, nil, nil, true, windows.CREATE_DEFAULT_ERROR_MODE|windows.CREATE_UNICODE_ENVIRONMENT|windows.EXTENDED_STARTUPINFO_PRESENT, nil, nil, &si.StartupInfo, pi)
1313 if err != nil {
1314 t.Fatal(err)
1315 }
1316 defer windows.CloseHandle(pi.Thread)
1317 defer windows.CloseHandle(pi.Process)
1318 pipeR.SetReadDeadline(time.Now().Add(time.Minute))
1319 out, _, err := bufio.NewReader(pipeR).ReadLine()
1320 if err != nil {
1321 t.Fatal(err)
1322 }
1323 if string(out) != sentinel {
1324 t.Fatalf("got %q; want %q", out, sentinel)
1325 }
1326 }
1327
1328 func TestWSALookupService(t *testing.T) {
1329 var flags uint32 = windows.LUP_CONTAINERS
1330 flags |= windows.LUP_RETURN_NAME
1331 flags |= windows.LUP_RETURN_ADDR
1332
1333 var querySet windows.WSAQUERYSET
1334 querySet.NameSpace = windows.NS_BTH
1335 querySet.Size = uint32(unsafe.Sizeof(windows.WSAQUERYSET{}))
1336
1337 var handle windows.Handle
1338 err := windows.WSALookupServiceBegin(&querySet, flags, &handle)
1339 if err != nil {
1340 if errors.Is(err, windows.WSASERVICE_NOT_FOUND) {
1341 t.Skip("WSA Service not found, so skip this test")
1342 }
1343 t.Fatal(err)
1344 }
1345
1346 defer windows.WSALookupServiceEnd(handle)
1347
1348 n := int32(unsafe.Sizeof(windows.WSAQUERYSET{}))
1349 buf := make([]byte, n)
1350 items_loop:
1351 for {
1352 q := (*windows.WSAQUERYSET)(unsafe.Pointer(&buf[0]))
1353 err := windows.WSALookupServiceNext(handle, flags, &n, q)
1354 switch err {
1355 case windows.WSA_E_NO_MORE, windows.WSAENOMORE:
1356 // no more data available - break the loop
1357 break items_loop
1358 case windows.WSAEFAULT:
1359 // buffer is too small - reallocate and try again
1360 buf = make([]byte, n)
1361 case nil:
1362 // found a record - display the item and fetch next item
1363 var addr string
1364 for _, e := range q.SaBuffer.RemoteAddr.Sockaddr.Addr.Data {
1365 if e != 0 {
1366 addr += fmt.Sprintf("%x", e)
1367 }
1368 }
1369 t.Logf("%s -> %s\n", windows.UTF16PtrToString(q.ServiceInstanceName), addr)
1370
1371 default:
1372 t.Fatal(err)
1373 }
1374 }
1375 }
1376
1377 func TestTimePeriod(t *testing.T) {
1378 if err := windows.TimeBeginPeriod(1); err != nil {
1379 t.Fatal(err)
1380 }
1381 if err := windows.TimeEndPeriod(1); err != nil {
1382 t.Fatal(err)
1383 }
1384 }
1385
1386 func TestGetStartupInfo(t *testing.T) {
1387 var si windows.StartupInfo
1388 err := windows.GetStartupInfo(&si)
1389 if err != nil {
1390 // see https://go.dev/issue/31316
1391 t.Fatalf("GetStartupInfo: got error %v, want nil", err)
1392 }
1393 }
1394
1395 func TestAddRemoveDllDirectory(t *testing.T) {
1396 if _, err := exec.LookPath("gcc"); err != nil {
1397 t.Skip("skipping test: gcc is missing")
1398 }
1399 dllSrc := `#include <stdint.h>
1400 #include <windows.h>
1401
1402 uintptr_t beep(void) {
1403 return 5;
1404 }`
1405 tmpdir := t.TempDir()
1406 srcname := "beep.c"
1407 err := os.WriteFile(filepath.Join(tmpdir, srcname), []byte(dllSrc), 0)
1408 if err != nil {
1409 t.Fatal(err)
1410 }
1411 name := "beep.dll"
1412 cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", name, srcname)
1413 cmd.Dir = tmpdir
1414 out, err := cmd.CombinedOutput()
1415 if err != nil {
1416 t.Fatalf("failed to build dll: %v - %v", err, string(out))
1417 }
1418
1419 if _, err := windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS); err == nil {
1420 t.Fatal("LoadLibraryEx unexpectedly found beep.dll")
1421 }
1422
1423 dllCookie, err := windows.AddDllDirectory(windows.StringToUTF16Ptr(tmpdir))
1424 if err != nil {
1425 t.Fatalf("AddDllDirectory failed: %s", err)
1426 }
1427
1428 handle, err := windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS)
1429 if err != nil {
1430 t.Fatalf("LoadLibraryEx failed: %s", err)
1431 }
1432
1433 if err := windows.FreeLibrary(handle); err != nil {
1434 t.Fatalf("FreeLibrary failed: %s", err)
1435 }
1436
1437 if err := windows.RemoveDllDirectory(dllCookie); err != nil {
1438 t.Fatalf("RemoveDllDirectory failed: %s", err)
1439 }
1440
1441 _, err = windows.LoadLibraryEx("beep.dll", 0, windows.LOAD_LIBRARY_SEARCH_USER_DIRS)
1442 if err == nil {
1443 t.Fatal("LoadLibraryEx unexpectedly found beep.dll")
1444 }
1445 }
1446
1447 func TestToUnicodeEx(t *testing.T) {
1448 var utf16Buf [16]uint16
1449
1450 // Arabic (101) Keyboard Identifier
1451 // See https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-language-pack-default-values
1452 ara, err := windows.UTF16PtrFromString("00000401")
1453 if err != nil {
1454 t.Fatalf("UTF16PtrFromString failed: %v", err)
1455 }
1456 araLayout, err := windows.LoadKeyboardLayout(ara, windows.KLF_ACTIVATE)
1457 if err != nil {
1458 t.Fatalf("LoadKeyboardLayout failed: %v", err)
1459 }
1460
1461 var keyState [256]byte
1462 ret := windows.ToUnicodeEx(
1463 0x41, // 'A' vkCode
1464 0x1e, // 'A' scanCode
1465 &keyState[0],
1466 &utf16Buf[0],
1467 int32(len(utf16Buf)),
1468 0x4, // don't change keyboard state
1469 araLayout,
1470 )
1471
1472 if ret != 1 {
1473 t.Errorf("ToUnicodeEx failed, wanted 1, got %d", ret)
1474 }
1475 if utf16Buf[0] != 'ش' {
1476 t.Errorf("ToUnicodeEx failed, wanted 'ش', got %q", utf16Buf[0])
1477 }
1478 if err := windows.UnloadKeyboardLayout(araLayout); err != nil {
1479 t.Errorf("UnloadKeyboardLayout failed: %v", err)
1480 }
1481 }
1482
1483 func TestRoundtripNTUnicodeString(t *testing.T) {
1484 // NTUnicodeString maximum string length must fit in a uint16, less for terminal NUL.
1485 maxString := strings.Repeat("*", (math.MaxUint16/2)-1)
1486 for _, test := range []struct {
1487 s string
1488 wantErr bool
1489 }{{
1490 s: "",
1491 }, {
1492 s: "hello",
1493 }, {
1494 s: "Ƀ",
1495 }, {
1496 s: maxString,
1497 }, {
1498 s: maxString + "*",
1499 wantErr: true,
1500 }, {
1501 s: "a\x00a",
1502 wantErr: true,
1503 }} {
1504 ntus, err := windows.NewNTUnicodeString(test.s)
1505 if (err != nil) != test.wantErr {
1506 t.Errorf("NewNTUnicodeString(%q): %v, wantErr:%v", test.s, err, test.wantErr)
1507 continue
1508 }
1509 if err != nil {
1510 continue
1511 }
1512 s2 := ntus.String()
1513 if test.s != s2 {
1514 t.Errorf("round trip of %q = %q, wanted original", test.s, s2)
1515 }
1516 }
1517 }
1518
1519 func TestRoundtripNTString(t *testing.T) {
1520 // NTString maximum string length must fit in a uint16, less for terminal NUL.
1521 maxString := strings.Repeat("*", windows.MAX_USHORT-1)
1522 for _, test := range []struct {
1523 s string
1524 wantErr bool
1525 }{{
1526 s: "",
1527 }, {
1528 s: "hello",
1529 }, {
1530 s: maxString,
1531 }, {
1532 s: maxString + "*",
1533 wantErr: true,
1534 }, {
1535 s: "a\x00a",
1536 wantErr: true,
1537 }} {
1538 nts, err := windows.NewNTString(test.s)
1539 if (err != nil) != test.wantErr {
1540 t.Errorf("NewNTString(%q): %v, wantErr:%v", test.s, err, test.wantErr)
1541 continue
1542 }
1543 if err != nil {
1544 if !errors.Is(err, syscall.EINVAL) {
1545 t.Errorf("NewNTString(%q): %v, want %v", test.s, err, syscall.EINVAL)
1546 }
1547 continue
1548 }
1549 s2 := nts.String()
1550 if test.s != s2 {
1551 t.Errorf("round trip of %q = %q, wanted original", test.s, s2)
1552 }
1553 }
1554 }
1555
1556 func TestIsProcessorFeaturePresent(t *testing.T) {
1557 // according to
1558 // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-isprocessorfeaturepresent
1559 // if PF_PAE_ENABLED returns nonzero value, then
1560 // ...
1561 // The processor is PAE-enabled. For more information, see Physical Address Extension.
1562 // All x64 processors always return a nonzero value for this feature.
1563 // ...
1564 switch runtime.GOARCH {
1565 case "amd64", "386":
1566 default:
1567 t.Skipf("the test is no supported by %q processor type", runtime.GOARCH)
1568 }
1569
1570 if !windows.IsProcessorFeaturePresent(windows.PF_PAE_ENABLED) {
1571 t.Fatal("IsProcessorFeaturePresent failed, but should succeed")
1572 }
1573 }