Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Address Windows recommendations for Link APIs #58592

Merged
merged 6 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/libraries/Common/src/System/IO/PathInternal.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ internal static partial class PathInternal

internal const string DirectorySeparatorCharAsString = "\\";

internal const string NTPathPrefix = @"\??\";
internal const string ExtendedPathPrefix = @"\\?\";
internal const string UncPathPrefix = @"\\";
internal const string UncExtendedPrefixToInsert = @"?\UNC\";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,22 @@ public void ResolveLinkTarget_ReturnFinalTarget_ChainOfLinks_ExceedsLimit_Throws
Assert.Throws<IOException>(() => ResolveLinkTarget(tail, returnFinalTarget: true));
}

[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(@"\??\", false)]
[InlineData(@"\??\", true)]
[InlineData(@"\\?\", false)]
[InlineData(@"\\?\", true)]
public void ResolveLinkTarget_ExtendedPrefix_IsNotTrimmed(string prefix, bool returnFinalTarget)
{
string linkPath = GetRandomLinkPath();
string targetPathWithPrefix = Path.Join(prefix, GetRandomFilePath());
CreateSymbolicLink(linkPath, targetPathWithPrefix);

FileSystemInfo info = ResolveLinkTarget(linkPath, returnFinalTarget);
Assert.Equal(targetPathWithPrefix, info.FullName);
}

private string CreateChainOfLinks(string target, int length, bool relative)
{
string previousPath = target;
Expand Down Expand Up @@ -344,32 +360,6 @@ public void DetectLinkReferenceToSelf()
Assert.Throws<IOException>(() => ResolveLinkTarget(linkPath, returnFinalTarget: true));
}

[Fact]
public void CreateSymbolicLink_WrongTargetType_Throws()
{
// dirLink -> file
// fileLink -> dir

string targetPath = GetRandomFilePath();
CreateFileOrDirectory(targetPath, createOpposite: true); // The underlying file system entry needs to be different
Assert.Throws<IOException>(() => CreateSymbolicLink(GetRandomFilePath(), targetPath));
}

[Fact]
public void CreateSymbolicLink_WrongTargetType_Indirect_Throws()
{
// link-2 (dir) -> link-1 (file) -> file
// link-2 (file) -> link-1 (dir) -> dir
string targetPath = GetRandomFilePath();
string firstLinkPath = GetRandomFilePath();
string secondLinkPath = GetRandomFilePath();

CreateFileOrDirectory(targetPath, createOpposite: true);
CreateSymbolicLink_Opposite(firstLinkPath, targetPath);

Assert.Throws<IOException>(() => CreateSymbolicLink(secondLinkPath, firstLinkPath));
}

[Fact]
public void CreateSymbolicLink_CorrectTargetType_Indirect_Succeeds()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ public void LinkTarget_RefreshesCorrectly()
Assert.Equal(newLinkInfo.LinkTarget, linkInfo.LinkTarget);
}

[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(@"\??\")]
[InlineData(@"\\?\")]
public void LinkTarget_ExtendedPrefix_IsNotTrimmed(string prefix)
{
string linkPath = GetRandomLinkPath();
string targetPathWithPrefix = Path.Join(prefix, GetRandomFilePath());

FileSystemInfo info = CreateSymbolicLink(linkPath, targetPathWithPrefix);
Assert.Equal(targetPathWithPrefix, info.LinkTarget);
}

public static IEnumerable<object[]> LinkTarget_PathToTarget_Data
{
get
Expand Down
59 changes: 28 additions & 31 deletions src/libraries/System.Private.CoreLib/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

<!--
Microsoft ResX Schema
Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -2659,9 +2659,6 @@
<data name="IO_BindHandleFailed" xml:space="preserve">
<value>BindHandle for ThreadPool failed on this handle.</value>
</data>
<data name="IO_InconsistentLinkType" xml:space="preserve">
<value>The link's file system entry type is inconsistent with that of its target: {0}</value>
</data>
jozkee marked this conversation as resolved.
Show resolved Hide resolved
<data name="IO_FileExists_Name" xml:space="preserve">
<value>The file '{0}' already exists.</value>
</data>
Expand Down Expand Up @@ -3817,4 +3814,4 @@
<data name="NullabilityInfoContext_NotSupported" xml:space="preserve">
<value>NullabilityInfoContext is not supported in the current application because 'System.Reflection.NullabilityInfoContext.IsSupported' is set to false. Set the MSBuild Property 'NullabilityInfoContextSupport' to true in order to enable it.</value>
</data>
</root>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -571,16 +571,6 @@ public static string[] GetLogicalDrives()
internal static void CreateSymbolicLink(string path, string pathToTarget, bool isDirectory)
{
string pathToTargetFullPath = PathInternal.GetLinkTargetFullPath(path, pathToTarget);

// Fail if the target exists but is not consistent with the expected filesystem entry type
if (Interop.Sys.Stat(pathToTargetFullPath, out Interop.Sys.FileStatus targetInfo) == 0)
{
if (isDirectory != ((targetInfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR))
{
throw new IOException(SR.Format(SR.IO_InconsistentLinkType, path));
}
}

Interop.CheckIo(Interop.Sys.SymLink(pathToTarget, path), path, isDirectory);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -415,16 +415,6 @@ public static string[] GetLogicalDrives()
internal static void CreateSymbolicLink(string path, string pathToTarget, bool isDirectory)
{
string pathToTargetFullPath = PathInternal.GetLinkTargetFullPath(path, pathToTarget);

Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(pathToTargetFullPath, ref data, returnErrorOnNotFound: true);
if (errorCode == Interop.Errors.ERROR_SUCCESS &&
data.dwFileAttributes != -1 &&
isDirectory != ((data.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0))
{
throw new IOException(SR.Format(SR.IO_InconsistentLinkType, path));
}

Interop.Kernel32.CreateSymbolicLink(path, pathToTarget, isDirectory);
}

Expand Down Expand Up @@ -502,11 +492,9 @@ internal static void CreateSymbolicLink(string path, string pathToTarget, bool i
success = MemoryMarshal.TryRead(bufferSpan, out Interop.Kernel32.SymbolicLinkReparseBuffer rbSymlink);
Debug.Assert(success);

// We use PrintName(Offset|Length) instead of SubstituteName(Offset|Length) given that we don't want to return
// an NT path when the link wasn't created with such NT path.
// Unlike SubstituteName and GetFinalPathNameByHandle(), PrintName doesn't start with a prefix.
// Another nuance is that SubstituteName does not contain redundant path segments while PrintName does.
// PrintName can ONLY return a NT path if the link was created explicitly targeting a file/folder in such way.
// We use PrintName(Offset|Length) instead of SubstituteName(Offset|Length) since is more friendly to the end-user, // however, there's no guarantee that the NT prefix doesn't show up.

// PrintName can return a NT path if the link was created explicitly targeting a file/folder in such way.
// e.g: mklink /D linkName \??\C:\path\to\target.

if (rbSymlink.ReparseTag == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_SYMLINK)
Expand All @@ -515,9 +503,10 @@ internal static void CreateSymbolicLink(string path, string pathToTarget, bool i
int printNameLength = rbSymlink.PrintNameLength;

Span<char> targetPath = MemoryMarshal.Cast<byte, char>(bufferSpan.Slice(printNameOffset, printNameLength));
Debug.Assert((rbSymlink.Flags & Interop.Kernel32.SYMLINK_FLAG_RELATIVE) == 0 || !PathInternal.IsExtended(targetPath));

if (returnFullPath && (rbSymlink.Flags & Interop.Kernel32.SYMLINK_FLAG_RELATIVE) != 0)
if (returnFullPath &&
(rbSymlink.Flags & Interop.Kernel32.SYMLINK_FLAG_RELATIVE) != 0 &&
!targetPath.StartsWith(PathInternal.NTPathPrefix.AsSpan())) // Edge-case: SYMLINK_FLAG_RELATIVE is incorrectly set when the target starts with \??\.
{
// Target path is relative and is for ResolveLinkTarget(), we need to append the link directory.
return Path.Join(Path.GetDirectoryName(linkPath.AsSpan()), targetPath);
Expand Down