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