Skip to content

Commit

Permalink
windows: manually initialize NewNTUnicodeString
Browse files Browse the repository at this point in the history
The `RtlInitUnicodeString` syscall can be avoided by manually
initializing the `NTUnicodeString`.

The process is described in [WdmlibRtlInitUnicodeStringEx](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdmsec/nf-wdmsec-wdmlibrtlinitunicodestringex).

The less syscalls, the better. It also makes the function faster:

```
goos: windows
goarch: amd64
pkg: golang.org/x/sys/windows
cpu: Intel(R) Core(TM) i7-10850H CPU @ 2.70GHz
                      │    old.txt    │               new.txt                │
                      │    sec/op     │    sec/op     vs base                │
NewNTUnicodeString-12   181.05n ± 15%   96.32n ± 11%  -46.80% (p=0.000 n=10)
```

Change-Id: Iaf079acdcc2024cdca6b6b649a711f6be99c5b87
Reviewed-on: https://go-review.googlesource.com/c/sys/+/618175
Reviewed-by: Damien Neil <[email protected]>
Reviewed-by: Cherry Mui <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
  • Loading branch information
qmuntal committed Oct 7, 2024
1 parent 23b0dab commit 7143f4a
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions windows/syscall_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -1685,13 +1685,16 @@ func (s NTStatus) Error() string {
// do not use NTUnicodeString, and instead UTF16PtrFromString should be used for
// the more common *uint16 string type.
func NewNTUnicodeString(s string) (*NTUnicodeString, error) {
var u NTUnicodeString
s16, err := UTF16PtrFromString(s)
s16, err := UTF16FromString(s)
if err != nil {
return nil, err
}
RtlInitUnicodeString(&u, s16)
return &u, nil
n := uint16(len(s16) * 2)
return &NTUnicodeString{
Length: n - 2, // subtract 2 bytes for the NULL terminator
MaximumLength: n,
Buffer: &s16[0],
}, nil
}

// Slice returns a uint16 slice that aliases the data in the NTUnicodeString.
Expand Down

0 comments on commit 7143f4a

Please sign in to comment.