Skip to content

Target type detection (file/directory) for relative symlinks is still broken, even on Windows #15235

Closed

Description

#12797 (comment)

Intro & context

Symlink target may be a relative path, which is then resolved by the filesystem as a relative path from parent directory of the symlink. Example:
We have the following 2 files:

    Directory: D:\test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---          2021-04-15    00:41              0 file_link.txt -> .\file.txt
-a---          2021-04-15    00:41              0 file.txt

file_link.txt is a file symlink, which resolves to D:\test\file.txt. It might be created with New-Item -Type SymbolicLink .\file_link.txt -Target .\file.txt.

There's a difference between a symlink to a file and to a directory, and attempting to traverse a directory symlink pointing to a file does not work (and same for trying to read from a file symlink pointing to a directory).

To correctly create the symlink, PowerShell checks whether the target is a file or a directory. Originally, this check was broken for relative target paths, because the process-wide .NET working directory was used to resolve the target (so the above command would check for a target path like C:\Windows\System32\file.txt - that path doesn't exist, so pwsh defaults to creating a file symlink). This was supposedly fixed in #12797.

With this "fix", working directory of PowerShell is now used instead of the .NET working directory. This is however still incorrect, because we don't want to resolve the target relative to CWD, but relative to the symlink itself.

Reproduction

(I'll use D:/test as our testing directory to make it clear when I'm talking about absolute paths)

1)

mkdir D:/test
mkdir D:/test/dir
cd D:/
ni -Type SymbolicLink D:/test/dir_link -Target ./dir

Expected: directory symlink to D:/test/dir, with target ./dir
Got: file symlink to D:/test/dir, with target ./dir
The target type detection code checks the relative path ./dir (D:/dir), which doesn't exist, so the symlink incorrectly defaults to file symlink.

2)

mkdir D:/test
mkdir D:/test/dir
cd D:/test
ni -Type SymbolicLink D:/test/dir_link -Target ./dir

Expected: directory symlink to D:/test/dir, with target ./dir
Got: what I expected
Only difference from previous example is the cd D:/test on line 3. This correctly creates a directory symlink, because the code checks type of target for ./dir (D:/test/dir), which now matches the real target.

3)

mkdir D:/test/subdir
mkdir D:/test/item # <-- directory
ni D:/test/subdir/item # <-- file
cd D:/test
ni -Type SymbolicLink D:/test/subdir/item_link -Target ./item

Expected: file symlink to D:/test/subdir/item, with target ./item
Got: directory symlink D:/test/subdir/item, with target ./item
The the file D:/test/item is used for target check, it's a directory, so a directory symlink is created (but the actual target is D:/test/subdir/item, which is a file).

Proposed fixes

There are 2 possible correct behaviors I see here:

  1. Always resolve symlink target to an absolute path in New-Item. This effectively prevents PowerShell from creating symlinks with relative paths to target.
  2. Allow relative paths, but when checking for target type (file/directory), use the path Join-Path $Path $Target internally, but still write $Target as provided by user (relative) into the symlink itself. This is imo the better solution, allows the user to create symlinks with relative paths, but still correctly detects the type.

Environment data


Name                           Value
----                           -----
PSVersion                      7.2.0-preview.4
PSEdition                      Core
GitCommitId                    7.2.0-preview.4
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. added
    Needs-Triage
    on Apr 14, 2021
  2. mklement0 commented on Apr 15, 2021

    @mklement0
    Contributor

    Thanks for writing this up.

    Re behavior 1. (resolving to full paths before creating the symlink):

    We do not want this, because defining symlinks that reference their targets via relative paths is an important feature, which enables moving such symlinks - along with their targets - to a different location without breaking things.

    Therefore - I agree with your preference - we want behavior 2.

    With that in mind, we want:

    • preserving relative targets as specified in the symlink's actual definition (potentially after normalizing path separators to the platform-native form).

    • for the sake of validating the target on creation, an existence check relative to the symlink's directory.

      • Currently, such checks are not performed (in terms of resulting in errors), except if the target is specified as a full path AND that path starts with a nonexistent drive specification or a nonexistent UNC share.

      • Conversely, you may want to - by way of opt-in - create a symlink to a target that you know not to exist yet.

        • For technical reasons, on Windows this additionally requires explicitly indicating the target's file-system type (file vs. directory).
      • See New-Item symlinks cannot be created if destination (target) is non-existent or not accessible #9067 (comment) for a discussion of these issues.

  3. added
    WG-Engine-Providers
    on Apr 15, 2021
  4. mklement0 commented on Apr 15, 2021

    @mklement0
    Contributor

    If this gets fixed as suggested, the following is a moot point, but just to prevent additional confusion:

    #12797, which, as you state, was conceptually the wrong fix, only partially achieved what it tried to do: a target path such as .\foo is recognized as a relative path and resolved against $PWD, but the equivalent foo (no .\ prefix) is not, and is currently still resolved against the process' current directory ([Environment]::CurrentDirectory); see #15161 for a repro (since closed, because it will implicitly also be resolved by resolving this issue).

  5. added
    Issue-Bug
    and removed
    Needs-Triage
    on Jun 10, 2021
  6. daxian-dbw commented on Jun 11, 2021

    @daxian-dbw
    Member

    The Engine WG spent ~25 minutes discussing about this issue. We agreed that the proposed fix no.2 is reasonable (quoted below). Namely, a relative path specified for -Target should be resolved using the path to the symbolic link, instead of powershell's current working directory.

    Allow relative paths, but when checking for target type (file/directory), use the path Join-Path $Path $Target internally, but still write $Target as provided by user (relative) into the symlink itself. This is imo the better solution, allows the user to create symlinks with relative paths, but still correctly detects the type.

    This makes sense because when accessing a file/directory symbolic that is associated with a relative path, such as Get-Content <symlink>, the relative path is resolved using the symlink path. So, we should be consistent in resolving the target relative path when creating a symbolic link with New-Item.

    This proposed fix would be a breaking change to PowerShell 7.1. It feels like the right thing to do, but we need to evaluate the impact before proceeding.


    Interestingly, our discussion led to another idea when comparing New-Item with mklink, which we want to throw out here for more discussion.

    When creating a symbolic using mklink, mklink doesn't check the existence of the specified <target> path. It creates a file symbolic by default, and creates a directory symbolic when /d is specified.

    As is shown in the screenshot below, myfolder is an existing directory, but mklink my-link c:\arena\tmp\test-2\myfolder creates a file symbolic, even though the target path is an existing directory.

    image

    So, maybe New-Item should work similarly as mklink in creating a symbolic link?
    - does not check on the existence of target path
    - create file symbolic by default, and add a new switch parameter for creating directory symbolic

    This would be a breaking change too, in that if target points to an existing directory, a directory symbolic will be create with the current behavior, but a file symbolic will be created if we change to the mklink behavior.

  7. iSazonov commented on Jun 11, 2021

    @iSazonov
    Collaborator

    If it is a bug why we would say "breaking change"? :-)

  8. dogancelik commented on Aug 23, 2021

    @dogancelik

    I was going to comment on #15750 but it was closed.

    New-Item Junction example:
    Pwsh version: 7.1.4

    New-Item '.\node_modules\example-project-base\' -ItemType Junction -Value '.\example-project-base\'
    # New-Item: Could not find item .\example-project-base\.

    PowerShell version: 5.1.19041.1023:

    New-Item '.\node_modules\example-project-base\' -ItemType Junction -Value '.\example-project-base\'
    #    Directory: C:\example-project\node_modules
    # Mode                 LastWriteTime         Length Name
    # ----                 -------------         ------ ----
    # d----l        2021.08.23     23:27                example-project-base
  9. Xiphoseer commented on Jun 27, 2022

    @Xiphoseer

    I ran into this regression today and found it rather tricky to find this issue because a lot of parts just work until they don't. I hope the following points help others find it more easily and deal with it:

    1. Relative paths that start with ..\ (or ../) are not supported by the current PowerShell implementation, but happen to work in many cases, specifically, when the path exists relative to the directory PowerShell was started in. (../<username> is a good candidate to check that, in console windows started in the home directory).
      • There is little reason for the following code to check for literal ./ or .\ at the start of the target path. Those are not the only valid relative paths. Instead, I'd argue that !System.IO.Path.IsPathRooted(strTargetPath) should be used.
        var normalizedTargetPath = strTargetPath;
        if (strTargetPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) ||
        strTargetPath.StartsWith("./", StringComparison.OrdinalIgnoreCase))
        {
        normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan(2));
        }
        Alternatively, Path.Join could be called unconditionally, because rooted paths just discard the first part of the join anyways.
    2. The new feature, which we'd like to keep is that only the relative path is stored on disk, while PWSH 5 made every path absolute first, then checked whether it exists and then set the absolute path into the reparse point. This would not work well with git repos.
    3. When a binary (e.g. PowerShell) calls CreateSymbolicLink, there's a flag called SYMBOLIC_LINK_FLAG_DIRECTORY, whose only effect is to switch the result of GetFileAttributesA from FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_REPARSE_POINT to FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT. That's the reason PowerShell needs to figure out why that target is a directory in the first place, which isn't something Linux needs.
    4. In fact, this matters so little, that you can Get-ChildItem symlink/subfolder through a symlink with the wrong attribute (adding to the confusion). The only thing that actually breaks is getting a handle to the target directory via CreateFile. This could be considered a bug inside of windows (and breaks the way flutter detects invalid links on windows, which is how I got here in the first place)
    5. Powershell also needs to take care of replacing / with \ because that causes different sets of errors if written to the repare point with un-normalized forward slashes.

    To summarize: If you need to work around this bug right now, just prefix all relative paths with .\ even if they start with ..\ already. This is both a regression in PowerShell from 5 to 7 (e.g. New-Item -ItemType SymbolicLink -Path "data" -Target "..\data" no longer works reliably) and an area of the operating system that still breaks in mysterious and under-documented ways if not handled right (e.g. creating symlinks using the Win32 api with forward slashes or pointing to the wrong type of filesystem entry)

  10. God-damnit-all commented on Aug 20, 2022

    @God-damnit-all
    Contributor

    To summarize: If you need to work around this bug right now, just prefix all relative paths with .\ even if they start with ..\ already. This is both a regression in PowerShell from 5 to 7 (e.g. New-Item -ItemType SymbolicLink -Path "data" -Target "..\data" no longer works reliably) and an area of the operating system that still breaks in mysterious and under-documented ways if not handled right (e.g. creating symlinks using the Win32 api with forward slashes or pointing to the wrong type of filesystem entry)

    Additionally, you need to be in the working directory you want to add the directory-based symbolic link to because PowerShell is currently detecting whether a path is a file or a folder based on your current working directory rather than relative to the new item's path.

    Lastly, you have to use double-quotes, if the relative path is in single-quotes it won't work properly.

    This is rather contrived, I wish there could just be a switch parameter to specify that it's a directory I want to make rather than a file, or maybe its own special type like 'SymbolicLinkDir'.

  11. 7 remaining items

  12. added
    In-PR
    on Dec 18, 2023
  13. added
    Resolution-No Activity
    and removed
    Resolution-No Activity
    on Nov 11, 2024
  14. kodra-dev commented on Nov 21, 2024

    @kodra-dev

    Is there any solution to this? What's the true Powershell equivalent of mklink /D now?

  15. msftrncs commented on Nov 22, 2024

    @msftrncs
    Contributor
    • Two new item types FileSymbolicLink and DirectorySymbolicLink should be introduced to make the equivalent of mklink and mklink /D available in PowerShell. On non-Windows systems, they would be treated as synonyms of SymbolicLink, and on Windows, PowerShell would skip the target check and create the specified type of symbolic link.

    Ideally, PowerShell should still check the link type, and report errors if it finds the target but the type is wrong.

    Also, there seems to be more wrong with the original fix than I found discussed here. Interactively, the previous fix seems to work as described using the CWD, but in a script, it does not appear to use the CWD to resolve the relative link. CD/Set-Location/Push-Location do not help the New-Item command correctly interpret the relative path and resolve the target. As long as the target is relative to the path PowerShell (pwsh.exe) was originally started in at the point the script was executed, then it works fine.

    Edit: to note that Daniel Seiler (@Xiphoseer) 's reference to adding a ".\" to the relative path resolves the difference between interactive and script mode I mentioned above...

  16. microsoft-github-policy-service commented on Dec 3, 2024

    @microsoft-github-policy-service
    Contributor

    📣 Hey Matěj Kafka (@MatejKafka), how did we do? We would love to hear your feedback with the link below! 🗣️

    🔗 https://aka.ms/PSRepoFeedback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-FileSystem-ProviderIn-PRIssue-BugWG-CmdletsWG-Engine-Providers

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions