Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tests/checks/python-linux/startup_gfx2hlsl_load_desc.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tests/startup_gfx2hlsl_load_desc_check.py
6 changes: 6 additions & 0 deletions tests/cmake/startup_gfx2hlsl_load_desc.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# gfx2hlsl compute buffer load through a modified descriptor (#2901):
# validates that compute buffer loads through a modified or overwritten descriptor word are refused.
if(EXISTS "${INTAKE_PYTHON}")
add_test(NAME startup_gfx2hlsl_load_desc_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_load_desc_check.py")
endif()
4 changes: 4 additions & 0 deletions tests/startup_gfx2hlsl_compute_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -1505,6 +1505,10 @@ def check_formatted_loads():
assert hlsl.count(' = ((ud3 >> ') == width
# Word 3 is overwritten in an otherwise intact native descriptor.
refused('words were rewritten', lambda: translate('L-uint', code=prefix + bytes.fromhex('80038fbe') + LOAD_L + end))
# An instruction writes a derived descriptor word to a separate SGPR (s21), leaving operand s[12:15] intact.
# The indexed formatted load is refused because the descriptor is modified.
refused('indexed load through a modified descriptor',
lambda: translate('L-uint', code=prefix + bytes.fromhex('0dff1587ffff00c0') + LOAD_L + end))
# At a branch target, there is no local descriptor load to prove.
refused('local table load', lambda: translate('L-uint', code=prefix + bytes.fromhex('000082bf') + LOAD_L + end))
local_load = bytes.fromhex('000082bf') + prefix + LOAD_L + end
Expand Down
143 changes: 143 additions & 0 deletions tests/startup_gfx2hlsl_load_desc_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Verify that compute buffer loads through a modified or overwritten descriptor word are refused.

Refs #2901, #2618.
"""
from pathlib import Path
import struct
import sys

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent / 'tools' / 'startup'))

import gfx2hlsl as G # noqa: E402
import startup_gfx2hlsl_compute_check as C # noqa: E402


def sop2(op, d, a, b, lit=None):
return struct.pack('<I', 0x80000000 | op << 23 | d << 16 | b << 8 | a) + (b'' if lit is None else struct.pack('<I', lit))


def sop1(op, d, a):
return struct.pack('<I', 0xbe800000 | d << 16 | op << 8 | a)


W = C.WORDS_A
LOAD_SITE = W.index(bytes.fromhex('001030e004050380'))
STORE_SITE = C.STORE_A

# r = first register of the descriptor (12 for load s[12:15], 16 for store s[16:19])
# Word 1: stride; Word 2: NUM_RECORDS; Word 3: format/OOB
EDITS = {
'descnum copy w1': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 1, 21),
'descnum copy w2': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 2, 21),
'descnum copy w3': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 3, 21),
'descnum alu w2': lambda r: sop2(0x20, 21, r + 2, 130) + sop2(0x20, r + 2, 21, 128),
'in-place and 0 w2': lambda r: sop2(0x0e, r + 2, r + 2, 128),
'constant 0 w2': lambda r: sop1(0x03, r + 2, 128),
}


def translate_code(code):
return G.ComputePipeline(code, C.root_blob(), C.CASES['A'][2], (2, 3, 4)).hlsl_cs()


def check_refusals():
# 1. Base case A translates cleanly without edits
base_hlsl = translate_code(W)
assert 'v5 = r0.Load(a + 0);' in base_hlsl, 'base case A load missing'
assert 'u0.Store(a, v5);' in base_hlsl, 'base case A store missing'

# 2. Check each edit refused for both load and store
for label, edit in EDITS.items():
# Check load refusal
load_code = W[:LOAD_SITE] + edit(12) + W[LOAD_SITE:]
try:
translate_code(load_code)
raise AssertionError(f'expected load refusal for {label}, but translation succeeded')
except G.Unsupported as e:
assert 'buffer load through a modified descriptor' in str(e), (
f'unexpected refusal for load {label}: {e}'
)

# Check store refusal
store_code = W[:STORE_SITE] + edit(16) + W[STORE_SITE:]
try:
translate_code(store_code)
raise AssertionError(f'expected store refusal for {label}, but translation succeeded')
except G.Unsupported as e:
assert 'buffer store through a modified descriptor' in str(e), (
f'unexpected refusal for store {label}: {e}'
)

# 3. Proven stride-0 clear on raw load is accepted (stride0_ok=True for non-indexed load)
# s_and_b32 s13, s13, 0xc000ffff
stride0_inst = sop2(0x0e, 13, 13, 255) + struct.pack('<I', 0xc000ffff)
stride0_hlsl = translate_code(W[:LOAD_SITE] + stride0_inst + W[LOAD_SITE:])
assert 'v5 = r0.Load(a + 0);' in stride0_hlsl, 'stride0 load failed to translate'

# 4. Incorrect stride mask (0xc000fff0) is refused on load
bad_stride_inst = sop2(0x0e, 13, 13, 255) + struct.pack('<I', 0xc000fff0)
try:
translate_code(W[:LOAD_SITE] + bad_stride_inst + W[LOAD_SITE:])
raise AssertionError('expected refusal for bad stride mask on load, but succeeded')
except G.Unsupported as e:
assert 'buffer load through a modified descriptor' in str(e), f'unexpected refusal: {e}'

# 5. Proven structured-to-raw conversion on load descriptor is accepted (raw_conversion_ok=True)
# Extracts stride from s13, clears stride in s13, scales s14 by s21, sets raw OOB in s15.
raw_conv = (
sop2(0x27, 21, 13, 255, 0xe0010) +
sop2(0x0e, 13, 13, 255, 0xc000ffff) +
sop2(0x26, 14, 14, 21) +
sop2(0x0e, 15, 15, 255, 0xcfffffff) +
sop2(0x10, 15, 15, 255, 0x30000000)
)
raw_hlsl = translate_code(W[:LOAD_SITE] + raw_conv + W[LOAD_SITE:])
assert 'v5 = r0.Load(a + 0);' in raw_hlsl, 'raw conversion load failed to translate'

# 6. Incomplete or invalid raw conversion (e.g. constant multiplier 4 instead of extracted stride s21) is refused
bad_raw_conv = (
sop2(0x27, 21, 13, 255, 0xe0010) +
sop2(0x0e, 13, 13, 255, 0xc000ffff) +
sop2(0x26, 14, 14, 132) + # literal 4
sop2(0x0e, 15, 15, 255, 0xcfffffff) +
sop2(0x10, 15, 15, 255, 0x30000000)
)
try:
translate_code(W[:LOAD_SITE] + bad_raw_conv + W[LOAD_SITE:])
raise AssertionError('expected refusal for bad raw conversion on load, but succeeded')
except G.Unsupported as e:
assert 'buffer load through a modified descriptor' in str(e), f'unexpected refusal: {e}'

# 7. Formatted indexed buffer load through a modified descriptor is refused.
# Inserting `s_and_b32 s21, s13, 0xc000ffff` immediately before LOAD_L writes
# a derived descriptor word to s21, leaving the four operand registers s[12:15]
# intact. The indexed formatted load must be refused with 'indexed load through a modified descriptor'.
prefix_l = C.WORDS_L[:C.WORDS_L.index(C.LOAD_L)]
end_l = bytes.fromhex('000081bf')
s_and_s21_s13 = sop2(0x0e, 21, 13, 255, 0xc000ffff)
formatted_mod_code = prefix_l + s_and_s21_s13 + C.LOAD_L + end_l
try:
G.ComputePipeline(formatted_mod_code, C.root_blob(), C.CASES['L-uint'][2], (2, 3, 4)).hlsl_cs()
raise AssertionError('expected refusal for formatted indexed load with modified descriptor, but translated')
except G.Unsupported as e:
assert 'indexed load through a modified descriptor' in str(e), f'unexpected refusal: {e}'

# 8. Negative control: pre-fix mutant (bypassing load descriptor validation)
# Under this mutant, unvalidated loads must translate (escaping detection).
real_load_desc = G.Stage.load_descriptor
try:
G.Stage.load_descriptor = lambda self, tok, what, **kw: self.descriptor(tok)
for label, edit in EDITS.items():
mutant_code = W[:LOAD_SITE] + edit(12) + W[LOAD_SITE:]
res = translate_code(mutant_code)
assert 'v5 = r0.Load(a + 0);' in res, f'mutant failed to reproduce issue on {label}'
finally:
G.Stage.load_descriptor = real_load_desc

print('compute buffer load modified descriptor checks passed')


if __name__ == '__main__':
check_refusals()
49 changes: 42 additions & 7 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -6604,7 +6604,7 @@ def op_s_buffer_load_dwordx8(self, ops, mods):
def op_s_buffer_load_dwordx16(self, ops, mods):
self.op_s_buffer_load_dword(ops, mods, 16)

def buffer_address(self, ops, mods):
def buffer_address(self, ops, mods, *, is_formatted=False):
# MUBUF and MTBUF share the same address calculation: optional index * stride (idxen),
# optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate
# offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe
Expand All @@ -6617,7 +6617,12 @@ def buffer_address(self, ops, mods):
raise Unsupported('buffer modifier %s' % m)
if len(ops) != 4:
raise Unsupported('buffer load with %d operands, expected 4' % len(ops))
key = self.descriptor(ops[2])
idxen, offen = 'idxen' in mods, 'offen' in mods
what = 'indexed load' if idxen else 'buffer load'
if not is_formatted:
key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen)
else:
key = self.descriptor(ops[2])
buf = self.pipe.resource(key, 'buf')
soffset = None
if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]):
Expand All @@ -6627,10 +6632,9 @@ def buffer_address(self, ops, mods):
if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105:
raise Unsupported('buffer soffset %s' % ops[3])
soffset = self.S(sreg[1])
idxen, offen = 'idxen' in mods, 'offen' in mods
terms = []
if idxen and offen:
if key in self.pipe.modified:
if key in getattr(self.pipe, 'modified', ()):
raise Unsupported('indexed load through a modified descriptor')
r = reg_range(ops[1])
if not r or r[0] != 'v' or r[2] - r[1] != 1 or r[2] > 255:
Expand All @@ -6639,7 +6643,7 @@ def buffer_address(self, ops, mods):
terms.append('%s * ud%d' % (self.u('v%d' % r[1]), stride))
terms.append(self.u('v%d' % r[2]))
elif idxen:
if key in self.pipe.modified:
if key in getattr(self.pipe, 'modified', ()):
raise Unsupported('indexed load through a modified descriptor')
r = reg_range(ops[1])
if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255:
Expand Down Expand Up @@ -6789,6 +6793,37 @@ def op_buffer_store_vs(self, ops, mods, count):
self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset)
self.emit(store if self.exec_known else 'if (exec & 1) %s' % store)

def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=False):
"""Resource key for a 4-word buffer load descriptor operand, checking for unproved modifications.

A descriptor modification is accepted only for proven safe transformations:
- stride0_ok: Allows word 1 (STRIDE[29:16]) to be zeroed via `s_and_b32 ... 0xc000ffff`.
Permitted on non-indexed buffer loads (offen or off) where byte addressing is used and
the hardware stride field is not consulted.
- raw_conversion_ok: Allows the complete RDNA2 structured-to-raw buffer conversion:
word 1 stride zeroed (`stride0`), word 2 scaled by the extracted stride (`byte_count`),
and word 3 OOB_SELECT set to raw mode (`oob3` via 0x30000000). Permitted when the load
is non-indexed and the resulting byte range is validated.
Any other scalar ALU modifications or unproven overwrites raise Unsupported.
"""
key = self.descriptor(tok)
rsrc = reg_range(tok)
first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None
if first and first[0] == 'desc':
loaded = tuple(desc_word(first, first[3] + k) for k in range(4))
actual = tuple(self.sym.get(rsrc[1] + k) for k in range(4))
valid = names_one_value(first) and actual == loaded
if names_one_value(first) and stride0_ok:
cleared = loaded[1] + ('stride0',)
valid = valid or actual == (loaded[0], cleared, *loaded[2:])
if not valid and raw_conversion_ok:
valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',))
if (not valid or key in getattr(self.pipe, 'other_modified', ())
or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)):
raise Unsupported('%s through a modified descriptor' % what)
return key
return key

def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False):
"""Resource key for a single loaded descriptor or a proven raw transformation of it."""
rsrc = reg_range(tok)
Expand All @@ -6805,7 +6840,7 @@ def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok
if not valid and raw_conversion_ok:
valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',))
if (not valid or key in getattr(self.pipe, 'other_modified', ())
or (key in self.pipe.modified and not stride0_ok)):
or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)):
raise Unsupported('%s through a modified descriptor' % what)
return key

Expand Down Expand Up @@ -7199,7 +7234,7 @@ def mubuf_format(self, ops, mods, count):
For compute, the caller must validate the native descriptor and reachable byte addresses, and bind the
SRV and entry constants from that same descriptor snapshot.
"""
buf, address = self.buffer_address(ops, mods)
buf, address = self.buffer_address(ops, mods, is_formatted=True)
dst = reg_range(ops[0])
if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != count or dst[2] > 255:
raise Unsupported('formatted buffer load destination %s for %d components' % (ops[0], count))
Expand Down
Loading