Skip to content

Implement RISC-V dynamic linking - #323

Open
DrXiao wants to merge 11 commits into
sysprog21:masterfrom
DrXiao:feat/dynlink-for-rv32
Open

Implement RISC-V dynamic linking#323
DrXiao wants to merge 11 commits into
sysprog21:masterfrom
DrXiao:feat/dynlink-for-rv32

Conversation

@DrXiao

@DrXiao DrXiao commented Apr 23, 2026

Copy link
Copy Markdown
Collaborator

The proposed changes primarily improve the ELF generation and the RISC-V backend, enabling the build system to generate a dynamically linked shecc targeting the RISC-V architecture.

Although the current changes allow both bootstrapping and test suite to complete successfully, this is still a work in progress. The TODO items are listed as follows:

  • Enhance code quality, comments and commit messages.
  • Confirm the RISC-V ABI compliance.
  • Add a new script (riscv-abi.sh) to validate the RISC-V ABI.
  • Improve the documentation and README.
  • Consolidate arm.mk and riscv.mk into a common build logic (e.g.: configure RUNNER_LD_PREFIX).

Summary by cubic

Adds RV32 dynamic linking using RELA with an ABI-compliant PLT/GOT and __libc_start_main, and switches .rel.plt (Arm) vs .rela.plt (RISC‑V) via ELF_MACHINE_ARM32/ELF_MACHINE_RV32. CI now builds/tests static and dynamic for arm and riscv, with new RV32 ABI tests, snapshots, and docs.

  • New Features

    • RISC‑V dynamic linking: .rela.plt; PLT0=32B, stubs=16B; RESERVED_GOT_NUM (RV32=2, ARM=3); DYN_LINKER /lib/ld-linux-riscv32-ilp32d.so.1; ELF_FLAGS 0x4; correct DT_RELA*/DT_REL*, DT_PLTREL, DT_PLTRELSZ, DT_JMPREL.
    • Architecture switch: ELF_MACHINE_* macros gate .rel.plt vs .rela.plt.
    • RISC‑V backend/ABI: internal calls direct, extern via PLT; 16‑byte stack alignment; JAL ±1 MB range check; entry via __libc_start_main; removed got_offset.
    • Build/CI: shared toolchain detection in mk/common.mk; Actions download toolchains only for dynamic jobs; matrix runs static+dynamic for arm and riscv.
    • Tests/Docs: RV32 ABI suite (tests/riscv-abi.sh), dynamic snapshots (hello, fib), expanded dynamic linking docs with RISC‑V PLT/ABI details.
  • Bug Fixes

    • ABI scripts now validate exit code and output; fixed expected output for multi‑arg printf to avoid false positives.

Written for commit 6f43590. Summary will update on new commits.

Review in cubic

@DrXiao

DrXiao commented Apr 23, 2026

Copy link
Copy Markdown
Collaborator Author

As the apt package manager only provides a 64-bit RISC-V GNU cross-compilation toolchain, I utilize riscv-gnu-toolchain , which is a 32-bit variant, and leverage its artifacts for RISC-V dynamic linking development and validation.

The updated GitHub Actions also downloads the 32-bit variant to validate RISC-V dynamic linking.

@jserv

jserv commented Apr 23, 2026

Copy link
Copy Markdown
Collaborator

As the apt package manager only provides a 64-bit RISC-V GNU cross-compilation toolchain, I utilize riscv-gnu-toolchain , which is a 32-bit variant, and leverage its artifacts for RISC-V dynamic linking development and validation.
The updated GitHub Actions also downloads the 32-bit variant to validate RISC-V dynamic linking.

Evaluate Run 32-bit applications on 64-bit Linux kernel, which is exactly RV32-on-RV64 userspace compatibility, not emulation.

@DrXiao

DrXiao commented Apr 24, 2026

Copy link
Copy Markdown
Collaborator Author

Evaluate Run 32-bit applications on 64-bit Linux kernel, which is exactly RV32-on-RV64 userspace compatibility, not emulation.

I'm not sure whether I understand correctly. Do you mean that the proposed changes should be verified on a RISC-V machine?

@jserv

jserv commented Apr 24, 2026

Copy link
Copy Markdown
Collaborator

Do you mean that the proposed changes should be verified on a RISC-V machine?

See sysprog21/kbox#18
The RISE RISC-V Runners is a managed GitHub Actions runner service that executes CI/CD workflows on real RISC-V hardware.

@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from 446b538 to 44f2f47 Compare May 9, 2026 03:52
@DrXiao

DrXiao commented May 9, 2026

Copy link
Copy Markdown
Collaborator Author

RISE RISC-V Runners' documentation explicitly states that binaries must be compiled for riscv64. According to the FAQ - What architectures are supported?.

RISC-V 64-bit (riscv64) only. All runners execute on physical RISC-V hardware. There is no RISC-V emulation. Binaries must be compiled for riscv64.

I created another branch (feat/dynlink-for-rv32-test-rv64-runner) to verify if these RISC-V runners could support riscv32 binaries. However, the test result indicates that the runner failed to execute statically linked shecc.

Based on both the documentation and my test, it appears that RISE RISC-V runners lack support for 32-bit executables.

@DrXiao

DrXiao commented May 28, 2026

Copy link
Copy Markdown
Collaborator Author

RISC-V calling convention:

  1. First eight arguments are passed to a0-a7, and the extra arguments are pushed onto the stack.
  2. stack should be 128-bit (16-byte) aligned. In RISC-V ABIs Specification document, the section 2-1 describes

    2-1. Integer Calling Convention

    The stack grows downwards (towards lower addresses) and the stack pointer shall be aligned to a
    128-bit boundary upon procedure entry.

  3. Caller/Callee saved registers:
    Register ABI Name Saver
    zero, gp, tp (None)
    ra Caller
    sp Callee
    a0 - a7 Caller
    s0 - s11 Callee
    t0 - t6 Caller

Item 1: is done by the register allocation phase.

The register allocator uses virtual registers (vreg0-vreg7) to allocate reigsters for arguments when encountering a function call. vreg0-vreg7 will be mapped to a0-a7, so first eight arguments are naturally passed to these registers.

Since the current shecc only supports up to 8 arguments, no extra arguments need to be passed to the stack. Thus, we can skip this handling.

Item 2: is ensured by the RISC-V code generator.

When handling the stack pointer, the code generator will guarantee that sp is always incremented or decremented by a multiple of 16 bytes.

Item 3:

  • ra and sp: are properly handled by the code generator.
  • a0 - a7: are implicitly handled in register allocation phase.
  • s0 - s11: are not necessary to be preserved or restored.
  • t0 - t6: are not necessary to be handled.

Therefore, this item can also be considered complete. Further details and explanations can be found in riscv-codegen.c.

@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from 2599d74 to ee9db4a Compare June 1, 2026 13:44
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch 2 times, most recently from de67942 to 1af9140 Compare June 11, 2026 15:13
@DrXiao
DrXiao requested review from ChAoSUnItY and jserv June 13, 2026 15:37
@DrXiao

DrXiao commented Jun 13, 2026

Copy link
Copy Markdown
Collaborator Author

Since there may be additional requirements to address, I am still keeping this pull request as a draft currently, and will continue to make improvements if necessary.

@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from 5f8b272 to 9be9f62 Compare July 18, 2026 12:14
Comment thread .github/workflows/main.yml Outdated
Introduce ELF_MACHINE_ARM32 (0x28) and ELF_MACHINE_RV32 (0xf3) to
support architecture-specific logic in future developments.
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from 9be9f62 to 14220c1 Compare July 22, 2026 15:38
@DrXiao
DrXiao marked this pull request as ready for review July 28, 2026 13:48
cubic-dev-ai[bot]

This comment was marked as resolved.

@DrXiao

DrXiao commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

About LD_PRELOAD

The LD_PRELOAD mechanism allows specified libraries to be loaded before any other shared libraries (e.g.: libc.so) required by the running process, and the process can call a "wrapper" function.

This raises an interesting question: whether the dynamically linked executables generated by shecc can utilize LD_PRELOAD to perform "function interposition'.

Therefore, I prepared the following code and conducted an experiment, and it is pleasing that the generated executables can indeed leverage LD_PRELOAD and execute successfully.

Test library

The 'wrapped' malloc() can allocate memory and print the allocated size to standard output.

#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
void *malloc(size_t size) {
    char buf[32];
    static void *(*real_malloc)(size_t) = NULL;
    if (real_malloc == NULL) {
        real_malloc = dlsym(RTLD_NEXT, "malloc");
    }
    sprintf(buf, "malloc called, size = %zu\n", size);
    write(2, buf, strlen(buf));
    return real_malloc(size);
}

Use arm-linux-gnueabihf-gcc to build libmcount.so for later use.

$ arm-linux-gnueabihf-gcc -D_GNU_SOURCE -shared -ldl -fPIC -o libmcount.so malloc_count.c

Test program

/* test.c */
int main()
{
    int *a[3];

    a[0] = malloc(sizeof(int));
    a[1] = malloc(sizeof(int) * 7);
    a[2] = malloc(sizeof(int) * 1024);

    free(a[0]);
    free(a[1]);
    free(a[2]);

    return 0;
}

Use shecc to compile a dynamically linked executable, and then run it in QEMU with LD_PRELOAD=./libmcount.so.

$ make DYNLINK=1
$ qemu-arm -L /usr/arm-linux-gnueabihf/ out/shecc-stage2.elf --dynlink -o test test.c
$ qemu-arm -L /usr/arm-linux-gnueabihf/ -E LD_PRELOAD=./libmcount.so ./test
malloc called, size = 4
malloc called, size = 28
malloc called, size = 4096

We can observe that test.c calls the wrapped malloc() three times. Each call successfully allocates memory and correctly prints the allocated size.


Function interposition is also supported on the RISC-V architecture:

$ riscv32-unknown-linux-gnu-gcc -D_GNU_SOURCE -shared -ldl -fPIC -o libmcount.so malloc_count.c
$ make DYNLINK=1 ARCH=riscv
$ qemu-riscv32 -L $(riscv32-unknown-linux-gnu-gcc --print-sysroot) out/shecc-stage2.elf --dynlink -o test test.c
$ qemu-riscv32 -L $(riscv32-unknown-linux-gnu-gcc --print-sysroot) -E LD_PRELOAD=./libmcount.so ./test
malloc called, size = 4
malloc called, size = 28
malloc called, size = 4096

I will conduct this experiment on real hardware (e.g.: BeagleBone Black) later.

@DrXiao
DrXiao requested a review from jserv July 28, 2026 15:31
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from 14220c1 to 4a556ea Compare July 29, 2026 15:38

@jserv jserv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review notes on the RV32 dynamic linking implementation. Findings are inlined at their locations.

Comment thread src/riscv-codegen.c Outdated
Comment thread src/riscv-codegen.c
Comment thread mk/riscv.mk
Comment thread src/riscv-codegen.c Outdated
Comment thread src/elf.c Outdated
Comment thread src/elf.c
Comment thread tests/riscv-abi.sh Outdated
exit_code=$?

# Check result
if [[ $exit_code -eq 0 ]]; then

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A test is counted as passed on exit_code == 0 alone; an expected_output mismatch is only a warning, and only under VERBOSE. A broken external-call path that still exits 0 passes silently, which is exactly the failure mode this suite is meant to catch. Treat a non-matching expected_output as a failure.

Comment thread .github/workflows/main.yml Outdated
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch 2 times, most recently from b90b394 to 7e72003 Compare July 30, 2026 15:51
Comment thread docs/dynamic-linking.md Outdated
DrXiao added 4 commits July 30, 2026 23:57
This commit primarily improves the ELF handling and code generator to
enable the compiler to produce a dynamically linked executable targeting
the RISC-V architecture.

- Update the selected dynamic linker path and the ABI flag.
- Allow the ELF handling to generate RELA relocation table.
  - Use REL relocation when the target architecture is Arm. Othereise,
    use RELA relocation for RISC-V.
- Improve GOT generation process.
  - Arm: reserve three entries.
  - RISC-V: reserve two entries.
- Implement PLT generation for RISC-V.
  - The generation process follows the RISC-V ABI. The first PLT entry
    uses 8 instructions to call '_dl_runtime_resolve'. The subsequent
    entry uses 4 instructions to perform an indirect function call via
    GOT.
- Refine the function call handling for the RISC-V code generator.
  - Perform a direct call for internal functions
  - Otherwise, use PLT table to peform an indirect call for external
    functions.
- Enhance the build system:
  - Allow the build system to generate dynamically linked compilers when
    targeting the RISC-V architecture.
  - Detect the sysroot path of the RISC-V GNU toolchain automatically.
- Remove the unnecessary 'got_offset' field from 'struct func'.
Modify the 'update-snapshots' and 'check-snapshots' make targets to
include generation and validation of new snapshots for the RISC-V
architecture using dynamic linking.
The update workflow now downloads a RISC-V GNU toolchain to provide
necessary dependencies and validate the dynamically linked compiler
targeting the RISC-V architecture.

This update also improves the download step so that it retrieves the
ARM/RISC-V GNU toolchain only when verifying the dynamic linking mode.
Because two architecture-specific makefile fragments contain similar
snippets for locating the cross-compilation toolchain path, this commit
consolidates them into a shared build logic, thereby reducing code
duplication.
A new shell script is introduced to validate whether generated
executables targeting RISC-V correct comply with the RISC-V ABI.

The tests include:
- Parameter Passing: tests function calls with different numbers of
  arguments.
- Stack Alignment: validates whether the stack is always 16-byte
  aligned when calling a function.
- Return Values: confirms if the return value is correct after a
  function returns.
- External Calls: verifies whether dynamically linked programs can call
  external functions.
- Register Preservation: verify whether the contents of function
  argument registers are properly preserved when calling a function.
- Structure Passing: validates if a small structure object can be passed
  correctly.
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch 2 times, most recently from ea51c76 to f545b7a Compare July 31, 2026 12:06
DrXiao added 3 commits July 31, 2026 21:18
- Expand instructions on utilizing dynamic linking for both the Arm and
  RISC-V architectures.
- Describe the stack frame layout for the RISC-V implementation.
- Explain caller and callee behaviors when targeting the RISC-V
  architecture.
- Illustrate the RISC-V PLT stub implementation, including assembly code
  snippets and design intentions.
- Add reference links about RISC-V.
  - glibc implementation of '__dl_runtime_resolve' for RISC-V.
  - RISC-V ABIs specifications.
- Improve the explanation of the runtime execution flow of a dynamically
  linked program.
- Correct the description of callee behavior for the Arm architecture.
  - Clarify that registers r4-r11 are callee-saved, not caller-saved.
  - Explain that the saved lr is loaded into pc to return to the caller.
Since the dynamic linking is now supported for the RISC-V architecture,
this updates the relevant introductions and usage guides.
Since the jump offset of a 'jal' instruction is restricted to between
-1MB and +1MB, this commit adds a validation check to ensure the
compiler reports an error if the jump offset is out of range.
@DrXiao

DrXiao commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

About LD_PRELOAD

The LD_PRELOAD mechanism allows specified libraries to be loaded before any other shared libraries (e.g.: libc.so) required by the running process, and the process can call a "wrapper" function.
...
I will conduct this experiment on real hardware (e.g.: BeagleBone Black) later.

I have used my BeagleBone Black to conduct the same test, and the LD_PRELOAD mechanism still works on real hardware.

Demonstration:

bbb-shecc-test-ldpreload.mp4

DrXiao added 2 commits July 31, 2026 23:41
Previously, the scripts only validated the standard output of each case
when verbose mode was enabled. This may lead to false positives if the
exit code is zero but the output is incorrect.

This commit improves all ABI validation scripts to resolve this issue.
The updated validation flow now sets a status flag based on both the
exit code and the output, using it to accurately determine whether the
test case passes or fails.
Previously, the test_printf_multi_args() test case called printf() twice
to output "Values: 1 2 3 4" and "PASS", respectively. However, the test
suites only checked whether the entire standard output contained the
"PASS" string. This approach failed to verify if the first call printed
the correct string.

Thus, this commit updates the test case across all ABI validation
scripts. It preserves only the first printf() call and sets the expected
output to "Values: 1 2 3 4", ensuring the scripts can correctly validate
function calls with multiple arguments.
@DrXiao
DrXiao force-pushed the feat/dynlink-for-rv32 branch from f545b7a to 6f43590 Compare July 31, 2026 16:22
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