使MAF AddInProcess.exe“长路径感知”

Mat*_*ith 6 .net c# windows manifest system.io.file

我正在尝试使Windows 10的Addin(使用MAF)AddInProcess.exe(由AddInProcess类创建)具有“长路径意识”。

困难源于我不拥有 AddInProcess.exe的事实。它是.NET Framework的一部分,并且存在于C:\Windows\Microsoft.NET\Framework64\v4.0.30319\AddInProcess.exe

这是我所做的事情(基于遵循Jeremy Kuhne的Blog条目.NET 4.6.2的指导以及Windows 10上的长路径):

  • 设置AppContext开关Switch.System.IO.UseLegacyPathHandlingSwitch.System.IO.BlockLongPathsfalse。这使某些 .NET API开始接受长路径。但是,在后台调用本机 win32的调用仍然因System.IO.DirectoryNotFoundException其他异常而失败。

  • 应该做的下一件事,但不能做的是编辑应用程序的清单并在下面添加设置。但是,我没有一种(正确的)方法可以做到这一点。如果我做到这一点,那就行了。为了证明它会起作用,我做了以下工作:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
  <windowsSettings>
    <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
  </windowsSettings>
</application>
Run Code Online (Sandbox Code Playgroud)

尽管上述破解工作正常,但在最终用户的计算机上执行此操作显然是不合理的,而且,这将改变所有 行为AddInProcess.exe,而不仅仅是我创建的行为。

问题:是否存在使您无法控制(AddInProcess.exe)的过程的合法方法longPathAware

有没有办法在运行时更改此清单设置?

注意事项

  • 我在组策略编辑器中启用了Win32长路径支持(请参阅.NET 4.6.2和Windows 10上的长路径
  • 我在AppContextSwitchOverrides争取UseLegacyPathHandlingBlockLongPaths受到尊重方面遇到了一些困难。原来是这个问题,我能够解决它。
  • 可以使用扩展路径获取无法使用的方法(例如,前缀路径\\?\(因为这会导致路径长度检查被跳过))。请参阅路径规范化博客条目。但是,这种方法会大得多/冒险的尝试(尝试查找所有可能抛出并修改路径并阻止未来的开发人员添加新用法的当前代码出现)

其他参考资料

Mat*_*ith 0

@RbMm在评论中建议的未记录方法(将PEB'sIsLongPathAwareProcess位设置为1)有效(至少在我使用的 Windows 10 版本:1903 上)。由于该方法是本机 C/C++ 方法,因此我只需将其转换为 C# 可以使用的东西。

可以使用多种方法(C++/CLI、pinvoke)。由于我只是在做“概念验证”,所以我决定只使用 pinvoke,并且在代码质量方面有点懒。

笔记:

  • 此代码不会进行版本检查来确定它是否在支持IsLongPathAwareProcess.
  • 有限的错误检查
  • 我只包含了结构的开始部分PEB,因为这是访问我想要修改的位所需的全部内容。
  • 很可能有一种IsLongPathAwareProcess比我使用的方法更简洁的方法来设置位 ( Marshal.StructureToPtr)
  • 包括一个测试,该测试在执行调用时有效SetIsLongPathAwareProcess,在未调用时失败
  • 请注意我删除 的测试代码C:\Test(以便我可以在目录不存在的情况下多次重新运行测试)

测试代码:

    class Program
    {
        static void Main(string[] args)
        {
            SetIsLongPathAwareProcess();

            string reallyLongDirectory = @"C:\Test\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            reallyLongDirectory = reallyLongDirectory + @"\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            reallyLongDirectory = reallyLongDirectory + @"\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            CreateDirTest(reallyLongDirectory);
            Directory.Delete(@"C:\Test", recursive: true);
        }

        private static void CreateDirTest(string name)
        {
            Console.WriteLine($"Creating a directory that is {name.Length} characters long");

            // Test managed CreateDirectory
            Directory.CreateDirectory(name);

            // Test Native CreateDirectory.  Note this method will only create the "last part" of the directory (not the full path).
            // Also note that it fails if the directory already exists.
            // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectorya
            string nativeName = Path.Combine(name, "TestEnding");
            var r = Native.CreateDirectory(nativeName, null);
            if (!r)
            {
                int currentError = Marshal.GetLastWin32Error();
                Debug.Fail($"Native.CreateDirectory failed: {currentError}");
            }
        }


        // Adapted from https://www.pinvoke.net/default.aspx/ntdll.ntqueryinformationprocess
        private static void SetIsLongPathAwareProcess()
        {
            var currentProcess = Process.GetCurrentProcess();
            IntPtr hProc = currentProcess.Handle;

            IntPtr pPbi = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Native.PROCESS_BASIC_INFORMATION)));
            IntPtr outLong = Marshal.AllocHGlobal(sizeof(long));

            int status = Native.NtQueryInformationProcess(hProc, 0, pPbi, (uint)Marshal.SizeOf(typeof(Native.PROCESS_BASIC_INFORMATION)), outLong);

            Marshal.FreeHGlobal(outLong);

            //STATUS_SUCCESS = 0
            if (status == 0)
            {
                var pbi = Marshal.PtrToStructure<Native.PROCESS_BASIC_INFORMATION>(pPbi);
                var pPeb = pbi.PebBaseAddress;

                var peb = Marshal.PtrToStructure<Native.PEB_Beginning>(pPeb);

                var bitField1 = peb.BitField1;
                peb.BitField1 = bitField1 | Native.PEBBitField1.IsLongPathAwareProcess;
                Marshal.StructureToPtr<Native.PEB_Beginning>(peb, pPeb, false);
            }

            //Free allocated space
            Marshal.FreeHGlobal(pPbi);
        }

        static class Native
        {
            // http://pinvoke.net/default.aspx/Structures/PROCESS_BASIC_INFORMATION.html
            [StructLayout(LayoutKind.Sequential, Pack = 1)]
            internal struct PROCESS_BASIC_INFORMATION
            {
                public IntPtr ExitStatus;
                public IntPtr PebBaseAddress;
                public IntPtr AffinityMask;
                public IntPtr BasePriority;
                public UIntPtr UniqueProcessId;
                public IntPtr InheritedFromUniqueProcessId;

                public int Size
                {
                    get { return (int)Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION)); }
                }
            }

            [Flags]
            internal enum PEBBitField1 : byte
            {
                None = 0,
                ImageUsesLargePages = 1 << 0,
                IsProtectedProcess = 1 << 1,
                IsImageDynamicallyRelocated = 1 << 2,
                SkipPatchingUser32Forwarders = 1 << 3,
                IsPackagedProcess = 1 << 4,
                IsAppContainer = 1 << 5,
                IsProtectedProcessLight = 1 << 6,
                IsLongPathAwareProcess = 1 << 7
            }

            // Note: this only contains the "beginning" of the PEB structure
            // but that is all we need for access to the IsLongPathAwareProcess bit
            // Used as a guide: https://github.com/processhacker/processhacker/blob/master/phnt/include/ntpebteb.h#L75
            // Related: https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-peb
            [StructLayout(LayoutKind.Sequential, Pack = 1)]
            internal struct PEB_Beginning
            {
                Byte InheritedAddressSpace;
                Byte ReadImageFileExecOptions;
                Byte BeingDebugged;
                public PEBBitField1 BitField1;
            };

            // https://www.pinvoke.net/default.aspx/ntdll.ntqueryinformationprocess
            [DllImport("ntdll.dll", SetLastError = true)]
            internal static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, IntPtr processInformation, uint processInformationLength, IntPtr returnLength);

            // The below is for test purposes only:
            // Include CreateDirectory for testing if the long path aware changes work or not.
            // Requires SECURITY_ATTRIBUTES
            // http://pinvoke.net/default.aspx/kernel32/CreateDirectory.html?diff=y
            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
            internal static extern bool CreateDirectory(String path, SECURITY_ATTRIBUTES lpSecurityAttributes);


            // https://www.pinvoke.net/default.aspx/Structures/SECURITY_ATTRIBUTES.html
            [StructLayout(LayoutKind.Sequential)]
            internal class SECURITY_ATTRIBUTES
            {
                internal int nLength = 0;
                // don't remove null, or this field will disappear in bcl.small
                internal unsafe byte* pSecurityDescriptor = null;
                internal int bInheritHandle = 0;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果您在控制台应用程序中使用此代码,您仍然可以通过手动设置来longPathAware测试它是否正常工作:longPathAwarefalseapp.manifest

<application xmlns="urn:schemas-microsoft-com:asm.v3">
  <windowsSettings>
    <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">false</longPathAware>
  </windowsSettings>
</application>
Run Code Online (Sandbox Code Playgroud)