Skip to content

Fix: bug fixes and optomizations#21

Merged
mrLSD merged 2 commits into
masterfrom
fix/audit-jun-02
Jun 2, 2026
Merged

Fix: bug fixes and optomizations#21
mrLSD merged 2 commits into
masterfrom
fix/audit-jun-02

Conversation

@mrLSD

@mrLSD mrLSD commented Jun 2, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Bug Fixes

    • FENCE decoding now follows spec (reserved fields ignored).
    • Fixes to address alignment and trapping for loads, stores, atomics, and branch/jump targets.
    • LR/SC reservation semantics now respect access width.
    • ELF loading now enforces segment size limits and uses the ELF entry point to start execution.
    • CLI rejects unknown dash options and duplicate verbosity flags.
  • Performance

    • CLI argument parser rewritten to handle very large argv without stack overflow.
  • Tests & Docs

    • Added tests for ELF loading, atomics, branches, CLI, and updated changelog/version.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dcd44b9a-4a1b-45cc-bdeb-ebd1fe85d0c5

📥 Commits

Reviewing files that changed from the base of the PR and between 4abf2aa and b33e363.

📒 Files selected for processing (2)
  • CHANGELOG.md
  • risc-v.fsproj
✅ Files skipped from review due to trivial changes (1)
  • risc-v.fsproj

📝 Walkthrough

Walkthrough

This pull request refactors aligned memory access and LR/SC reservation tracking across the Execute modules, broadens FENCE decoding, returns ELF entry points for PC initialization, replaces the CLI parser with a stack-safe implementation, and adds tests and changelog/version updates.

Changes

Core Execution Engine Alignment and Memory API

Layer / File(s) Summary
MachineState API upgrade: reservations and load helpers
MachineState.fs
MachineState.Reservation now tracks both address and width as (int64 * int) option. New public memory load helpers (loadMemoryByte, loadMemoryHalfWord, loadMemoryWord, loadMemoryDoubleWord) are exposed, backed by a private loadBytes routine that ensures consistent byte-address normalization between load and store paths.
RV32I load/store and branch/jump alignment
ExecuteI.fs, Tests/unit/execute.fs, Tests/unit/branch.fs
All RV32I loads/stores route through alignByArchUnsign before invoking MachineState helpers. execJALR aligns jump targets. Branch helper refactored to separate taken-path alignment checks and self-loop detection from not-taken fall-through, ensuring traps and stops only trigger when branches are taken. Updated execBLTU and execBGEU to match. New tests verify taken-branch misalignment traps, taken self-branch stops, and not-taken fall-through with PC assertions.
RV64I load (LWU/LD) and store (SD) alignment
ExecuteI64.fs
64-bit loads (execLWU, execLD) and store (execSD) now align effective addresses via alignByArchUnsign before invoking MachineState load/store helpers, replacing direct loadWord/loadDouble calls.
RV32A atomic operations (LR/SC/AMO word)
ExecuteA.fs, Tests/unit/execute.fs
Load-reserved and store-conditional now align addresses and track 4-byte width. All nine AMO word variants align effective addresses and use loadMemoryWord/storeMemoryWord. Execute dispatcher pre-computes aligned addresses for these operations. Tests verify round-trips through bit-31 addresses and stress large argv without stack overflow for related CLI refactor.
RV64A atomic operations (LR/SC/AMO double)
ExecuteA64.fs, Tests/rv64a/amoSem.fs
Load-reserved and store-conditional now align addresses and track 8-byte width. All nine AMO double-word variants follow the same pattern. Execute dispatcher pre-computes aligned addresses. New tests verify SC.D after LR.W and SC.W after LR.D fail due to width mismatch, confirming reservation width is properly checked.
FENCE instruction decode specification compliance
DecodeI.fs, Tests/unit/decode.fs, Tests/unit/branch.fs
Broadened FENCE recognition to match funct3 = 0b000 regardless of rd/rs1 values (now treated as reserved per spec). Tests verify FENCE decodes with nonzero reserved fields and that FENCE.I (funct3=001) remains unimplemented and decodes to None.

ELF Loading, Entry Point, and CLI Optimization

Layer / File(s) Summary
ELF loading refactor: return entry point and set PC accordingly
Run.fs, Tests/run/run.fs, Tests/unit/app.fs
readElfFile now returns (Map<int64, byte> * int64), explicitly loads PT_LOAD segments, and caps total mapped size. Run destructures the entry point and initializes machine state PC from e_entry instead of a hardcoded address. New tests verify entry-point-based execution, ELF segment size rejection for 32-bit and 64-bit edge cases, and verbosity-dependent register dumping on Stopped and Trap halt states.
CLI argument parser stack-safety optimization
CLI.fs, Tests/unit/cli.fs
Reimplemented fetchArgs as tail-recursive parser with explicit leftover accumulation, replacing stack-overflow-prone recursion. Preserves all prior semantics: short/long options, value-required, Multiple configuration. Tests verify unknown dash options are rejected, duplicate flags do not leak into file lists, and huge non-matching and matching argv arrays complete without stack overflow.
Tests and release
Tests/*, CHANGELOG.md, risc-v.fsproj
Added/updated unit and integration tests covering ELF entry point use, loader memsz limits, branch/jump alignment behavior, atomic reservation width checks, CLI parser behavior, and updated CHANGELOG plus project version bump to 0.6.1.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • mrLSD/riscv-fs#19: Both PRs modify CLI.fs’s fetchArgs argument-parsing logic.
  • mrLSD/riscv-fs#20: Both PRs modify CLI.fs’s recursion/slicing behavior and parsing semantics.

Suggested labels

fix, tests, refactoring, ISA

Poem

🐰 I hopped through bytes both wide and small,
I aligned each address, one and all,
Reservations now know size and scope,
ELF entries guide PC like hope,
CLI no longer falls — it bounces tall.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is too vague and generic, using non-descriptive terms like 'bug fixes and optomizations' that don't convey specific information about the substantial changes in the PR. Replace with a specific title reflecting a main change, such as 'Add address alignment normalization and memory load helpers' or 'Refactor CLI parser for stack safety and improve memory APIs'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/audit-jun-02

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Jun 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (64878c4) to head (b33e363).

Additional details and impacted files
@@            Coverage Diff            @@
##            master       #21   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           21        21           
  Lines         1438      1441    +3     
  Branches       273       280    +7     
=========================================
+ Hits          1438      1441    +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
ExecuteA64.fs (1)

193-198: 💤 Low value

Minor: same redundant alignment pattern as ExecuteA.fs.

Both the dispatcher and individual exec* functions apply alignByArchUnsign. Same observation as ExecuteA.fs—idempotent but could be consolidated.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ExecuteA64.fs` around lines 193 - 198, The call to mstate.alignByArchUnsign
is being applied twice (once in the dispatcher pattern matching on instr in
ExecuteA64.fs and again inside the individual exec* functions), so remove the
redundancy by centralizing alignment in one place: either keep
mstate.alignByArchUnsign in the dispatcher (the match on instr including
LR_D/SC_D/.../InstructionA64.None) and delete the duplicate alignByArchUnsign
calls inside the exec* functions, or remove it from the dispatcher and ensure
each exec* (e.g. the functions handling LR_D, SC_D, AMO*_D) calls
alignByArchUnsign exactly once; update only the code paths that reference
mstate.alignByArchUnsign to ensure alignment is applied exactly once and
behavior remains unchanged.
ExecuteA.fs (1)

192-197: 💤 Low value

Minor: redundant alignment in dispatcher vs individual functions.

The Execute dispatcher applies alignByArchUnsign to the address (lines 192-197), and each exec* function also applies alignByArchUnsign again. While idempotent and harmless, you could consider removing one site for clarity.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ExecuteA.fs` around lines 192 - 197, The dispatcher currently calls
mstate.alignByArchUnsign on addresses before routing to the exec functions, but
each exec* function (e.g., execLR_W, execSC_W, execAMOSWAP_W, etc.) also applies
alignment, causing redundancy; remove the alignment call from the dispatcher
match (the mstate.alignByArchUnsign(...) wrapper) and pass the raw address
values (mstate.getRegister i.rs1 or 0L) so individual exec* handlers remain
responsible for alignment and no duplicate alignment is performed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@ExecuteA.fs`:
- Around line 192-197: The dispatcher currently calls mstate.alignByArchUnsign
on addresses before routing to the exec functions, but each exec* function
(e.g., execLR_W, execSC_W, execAMOSWAP_W, etc.) also applies alignment, causing
redundancy; remove the alignment call from the dispatcher match (the
mstate.alignByArchUnsign(...) wrapper) and pass the raw address values
(mstate.getRegister i.rs1 or 0L) so individual exec* handlers remain responsible
for alignment and no duplicate alignment is performed.

In `@ExecuteA64.fs`:
- Around line 193-198: The call to mstate.alignByArchUnsign is being applied
twice (once in the dispatcher pattern matching on instr in ExecuteA64.fs and
again inside the individual exec* functions), so remove the redundancy by
centralizing alignment in one place: either keep mstate.alignByArchUnsign in the
dispatcher (the match on instr including LR_D/SC_D/.../InstructionA64.None) and
delete the duplicate alignByArchUnsign calls inside the exec* functions, or
remove it from the dispatcher and ensure each exec* (e.g. the functions handling
LR_D, SC_D, AMO*_D) calls alignByArchUnsign exactly once; update only the code
paths that reference mstate.alignByArchUnsign to ensure alignment is applied
exactly once and behavior remains unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c1505247-6ef6-44e4-8444-c970e10ab58c

📥 Commits

Reviewing files that changed from the base of the PR and between 64878c4 and 4abf2aa.

📒 Files selected for processing (15)
  • CLI.fs
  • DecodeI.fs
  • ExecuteA.fs
  • ExecuteA64.fs
  • ExecuteI.fs
  • ExecuteI64.fs
  • MachineState.fs
  • Run.fs
  • Tests/run/run.fs
  • Tests/rv64a/amoSem.fs
  • Tests/unit/app.fs
  • Tests/unit/branch.fs
  • Tests/unit/cli.fs
  • Tests/unit/decode.fs
  • Tests/unit/execute.fs

@mrLSD mrLSD merged commit 4201afa into master Jun 2, 2026
4 checks passed
@mrLSD mrLSD deleted the fix/audit-jun-02 branch June 2, 2026 23:05
@mrLSD mrLSD added this to the v0.6.1 milestone Jun 2, 2026
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.

1 participant