stub-mask-overflow

A mask built from a length that can wrap, in machine code a stub generator writes.

Group
Code
Runs
Runs under ur scan: ur scan --rule stub-mask-overflow
Level
warning
Reads
Every file
Fix
None: the right bound depends on what the stub's caller gives it

Why

A stub generator, as HotSpot's StubGenerator, writes machine code through a macro-assembler, and a bzhi in that code builds a mask of the low bits a count names, as many bytes as a length the code computed. bzhi keeps every bit for a count of its operand's width or more, so a length that wraps below zero, or grows past the width, gives a mask of every byte, and a masked store under it writes past the buffer it meant to fill. The C++ is correct whatever the instructions do, so only the code it writes shows the bug. Check the length before building the mask from it, as OpenJDK's cmpl(length, 4); jcc(Assembler::less, ...) leaves a padded tail shorter than four characters to the caller.

The fix, as Ur suggests it: check the length before building the mask.

For agents

Check that a length is within the operand's width on every path before a bzhi builds a mask from it.

Example

src/hotspot/cpu/x86/stubGenerator_x86_64.cpp
#define __ _masm->

void StubGenerator::generate_tail() {
  Label L_exit, L_done;
  const Register length = c_rarg2;
  const Register size = r13;
  const Register mask = r15;

  __ cmpl(length, 0);
  __ jcc(Assembler::lessEqual, L_exit);
  __ movl(size, length);
  __ shrl(size, 2);
  __ cmpb(Address(c_rarg0, length, Address::times_1, -1), '=');
  __ jcc(Assembler::notEqual, L_done);
  __ decrementq(size, 1);
  __ BIND(L_done);
  __ movq(mask, -1);
  __ bzhiq(mask, mask, size);
  __ BIND(L_exit);
  __ ret(0);
}
What Ur prints
$ ur scan --rule stub-mask-overflow
warning[stub-mask-overflow]: possibly: `bzhiq` in `StubGenerator::generate_tail` may take a count past 64, so its mask would keep every bit; `--solver` checks whether a path can
  --> ./src/hotspot/cpu/x86/stubGenerator_x86_64.cpp:18:3 `bzhiq`
  = hint: check the length before building the mask
  = see: CWE-787: Out-of-bounds Write, MITRE (2024-11-19), https://cwe.mitre.org/data/definitions/787.html
scanned 1 file (no framework recognized)
  stub-mask-overflow: 0 high, 1 medium
0 findings and 1 of medium confidence

Try it in the playground →

Source

CWE-787: Out-of-bounds Write, MITRE (2024-11-19).