From da963a811505d854e11c67fffab3299dbe75a85c Mon Sep 17 00:00:00 2001 From: dahall Date: Mon, 14 Sep 2020 17:17:20 -0600 Subject: [PATCH] Fixed bug in marshaler for LSA_UNICODE_STRING under X64 that caused alignment error and failure on all calls. Thanks @ryannewington for identifying the problem and where to fix it (#169). --- PInvoke/Security/AdvApi32/NTSecApi.Lsa.cs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/PInvoke/Security/AdvApi32/NTSecApi.Lsa.cs b/PInvoke/Security/AdvApi32/NTSecApi.Lsa.cs index 0b6e52a5..64f2533a 100644 --- a/PInvoke/Security/AdvApi32/NTSecApi.Lsa.cs +++ b/PInvoke/Security/AdvApi32/NTSecApi.Lsa.cs @@ -3288,18 +3288,14 @@ namespace Vanara.PInvoke internal static IntPtr MarshalValue(string value) { if (value is null) return IntPtr.Zero; - var length = (short)StringHelper.GetByteCount(value, false, CharSet.Unicode); + var lus = new LSA_UNICODE_STRING { length = (ushort)StringHelper.GetByteCount(value, false, CharSet.Unicode) }; var chSz = StringHelper.GetCharSize(CharSet.Unicode); - var maxLength = (short)(length + chSz); - var sz = 4 + IntPtr.Size + length + chSz; - var mem = Marshal.AllocCoTaskMem(sz); - using (var s = new NativeMemoryStream(mem, sz, System.IO.FileAccess.Write) { CharSet = CharSet.Unicode }) - { - s.Write(length); - s.Write(maxLength); - s.WriteReference(value); - s.Flush(); - } + lus.MaximumLength = (ushort)(lus.length + chSz); + var ssz = Marshal.SizeOf(typeof(LSA_UNICODE_STRING)); + var mem = Marshal.AllocCoTaskMem(ssz + lus.MaximumLength); + lus.Buffer = mem.Offset(ssz); + mem.Write(lus); + StringHelper.Write(value, mem.Offset(ssz), out _, true, CharSet.Unicode, lus.MaximumLength); return mem; } }