Skip to content

Commit

Permalink
CreateSymbolicLink PInvoke retval must be marshalled as U1 (#69150) (#…
Browse files Browse the repository at this point in the history
…73004)

* CreateSymbolicLink PInvoke retval must be marshalled as U1

* Fix redundant invocations of Environment.OSVersion.Version
  • Loading branch information
jozkee committed Aug 11, 2022
1 parent b6366d4 commit 9180526
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 10 deletions.
1 change: 1 addition & 0 deletions src/installer/tests/TestUtils/SymbolicLinking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ private enum SymbolicLinkFlag
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool CreateSymbolicLink(
string symbolicLinkName,
string targetFileName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ internal static partial class Kernel32
internal const int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x2;

[DllImport(Libraries.Kernel32, EntryPoint = "CreateSymbolicLinkW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool CreateSymbolicLinkPrivate(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

/// <summary>
Expand All @@ -38,9 +39,8 @@ internal static void CreateSymbolicLink(string symlinkFileName, string targetFil

int flags = 0;

bool isAtLeastWin10Build14972 =
Environment.OSVersion.Version.Major == 10 && Environment.OSVersion.Version.Build >= 14972 ||
Environment.OSVersion.Version.Major >= 11;
Version osVersion = Environment.OSVersion.Version;
bool isAtLeastWin10Build14972 = osVersion.Major >= 11 || osVersion.Major == 10 && osVersion.Build >= 14972;

if (isAtLeastWin10Build14972)
{
Expand All @@ -54,17 +54,10 @@ internal static void CreateSymbolicLink(string symlinkFileName, string targetFil

bool success = CreateSymbolicLinkPrivate(symlinkFileName, targetFileName, flags);

int error;
if (!success)
{
throw Win32Marshal.GetExceptionForLastWin32Error(originalPath);
}
// In older versions we need to check GetLastWin32Error regardless of the return value of CreateSymbolicLink,
// e.g: if the user doesn't have enough privileges to create a symlink the method returns success which we can consider as a silent failure.
else if (!isAtLeastWin10Build14972 && (error = Marshal.GetLastWin32Error()) != 0)
{
throw Win32Marshal.GetExceptionForWin32Error(error, originalPath);
}
}
}
}

0 comments on commit 9180526

Please sign in to comment.