Skip to content

Improve exception message for empty assembly loading#124301

Draft
Copilot wants to merge 3 commits intomainfrom
copilot/improve-exception-message
Draft

Improve exception message for empty assembly loading#124301
Copilot wants to merge 3 commits intomainfrom
copilot/improve-exception-message

Conversation

Copy link
Contributor

Copilot AI commented Feb 11, 2026

Description

Loading an empty assembly (0-length byte array or stream) throws BadImageFormatException with the generic message "Bad IL format." This is a common scenario with bugs in dynamically generated assemblies and provides no actionable information.

Changes

Before:

Assembly.Load(new byte[0]);  
// BadImageFormatException: Bad IL format.

After:

Assembly.Load(new byte[0]);
// BadImageFormatException: Assembly image is empty. The stream or byte array must contain a valid PE file.

Implementation

  • Added BadImageFormat_EmptyAssembly resource string
  • Updated Assembly.Load(byte[]) and AssemblyLoadContext.LoadFromStream() to use specific message when input is empty
  • Updated tests to verify error message contains "empty"

The change is scoped to explicit empty checks in managed code. Native code paths (AssemblyNative_LoadFromStream) already assert non-empty input via managed validation.

Original prompt

This section details on the original issue you should resolve

<issue_title>Improve exception message when loading an empty assembly</issue_title>
<issue_description>Based on dotnet/roslyn#39470, a relatively common issue when working with dynamically generated assemblies is that, due to a bug in your code, you attempt to load an empty assembly (e.g., you call Assembly.Load(Stream) with a Stream of Length 0). When this happens, you get a correct, but not particularly helpful exception:

System.BadImageFormatException: Bad IL format.

Would it make sense to improve the exception message, to make it more clear what the issue is?</issue_description>

Comments on the Issue (you are @copilot in this section)

@Dotnet-GitSync-Bot I couldn't figure out the best area label to add to this issue. Please help me learn by adding exactly one [area label](https://github.com/dotnet/runtime/blob/master/docs/area-owners.md). @ Tagging subscribers to this area: @vitek-karas Notify danmosemsft if you want to be subscribed.

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@github-actions github-actions bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Feb 11, 2026
- Added new resource string BadImageFormat_EmptyAssembly
- Updated Assembly.Load and AssemblyLoadContext.LoadFromStream to use the new message
- Updated tests to verify the new error message contains "empty"

Co-authored-by: elinor-fung <47805090+elinor-fung@users.noreply.github.com>
Copilot AI changed the title [WIP] Improve exception message for loading empty assembly Improve exception message for empty assembly loading Feb 11, 2026
Copilot AI requested a review from elinor-fung February 11, 2026 23:25
@elinor-fung elinor-fung added area-AssemblyLoader-coreclr and removed needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners labels Feb 12, 2026
@stephentoub
Copy link
Member

@copilot please invoke the code-review skill and post the analysis/results as a comment on this PR

Copy link
Contributor Author

Copilot AI commented Feb 16, 2026

@copilot please invoke the code-review skill and post the analysis/results as a comment on this PR

🤖 Copilot Code Review — PR #124517

Holistic Assessment

Motivation: ✅ Justified. Loading empty assemblies (0-byte streams/arrays) is a real scenario that users encounter when working with dynamically generated assemblies, and the current generic "Bad IL format" message provides no actionable guidance. The linked Roslyn issue confirms this is a genuine pain point.

Approach: ✅ Sound. The fix is surgical and targeted—it introduces a new, specific resource string for the empty assembly case while preserving the generic message for other BadImageFormat scenarios. The change is behavior-preserving (exception type and throwing conditions unchanged) and only improves diagnostic quality.

Summary: ✅ LGTM. This is a focused, low-risk improvement that makes an error message more actionable. The code changes are minimal, the tests validate the new behavior appropriately, and the approach follows established patterns for error message improvements in the codebase.


Detailed Findings

✅ Core Implementation — Correctly Scoped

The change appropriately:

  • Adds a new resource string (BadImageFormat_EmptyAssembly) rather than modifying the existing generic one (BadImageFormat_BadILFormat), preserving backward compatibility for other error scenarios
  • Updates only the two explicit empty-input checks (rawAssembly.Length == 0 and spanAssembly.IsEmpty) to use the new message
  • Leaves the generic message in place for the "stream too large" case (line 422 in AssemblyLoadContext.cs: if (((ulong)length) > (ulong)Array.MaxLength))

This is the correct approach—specific messages for diagnosable cases, generic messages for others.

✅ Test Quality — Appropriate Validation Strategy

The test assertions use Assert.Contains("empty", ex.Message, StringComparison.OrdinalIgnoreCase), which is the right pattern per dotnet/runtime conventions:

  • Resilient to minor message wording changes
  • Verifies the key diagnostic information is present
  • Avoids brittle exact-string matching

Both empty-byte-array and empty-stream code paths are now covered by tests.

💡 Message Wording — Minor Clarity Consideration

The message reads: "Assembly image is empty. The stream or byte array must contain a valid PE file."

The second sentence could be read as "the problem is the PE file isn't valid" rather than "the problem is there's no data at all." Consider whether a slight rephrasing would be clearer, e.g.:

  • "Assembly image is empty. The stream or byte array must contain data for a valid PE file."
  • "Cannot load empty assembly. The stream or byte array must contain a valid PE file."

However, this is a minor point—the current message is substantially better than "Bad IL format" and clearly mentions "empty," which is the key diagnostic information. This is purely a suggestion for future refinement if desired.

✅ Cross-Cutting Consistency — Other Load Paths Considered

I verified whether file-based loading paths (Assembly.LoadFile) encounter the same issue. File-based loading goes through native code (PEImage::OpenImage), which will fail with a different error path if the file is 0 bytes (native CheckILFormat failure). The empty check is specific to in-memory byte arrays and streams, so limiting the change to those two call sites is correct.


Verdict: This is a well-scoped, low-risk improvement that makes a common error scenario easier to diagnose. No blocking issues identified.

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

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Improve exception message when loading an empty assembly

3 participants