-
Notifications
You must be signed in to change notification settings - Fork 1.4k
CA1838 Avoid 'StringBuilder' parameters for P/Invokes #7186
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
Changes from all commits
994b696
4b519a9
3a88ed9
638775f
751fea3
661c2c8
4f0424c
e042e66
4ddf661
8f0c31c
04e4a1b
903f35d
69cf05f
300179b
c392277
de3618c
a0178d7
54878ac
567cc08
8af24e5
031af51
b4f6bf7
b5f60db
53d3da4
0a97bfd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -569,30 +569,36 @@ internal static string GetRuntimeVersion(string path) | |
| #if FEATURE_MSCOREE | ||
| if (NativeMethodsShared.IsWindows) | ||
| { | ||
| StringBuilder runtimeVersion; | ||
| uint hresult; | ||
| #if DEBUG | ||
| // Just to make sure and exercise the code that doubles the size | ||
| // every time GetRequestedRuntimeInfo fails due to insufficient buffer size. | ||
| // Just to make sure and exercise the code that uses dwLength to allocate the buffer | ||
| // when GetRequestedRuntimeInfo fails due to insufficient buffer size. | ||
| int bufferLength = 1; | ||
| #else | ||
| int bufferLength = 11; // 11 is the length of a runtime version and null terminator v2.0.50727/0 | ||
elachlan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| #endif | ||
| do | ||
| { | ||
| runtimeVersion = new StringBuilder(bufferLength); | ||
| hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out _); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That said, I'm not a fan of this code, so I'm glad it's gone 😁 |
||
| bufferLength *= 2; | ||
| } while (hresult == NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER); | ||
|
|
||
| if (hresult == NativeMethodsShared.S_OK) | ||
| unsafe | ||
| { | ||
| return runtimeVersion.ToString(); | ||
| } | ||
| else | ||
| { | ||
| return String.Empty; | ||
| } | ||
| // Allocate an initial buffer | ||
| char* runtimeVersion = stackalloc char[bufferLength]; | ||
|
|
||
| // Run GetFileVersion, this should succeed using the initial buffer. | ||
| // It also returns the dwLength which is used if there is insufficient buffer. | ||
| uint hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out int dwLength); | ||
|
|
||
| if (hresult == NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER) | ||
| { | ||
| // Allocate new buffer based on the returned length. | ||
| char* runtimeVersion2 = stackalloc char[dwLength]; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there an unstackalloc? And maybe check what dwLength is? If dwLength is big, it would be good not to overrun the stack. I imagine we'd have a little more space if we can un-allocate the first stack before allocating the second. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No Its scoped the the current method.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/stackalloc |
||
| runtimeVersion = runtimeVersion2; | ||
|
|
||
| // Get the RuntimeVersion in this second call. | ||
| bufferLength = dwLength; | ||
| hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out dwLength); | ||
| } | ||
|
|
||
| return hresult == NativeMethodsShared.S_OK ? new string(runtimeVersion, 0, dwLength - 1) : string.Empty; | ||
| } | ||
| } | ||
| else | ||
| { | ||
|
|
@@ -603,7 +609,6 @@ internal static string GetRuntimeVersion(string path) | |
| #endif | ||
| } | ||
|
|
||
|
|
||
| /// <summary> | ||
| /// Import assembly dependencies. | ||
| /// </summary> | ||
|
|
@@ -790,7 +795,7 @@ private static AssemblyNameExtension ConstructAssemblyName(IntPtr asmMetaPtr, ch | |
| // Construct the assembly name. (Note asmNameLength should/must be > 0.) | ||
| var assemblyName = new AssemblyName | ||
| { | ||
| Name = new string(asmNameBuf, 0, (int) asmNameLength - 1), | ||
| Name = new string(asmNameBuf, 0, (int)asmNameLength - 1), | ||
| Version = new Version( | ||
| asmMeta.usMajorVersion, | ||
| asmMeta.usMinorVersion, | ||
|
|
@@ -911,7 +916,7 @@ public static string GetRuntimeVersion(string path) | |
| // Read the PE header signature | ||
|
|
||
| sr.BaseStream.Position = peHeaderOffset; | ||
| if (!ReadBytes(sr, (byte) 'P', (byte) 'E', 0, 0)) | ||
| if (!ReadBytes(sr, (byte)'P', (byte)'E', 0, 0)) | ||
| { | ||
| return string.Empty; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,6 +31,16 @@ internal static class GlobalAssemblyCache | |
| /// </summary> | ||
| internal static readonly GetGacEnumerator gacEnumerator = GetGacNativeEnumerator; | ||
|
|
||
| /// <summary> | ||
| /// Lazy loaded cached root path of the GAC. | ||
| /// </summary> | ||
| private static readonly Lazy<string> _gacPath = new(() => GetGacPath()); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it worth making this lazy vs. just leaving it as a static call? It looks like it's only used once per ResolveComReference call, which seems like not very much to me. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My thought process was to hold a cached static value for it so we only have to call once per global run. I am unsure if that is how it works in practice. |
||
|
|
||
| /// <summary> | ||
| /// Gets the root path of the GAC. | ||
| /// </summary> | ||
| internal static string GacPath => _gacPath.Value; | ||
|
|
||
| /// <summary> | ||
| /// Given a strong name, find its path in the GAC. | ||
| /// </summary> | ||
|
|
@@ -367,16 +377,18 @@ bool specificVersion | |
| } | ||
|
|
||
| /// <summary> | ||
| /// Return the root path of the GAC | ||
| /// Return the root path of the GAC. | ||
| /// </summary> | ||
| internal static string GetGacPath() | ||
| { | ||
| int gacPathLength = 0; | ||
| NativeMethods.GetCachePath(AssemblyCacheFlags.GAC, null, ref gacPathLength); | ||
| StringBuilder gacPath = new StringBuilder(gacPathLength); | ||
| NativeMethods.GetCachePath(AssemblyCacheFlags.GAC, gacPath, ref gacPathLength); | ||
|
|
||
| return gacPath.ToString(); | ||
| unsafe | ||
| { | ||
| NativeMethods.GetCachePath(AssemblyCacheFlags.GAC, null, ref gacPathLength); | ||
| char* gacPath = stackalloc char[gacPathLength]; | ||
| NativeMethods.GetCachePath(AssemblyCacheFlags.GAC, gacPath, ref gacPathLength); | ||
| return new string(gacPath, 0, gacPathLength - 1); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -406,22 +406,33 @@ internal static string StripTypeLibNumberFromPath(string typeLibPath, FileExists | |
|
|
||
| private static string GetModuleFileName(IntPtr handle) | ||
| { | ||
| bool success = false; | ||
| var buffer = new StringBuilder(); | ||
| char[] buffer = null; | ||
|
|
||
| // Try increased buffer sizes if on longpath-enabled Windows | ||
| for (int bufferSize = NativeMethodsShared.MAX_PATH; !success && bufferSize <= NativeMethodsShared.MaxPath; bufferSize *= 2) | ||
| for (int bufferSize = NativeMethodsShared.MAX_PATH; bufferSize <= NativeMethodsShared.MaxPath; bufferSize *= 2) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think it's relevant for this PR, but MaxPath can be as large as int.MaxValue; since that isn't exactly a power of 2, doesn't that mean it could theoretically (if we keep getting ERROR_INSUFFICIENT_BUFFER or pathLength is 0) reach the top, overflow, and throw an exception? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are 23 doublings going from MAX_PATH (260) to int.MaxValue. So its not a trivial risk for long path enabled windows. Interestingly NTFS has a 65,535 character limit and The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. So I think we would run into file system/WinAPI limitations before hitting overflows. I think this would work. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Forgind let me know if you think the additional check is helpful or not. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think that would work. I'd be mildly in favor of adding it, but I don't care too much. It hasn't been an important case up to this point, so I doubt it'll be an important case in the future. It isn't really the point of this PR, but a VerifyThrow at the end of the loop might be a nicer solution? It's almost certainly a bug if we get close to int.MaxValue, and it would be good to make the bug as visible as possible. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added it. |
||
| { | ||
| buffer.EnsureCapacity(bufferSize); | ||
| buffer = System.Buffers.ArrayPool<char>.Shared.Rent(bufferSize); | ||
elachlan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| try | ||
| { | ||
| var handleRef = new System.Runtime.InteropServices.HandleRef(buffer, handle); | ||
| int pathLength = NativeMethodsShared.GetModuleFileName(handleRef, buffer, bufferSize); | ||
|
|
||
| var handleRef = new System.Runtime.InteropServices.HandleRef(buffer, handle); | ||
| int pathLength = NativeMethodsShared.GetModuleFileName(handleRef, buffer, buffer.Capacity); | ||
| bool isBufferTooSmall = (uint)Marshal.GetLastWin32Error() == NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER; | ||
| if (pathLength != 0 && !isBufferTooSmall) | ||
| { | ||
| return new string(buffer, 0, pathLength); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| System.Buffers.ArrayPool<char>.Shared.Return(buffer); | ||
| } | ||
|
|
||
| bool isBufferTooSmall = ((uint)Marshal.GetLastWin32Error() == NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER); | ||
| success = pathLength != 0 && !isBufferTooSmall; | ||
| // Double check that the buffer is not insanely big | ||
| ErrorUtilities.VerifyThrow(bufferSize <= int.MaxValue / 2, "Buffer size approaching int.MaxValue"); | ||
| } | ||
|
|
||
| return success ? buffer.ToString() : string.Empty; | ||
| return string.Empty; | ||
| } | ||
|
|
||
| /// <summary> | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.