Commit 408c1512 authored by Yong Cong Sin's avatar Yong Cong Sin Committed by Dan Kalowsky
Browse files

tests: arch: riscv: make sure that `gp` reg can't be corrupted

Add a test to make sure that the `gp` global pointer register used for
relative addressing when `CONFIG_RISCV_GP` is enabled can't be
corrupted by a rogue user thread.

Signed-off-by: default avatarYong Cong Sin <ycsin@meta.com>
Signed-off-by: default avatarYong Cong Sin <yongcong.sin@gmail.com>
parent e30db2d5
Loading
Loading
Loading
Loading
+8 −0
Changes for tests/arch/riscv/userspace/riscv_gp/CMakeLists.txt: 8 added lines, 0 removed lines.
Original line number Diff line number Diff line
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(riscv_gp)

FILE(GLOB app_sources src/*.c)
target_sources(app PRIVATE ${app_sources})
+3 −0
Changes for tests/arch/riscv/userspace/riscv_gp/prj.conf: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
CONFIG_ZTEST=y
CONFIG_RISCV_GP=y
CONFIG_TEST_USERSPACE=y
+47 −0
Changes for tests/arch/riscv/userspace/riscv_gp/src/main.c: 47 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*
 * Copyright (c) 2024 Meta Platforms
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <stdio.h>

#include <zephyr/arch/riscv/reg.h>
#include <zephyr/kernel.h>
#include <zephyr/ztest.h>

#define ROGUE_USER_STACK_SZ 2048

static struct k_thread rogue_user_thread;
static K_THREAD_STACK_DEFINE(rogue_user_stack, ROGUE_USER_STACK_SZ);

static void rogue_user_fn(void *p1, void *p2, void *p3)
{
	zassert_true(k_is_user_context());

	reg_write(gp, 0xbad);
	zassert_equal(reg_read(gp), 0xbad);
}

ZTEST_USER(riscv_gp, test_gp_value)
{
	uintptr_t gp_val = reg_read(gp);
	k_tid_t th;

	zassert_not_equal(gp_val, 0);

	th = k_thread_create(&rogue_user_thread, rogue_user_stack, ROGUE_USER_STACK_SZ,
			     rogue_user_fn, NULL, NULL, NULL, -1, K_USER, K_NO_WAIT);
	zassert_ok(k_thread_join(th, K_FOREVER));

	zassert_equal(reg_read(gp), gp_val, "`gp` corrupted by user thread");
}

static void *userspace_setup(void)
{
	k_thread_access_grant(k_current_get(), &rogue_user_thread, &rogue_user_stack);

	return NULL;
}

ZTEST_SUITE(riscv_gp, NULL, userspace_setup, NULL, NULL, NULL);
+8 −0
Changes for tests/arch/riscv/userspace/riscv_gp/testcase.yaml: 8 added lines, 0 removed lines.
Original line number Diff line number Diff line
common:
  ignore_faults: true
  ignore_qemu_crash: true
  tags: kernel riscv
  platform_allow:
    - qemu_riscv64
tests:
  arch.riscv64.riscv_gp: {}