Skip to content

Fix wrong condition in Memory64 data segment loading#4848

Open
sumleo wants to merge 2 commits intobytecodealliance:mainfrom
sumleo:fix/memory64-data-segment-index-check
Open

Fix wrong condition in Memory64 data segment loading#4848
sumleo wants to merge 2 commits intobytecodealliance:mainfrom
sumleo:fix/memory64-data-segment-index-check

Conversation

@sumleo
Copy link
Contributor

@sumleo sumleo commented Feb 25, 2026

Summary

In load_data_segment_section, the Memory64 code path manually inspects
import/defined memory arrays to determine the memory64 flag. The condition
module->import_memory_count > 0 is incorrect when a module has both imported
and defined memories — a data segment targeting a defined memory
(mem_index >= import_memory_count) would still enter the import branch,
causing an out-of-bounds read.

Fix

Replace the manual flag lookup with the existing has_module_memory64() helper,
which already encapsulates this logic correctly. Apply the same refactor to both
wasm_loader.c and wasm_mini_loader.c.

Before:

uint8 memory_flag;
if (module->import_memory_count > 0) {
    memory_flag = module->import_memories[mem_index].u.memory.mem_type.flags;
}
else {
    memory_flag = module->memories[mem_index - module->import_memory_count].flags;
}
mem_offset_type = memory_flag & MEMORY64_FLAG ? VALUE_TYPE_I64 : VALUE_TYPE_I32;

After:

mem_offset_type = has_module_memory64(module) ? VALUE_TYPE_I64 : VALUE_TYPE_I32;

Impact

Fixes an out-of-bounds array access when a module with both imported and defined
memories has a data segment targeting a defined memory with Memory64 enabled.

The condition for selecting between imported and defined memories
uses `import_memory_count > 0` when it should use
`mem_index < import_memory_count`. When a module has both imported
and defined memories and a data segment targets a defined memory
(mem_index >= import_memory_count), the current condition
incorrectly reads from the import_memories array out of bounds.
/* This memory_flag is from memory instead of data segment */
uint8 memory_flag;
if (module->import_memory_count > 0) {
if (mem_index < module->import_memory_count) {
Copy link
Contributor

Choose a reason for hiding this comment

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

better refactor this code snippet with has_module_memory64 instead, and modify the wasm_mini_loder.c too

Replace the manual import/defined memory flag lookup with a call to
the existing has_module_memory64() helper, which already encapsulates
this logic correctly. Apply the same change to wasm_mini_loader.c.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants