Skip to content

Fix incorrect operand size for long-form IL local/argument instructions in InstructionEncoder - #128279

Merged
MichalStrehovsky merged 2 commits into
mainfrom
copilot/fix-operand-encoding-il-instructions
Jun 15, 2026
Merged

MichalStrehovsky merged 2 commits into
mainfrom
copilot/fix-operand-encoding-il-instructions

Conversation

Copilot AI commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

InstructionEncoder was emitting a 4-byte int32 operand for long-form local/argument opcodes (ldloc, stloc, ldloca, ldarg, ldarga, starg). Per ECMA-335, these opcodes take a 2-byte unsigned short operand. For example, StoreLocal(256) was emitting FE 0E 00 01 00 00 instead of the correct FE 0E 00 01.

Changes

  • InstructionEncoder.cs — all six Load/Store local/argument methods:

    • WriteInt32(slotIndex) → WriteUInt16((ushort)slotIndex) for the long-form branch
    • Range guard changed from slotIndex > 0 to unchecked((uint)slotIndex) <= ushort.MaxValue, so indexes above 65535 now throw ArgumentOutOfRangeException
    • XML doc <exception> comments updated to reflect the new upper bound
  • InstructionEncoderTests.cs — all six corresponding test methods:

    • il.XXX(int.MaxValue) call replaced with il.XXX(ushort.MaxValue) (now a valid, in-range input)
    • Expected byte arrays corrected from 6-byte to 4-byte sequences (e.g. 0xFE, 0x0E, 0xFF, 0xFF instead of 0xFE, 0x0E, 0xFF, 0xFF, 0xFF, 0x7F)
    • Added Assert.Throws<ArgumentOutOfRangeException> for ushort.MaxValue + 1 and int.MaxValue
Original prompt

Fix incorrect operand encoding for long-form IL local/argument instructions in InstructionEncoder and add regression coverage.

Context:

  • Repository: dotnet/runtime
  • File: src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs
  • Commit/URL referenced by user: https://github.com/dotnet/runtime/blame/88dbd1173bde444926a06aeb14f507b04b451aa8/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs#L230

Problem:
InstructionEncoder currently emits a 4-byte operand for several long-form local/argument opcodes, for example:

else if (slotIndex > 0)
{
    OpCode(ILOpCode.Stloc);
    CodeBuilder.WriteInt32(slotIndex);
}

This is incorrect for ECMA-335 short-inline variable operands. Long-form local/argument opcodes such as ldloc, stloc, ldloca, ldarg, ldarga, and starg use a 2-byte unsigned local/argument index operand, not a 4-byte int32 operand. The _s forms use a 1-byte operand, and the dedicated _0 through _3 forms have no operand.

Tasks:

  1. Audit InstructionEncoder.cs for all similar local/argument encoding patterns, especially:
    • LoadLocal
    • StoreLocal
    • LoadLocalAddress
    • LoadArgument
    • LoadArgumentAddress
    • StoreArgument
  2. Fix long-form local/argument operand emission to write a 2-byte unsigned operand (ushort) instead of 4 bytes.
  3. Adjust validation/range checks so indexes greater than ushort.MaxValue are rejected with ArgumentOutOfRangeException, and negative indexes continue to be rejected.
  4. Preserve optimal encodings where applicable:
    • local load/store indexes 0-3 should still use dedicated single-byte opcodes
    • indexes <= byte.MaxValue should still use _s forms where currently used
    • indexes between 256 and 65535 should use the non-short form with a 2-byte operand
  5. Add regression tests in the System.Reflection.Metadata test suite that verify exact bytes emitted for the relevant methods/opcodes, including at least:
    • StoreLocal(256) emits FE 0E 00 01 (opcode stloc, ushort operand 256 little-endian), not six bytes
    • similar tests for LoadLocal(256), LoadLocalAddress(256), LoadArgument(256), LoadArgumentAddress(256), and StoreArgument(256)
    • boundary tests for ushort.MaxValue succeeding and ushort.MaxValue + 1 throwing, if consistent with the existing test style
  6. Run or document relevant test commands if possible.

Please create a pull request with the fix and regression tests.

The following is the prior conversation context from the user's chat exploration (may be truncated):

User: is there a bug around ILOpCode.Stloc writing?

Assistant: Yes — InstructionEncoder.StoreLocal appears to write the wrong operand size for the long-form stloc opcode.

In StoreLocal(int slotIndex), for slotIndex > byte.MaxValue, it emits:

else if (slotIndex > 0)
{
    OpCode(ILOpCode.Stloc);
    CodeBuilder.WriteInt32(slotIndex);
}

But ILOpCode.Stloc is 0xfe0e, i.e. the long local-store form. Per IL encoding, stloc takes an unsigned int16 local index operand, not int32. The corresponding long local load/address/arg forms have the same issue pattern in this file too:

  • ldloc writes Int32
  • stloc writes Int32
  • ldloca writes Int32
  • ldarg, ldarga, starg write Int32

For stloc, this means encoding local slot 256 would produce:

FE 0E 00 01 00 00

instead of the expected:

FE 0E 00 01

assuming little-endian operand bytes.

So yes, around ILOpCode.Stloc writing, the likely bug is that CodeBuilder.WriteInt32(slotIndex) should be WriteUInt16((ushort)slotIndex) or equivalent, and the accepted range should probably be ushort.MaxValue, not any positive int.

User: make a PR that fixes the bug and adds a regression test. look for similar patterns elsewhere (e.g ldloc/ldloca/ldarg/etc.)

Assistant: I’m waiting for your response to the confirmation dialog so I can continue creating the PR.

This pull request was created from Copilot chat.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-reflection-metadata
See info in area-owners.md if you want to be subscribed.

… instructions

Long-form local/argument opcodes (ldloc, stloc, ldloca, ldarg, ldarga, starg)
take a 2-byte unsigned short operand per ECMA-335, not a 4-byte int32.

- Change WriteInt32 to WriteUInt16 in all six methods: LoadLocal, StoreLocal,
  LoadLocalAddress, LoadArgument, LoadArgumentAddress, StoreArgument
- Tighten range check: reject indexes > ushort.MaxValue with ArgumentOutOfRangeException
- Update XML doc comments to reflect the new upper bound
- Fix regression tests to expect correct 4-byte sequences and verify that
  ushort.MaxValue succeeds while ushort.MaxValue+1 and int.MaxValue throw

Agent-Logs-Url: https://github.com/dotnet/runtime/sessions/b47df461-9f6f-4067-a596-9f4b69ec5d4d

Co-authored-by: MichalStrehovsky <[email protected]>
Copilot AI requested review from Copilot and removed request for Copilot May 16, 2026 04:45
Copilot AI changed the title [WIP] Fix incorrect operand encoding for long-form IL instructions Fix incorrect operand size for long-form IL local/argument instructions in InstructionEncoder May 16, 2026
Copilot AI requested a review from MichalStrehovsky May 16, 2026 04:46
@MichalStrehovsky
MichalStrehovsky marked this pull request as ready for review May 17, 2026 05:07
Copilot AI review requested due to automatic review settings May 17, 2026 05:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR corrects InstructionEncoder’s encoding of long-form local and argument IL instructions so their operands are emitted as 2-byte unsigned indexes, matching IL encoding rules.

Changes:

  • Writes ushort operands for long-form ldloc, stloc, ldloca, ldarg, ldarga, and starg.
  • Rejects indexes above ushort.MaxValue while preserving short/dedicated opcode encodings.
  • Updates tests to verify corrected byte sequences and upper-bound failures.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs Fixes operand size and range validation for local/argument instruction encoders.
src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/Encoding/InstructionEncoderTests.cs Updates expected encodings and adds out-of-range coverage for affected methods.

@MichalStrehovsky

Copy link
Copy Markdown
Member

@dotnet/area-system-reflection-metadata who would be the best to review this? It should be trivial enough, the original code was just plain wrong.

@MichalStrehovsky

Copy link
Copy Markdown
Member

@jeffhandley could you help me find a reviewer for this please?

@MichalStrehovsky

Copy link
Copy Markdown
Member

@tmat is this something you could have a look at please?

@MichalStrehovsky
MichalStrehovsky merged commit 24097f2 into main Jun 15, 2026
89 of 96 checks passed
@MichalStrehovsky
MichalStrehovsky deleted the copilot/fix-operand-encoding-il-instructions branch June 15, 2026 23:38
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone Jun 17, 2026
eiriktsarpalis pushed a commit that referenced this pull request Jul 15, 2026
…ns in InstructionEncoder (#128279)

`InstructionEncoder` was emitting a 4-byte `int32` operand for long-form
local/argument opcodes (`ldloc`, `stloc`, `ldloca`, `ldarg`, `ldarga`,
`starg`). Per ECMA-335, these opcodes take a **2-byte unsigned short**
operand. For example, `StoreLocal(256)` was emitting `FE 0E 00 01 00 00`
instead of the correct `FE 0E 00 01`.

## Changes

- **`InstructionEncoder.cs`** — all six `Load`/`Store` local/argument
methods:
- `WriteInt32(slotIndex)` → `WriteUInt16((ushort)slotIndex)` for the
long-form branch
- Range guard changed from `slotIndex > 0` to
`unchecked((uint)slotIndex) <= ushort.MaxValue`, so indexes above 65535
now throw `ArgumentOutOfRangeException`
- XML doc `<exception>` comments updated to reflect the new upper bound

- **`InstructionEncoderTests.cs`** — all six corresponding test methods:
- `il.XXX(int.MaxValue)` call replaced with `il.XXX(ushort.MaxValue)`
(now a valid, in-range input)
- Expected byte arrays corrected from 6-byte to 4-byte sequences (e.g.
`0xFE, 0x0E, 0xFF, 0xFF` instead of `0xFE, 0x0E, 0xFF, 0xFF, 0xFF,
0x7F`)
- Added `Assert.Throws<ArgumentOutOfRangeException>` for
`ushort.MaxValue + 1` and `int.MaxValue`

<!-- START COPILOT ORIGINAL PROMPT -->



<details>

<summary>Original prompt</summary>

> Fix incorrect operand encoding for long-form IL local/argument
instructions in `InstructionEncoder` and add regression coverage.
> 
> Context:
> - Repository: `dotnet/runtime`
> - File:
`src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs`
> - Commit/URL referenced by user:
`https://github.com/dotnet/runtime/blame/88dbd1173bde444926a06aeb14f507b04b451aa8/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs#L230`
> 
> Problem:
> `InstructionEncoder` currently emits a 4-byte operand for several
long-form local/argument opcodes, for example:
> 
> ```csharp
> else if (slotIndex > 0)
> {
>     OpCode(ILOpCode.Stloc);
>     CodeBuilder.WriteInt32(slotIndex);
> }
> ```
> 
> This is incorrect for ECMA-335 short-inline variable operands.
Long-form local/argument opcodes such as `ldloc`, `stloc`, `ldloca`,
`ldarg`, `ldarga`, and `starg` use a 2-byte unsigned local/argument
index operand, not a 4-byte int32 operand. The `_s` forms use a 1-byte
operand, and the dedicated `_0` through `_3` forms have no operand.
> 
> Tasks:
> 1. Audit `InstructionEncoder.cs` for all similar local/argument
encoding patterns, especially:
>    - `LoadLocal`
>    - `StoreLocal`
>    - `LoadLocalAddress`
>    - `LoadArgument`
>    - `LoadArgumentAddress`
>    - `StoreArgument`
> 2. Fix long-form local/argument operand emission to write a 2-byte
unsigned operand (`ushort`) instead of 4 bytes.
> 3. Adjust validation/range checks so indexes greater than
`ushort.MaxValue` are rejected with `ArgumentOutOfRangeException`, and
negative indexes continue to be rejected.
> 4. Preserve optimal encodings where applicable:
> - local load/store indexes 0-3 should still use dedicated single-byte
opcodes
> - indexes <= `byte.MaxValue` should still use `_s` forms where
currently used
> - indexes between 256 and 65535 should use the non-short form with a
2-byte operand
> 5. Add regression tests in the System.Reflection.Metadata test suite
that verify exact bytes emitted for the relevant methods/opcodes,
including at least:
> - `StoreLocal(256)` emits `FE 0E 00 01` (opcode `stloc`, ushort
operand 256 little-endian), not six bytes
> - similar tests for `LoadLocal(256)`, `LoadLocalAddress(256)`,
`LoadArgument(256)`, `LoadArgumentAddress(256)`, and
`StoreArgument(256)`
> - boundary tests for `ushort.MaxValue` succeeding and `ushort.MaxValue
+ 1` throwing, if consistent with the existing test style
> 6. Run or document relevant test commands if possible.
> 
> Please create a pull request with the fix and regression tests.
> 
> The following is the prior conversation context from the user's chat
exploration (may be truncated):
> 
> User: is there a bug around ILOpCode.Stloc writing?
> 
> Assistant: Yes — **`InstructionEncoder.StoreLocal` appears to write
the wrong operand size for the long-form `stloc` opcode**.
> 
> In `StoreLocal(int slotIndex)`, for `slotIndex > byte.MaxValue`, it
emits:
> 
> ```csharp name=InstructionEncoder.cs
url=https://github.com/dotnet/runtime/blob/88dbd1173bde444926a06aeb14f507b04b451aa8/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs#L264-L268
> else if (slotIndex > 0)
> {
>     OpCode(ILOpCode.Stloc);
>     CodeBuilder.WriteInt32(slotIndex);
> }
> ```
> 
> But `ILOpCode.Stloc` is `0xfe0e`, i.e. the long local-store form. Per
IL encoding, `stloc` takes an **unsigned int16** local index operand,
not int32. The corresponding long local load/address/arg forms have the
same issue pattern in this file too:
> 
> - `ldloc` writes `Int32`
> - `stloc` writes `Int32`
> - `ldloca` writes `Int32`
> - `ldarg`, `ldarga`, `starg` write `Int32`
> 
> For `stloc`, this means encoding local slot 256 would produce:
> 
> ```text
> FE 0E 00 01 00 00
> ```
> 
> instead of the expected:
> 
> ```text
> FE 0E 00 01
> ```
> 
> assuming little-endian operand bytes.
> 
> So yes, around `ILOpCode.Stloc` writing, the likely bug is that
`CodeBuilder.WriteInt32(slotIndex)` should be
`WriteUInt16((ushort)slotIndex)` or equivalent, and the accepted range
should probably be `ushort.MaxValue`, not any positive `int`.
> 
> User: make a PR that fixes the bug and adds a regression test. look
for similar patterns elsewhere (e.g ldloc/ldloca/ldarg/etc.)
> 
> Assistant: I’m waiting for your response to the confirmation dialog so
I can continue creating the PR.
> 
> 


</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

*This pull request was created from Copilot chat.*
>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: MichalStrehovsky <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 18, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants