Compare commits

...

9 commits

Author SHA1 Message Date
86ba43a25b
fix: see NJU-ProjectN/nemu#85 2024-03-03 20:58:29 +08:00
12f5ba0897
NJU-ProjectN/am-kernels ics2021 initialized without tracing
NJU-ProjectN/am-kernels bb725d6f8223dd7de831c3b692e8c4531e9d01af kernels,demo,donut: only clear screen before drawing
2024-03-03 11:26:08 +08:00
504d270947 pa1.3: watchpoint support 2024-02-08 20:07:03 +08:00
2675a647b0
fix: change x paddr to vaddr 2024-02-05 22:53:39 +08:00
4aa536e1ef
pa1.2: fix include and word type 2024-01-13 11:42:35 +08:00
ebece52aec
pa1.2: remove unused expr parsing code 2024-01-13 10:39:51 +08:00
e19e89f70e
pa1.2: add unit tests 2024-01-13 10:38:20 +08:00
9cca9de2a8
pa1.2: use flex and bason to implement expr parser 2024-01-12 22:16:35 +08:00
69264e69c6
pa1.1: add handler for x, info, si 2024-01-11 23:00:49 +08:00
22 changed files with 1101 additions and 207 deletions

1
.gitignore vendored
View file

@ -10,3 +10,4 @@
!init.sh
/fceux-am
/nvboard
/am-kernels

3
nemu/.clang-format Normal file
View file

@ -0,0 +1,3 @@
---
Language: Cpp
BasedOnStyle: LLVM

74
nemu/.gitignore vendored
View file

@ -1,12 +1,66 @@
*.*
*
!*/
!Makefile
!*.mk
!*.[cSh]
!*.cc
!.gitignore
!README.md
!Kconfig
include/config
include/generated
configs/defconfig
build/
.cache/
.direnv/
.config
.config.old
.envrc
.metals/
.vscode/
compile_commands.json
### C ###
# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf

127
nemu/LICENSE Normal file
View file

@ -0,0 +1,127 @@
木兰宽松许可证, 第2版
木兰宽松许可证, 第2版
2020年1月 http://license.coscl.org.cn/MulanPSL2
您对“软件”的复制、使用、修改及分发受木兰宽松许可证第2版“本许可证”的如下条款的约束
0. 定义
“软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
“贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
“贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
“法人实体”是指提交贡献的机构及其“关联实体”。
“关联实体”是指对“本许可证”下的行为方而言控制、受控制或与其共同受控制的机构此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
1. 授予版权许可
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
2. 授予专利许可
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
3. 无商标许可
“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可但您为满足第4条规定的声明义务而必须使用除外。
4. 分发限制
您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
5. 免责声明与责任限制
“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
6. 语言
“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。
条款结束
如何将木兰宽松许可证第2版应用到您的软件
如果您希望将木兰宽松许可证第2版应用到您的新软件为了方便接收者查阅建议您完成如下三步
1 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
2 请您在软件包的一级目录下创建以“LICENSE”为名的文件将整个许可证文本放入该文件中
3 请将如下声明文本放入每个源文件的头部注释中。
Copyright (c) 2014-2022 Zihao Yu, Nanjing University
NEMU is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
Mulan Permissive Software LicenseVersion 2
Mulan Permissive Software LicenseVersion 2 (Mulan PSL v2)
January 2020 http://license.coscl.org.cn/MulanPSL2
Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions:
0. Definition
Software means the program and related documents which are licensed under this License and comprise all Contribution(s).
Contribution means the copyrightable work licensed by a particular Contributor under this License.
Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
Legal Entity means the entity making a Contribution and all its Affiliates.
Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, control means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
1. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
2. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
3. No Trademark License
No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4.
4. Distribution Restriction
You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
5. Disclaimer of Warranty and Limitation of Liability
THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW ITS CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
6. Language
THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL.
END OF THE TERMS AND CONDITIONS
How to Apply the Mulan Permissive Software LicenseVersion 2 (Mulan PSL v2) to Your Software
To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps:
i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package;
iii Attach the statement to the appropriate annotated syntax at the beginning of each source file.
Copyright (c) 2014-2022 Zihao Yu, Nanjing University
NEMU is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.

View file

@ -40,7 +40,9 @@ SRCS-y += $(shell find -L $(DIRS-y) -name "*.c")
SRCS = $(filter-out $(SRCS-BLACKLIST-y),$(SRCS-y))
# Extract compiler and options from menuconfig
ifneq ($(CONFIG_CC),)
CC = $(call remove_quote,$(CONFIG_CC))
endif
CFLAGS_BUILD += $(call remove_quote,$(CONFIG_CC_OPT))
CFLAGS_BUILD += $(if $(CONFIG_CC_LTO),-flto,)
CFLAGS_BUILD += $(if $(CONFIG_CC_DEBUG),-Og -ggdb3,)
@ -48,6 +50,7 @@ CFLAGS_BUILD += $(if $(CONFIG_CC_ASAN),-fsanitize=address,)
CFLAGS_TRACE += -DITRACE_COND=$(if $(CONFIG_ITRACE_COND),$(call remove_quote,$(CONFIG_ITRACE_COND)),true)
CFLAGS += $(CFLAGS_BUILD) $(CFLAGS_TRACE) -D__GUEST_ISA__=$(GUEST_ISA)
LDFLAGS += $(CFLAGS_BUILD)
INC_PATH += $(NEMU_HOME)/src/isa/$(GUEST_ISA)/local-include
# Include rules for menuconfig
include $(NEMU_HOME)/scripts/config.mk
@ -59,3 +62,14 @@ else
# Include rules to build NEMU
include $(NEMU_HOME)/scripts/native.mk
endif
include $(NEMU_HOME)/tests/Makefile
all-tests: TEST_OBJS = $(filter-out $(OBJ_DIR)/src/nemu-main.o, $(OBJS))
all-tests: CFLAGS += $(shell pkg-config --cflags check)
all-tests: LDFLAGS += $(shell pkg-config --libs check)
all-tests: $(TEST_SRCS:%.c=$(OBJ_DIR)/%)
test: all-tests
@$(OBJ_DIR)/tests/expr_test
.PHONY: test

View file

@ -0,0 +1,74 @@
#
# Automatically generated file; DO NOT EDIT.
# NEMU Configuration Menu
#
# CONFIG_ISA_x86 is not set
# CONFIG_ISA_mips32 is not set
CONFIG_ISA_riscv=y
# CONFIG_ISA_loongarch32r is not set
CONFIG_ISA="riscv32"
#
# ISA-dependent Options for riscv
#
# CONFIG_RV64 is not set
# CONFIG_RVE is not set
# end of ISA-dependent Options for riscv
CONFIG_ENGINE_INTERPRETER=y
CONFIG_ENGINE="interpreter"
CONFIG_MODE_SYSTEM=y
CONFIG_TARGET_NATIVE_ELF=y
# CONFIG_TARGET_SHARE is not set
# CONFIG_TARGET_AM is not set
#
# Build Options
#
CONFIG_CC_GCC=y
# CONFIG_CC_GPP is not set
# CONFIG_CC_CLANG is not set
CONFIG_CC="gcc"
# CONFIG_CC_O0 is not set
# CONFIG_CC_O1 is not set
CONFIG_CC_O2=y
# CONFIG_CC_O3 is not set
CONFIG_CC_OPT="-O2"
# CONFIG_CC_LTO is not set
# CONFIG_CC_DEBUG is not set
CONFIG_CC_ASAN=y
# end of Build Options
#
# Testing and Debugging
#
CONFIG_TRACE=y
CONFIG_TRACE_START=0
CONFIG_TRACE_END=10000
CONFIG_ITRACE=y
CONFIG_ITRACE_COND="true"
# CONFIG_DIFFTEST is not set
CONFIG_DIFFTEST_REF_PATH="none"
CONFIG_DIFFTEST_REF_NAME="none"
# end of Testing and Debugging
#
# Memory Configuration
#
CONFIG_MBASE=0x80000000
CONFIG_MSIZE=0x8000000
CONFIG_PC_RESET_OFFSET=0
# CONFIG_PMEM_MALLOC is not set
CONFIG_PMEM_GARRAY=y
CONFIG_MEM_RANDOM=y
# end of Memory Configuration
# CONFIG_DEVICE is not set
#
# Miscellaneous
#
CONFIG_TIMER_GETTIMEOFDAY=y
# CONFIG_TIMER_CLOCK_GETTIME is not set
CONFIG_RT_CHECK=y
# end of Miscellaneous

View file

@ -40,13 +40,31 @@
gnumake
flex
bison
pkg-config
python3 # for testing
];
buildInputs = [
check
readline
libllvm
];
configurePhase = ''
echo NEMU_HOME=$NEMU_HOME
echo pwd=$(pwd)
mkdir -p $(pwd)/kconfig
WORK_DIR=$(pwd) obj=$(pwd)/kconfig make --trace -e -f scripts/config.mk WORK_DIR=$(pwd) obj=$(pwd)/kconfig rv32_defconfig
'';
installPhase = ''
BUILD_DIR=$out make install
'';
checkPhase = ''
BUILD_DIR=$out make test
'';
NEMU_HOME = src;
meta = with lib; {

View file

@ -37,6 +37,10 @@
typedef MUXDEF(CONFIG_ISA64, uint64_t, uint32_t) word_t;
typedef MUXDEF(CONFIG_ISA64, int64_t, int32_t) sword_t;
static const word_t WORD_T_MAX = MUXDEF(CONFIG_ISA64, UINT64_MAX, UINT32_MAX);
static const sword_t SWORD_T_MAX = MUXDEF(CONFIG_ISA64, INT64_MAX, INT32_MAX);
static const sword_t SWORD_T_MIN = MUXDEF(CONFIG_ISA64, INT64_MIN, INT32_MIN);
#define WORD_BYTES MUXDEF(CONFIG_ISA64, 8, 4)
#define FMT_WORD MUXDEF(CONFIG_ISA64, "0x%016" PRIx64, "0x%08" PRIx32)
typedef word_t vaddr_t;

View file

@ -21,7 +21,15 @@
#include <utils.h>
#define Log(format, ...) \
_Log(ANSI_FMT("[%s:%d %s] " format, ANSI_FG_BLUE) "\n", \
_Log(ANSI_FMT("[INFO] %s:%d %s() ", ANSI_FG_BLUE) format "\n", \
__FILE__, __LINE__, __func__, ## __VA_ARGS__)
#define Warning(format, ...) \
_Log(ANSI_FMT("[WARNING] %s:%d %s() ", ANSI_FG_YELLOW) format "\n", \
__FILE__, __LINE__, __func__, ## __VA_ARGS__)
#define Error(format, ...) \
_Log(ANSI_FMT("[ERROR] %s:%d %s() ", ANSI_FG_RED) format "\n", \
__FILE__, __LINE__, __func__, ## __VA_ARGS__)
#define Assert(cond, format, ...) \

View file

@ -10,7 +10,7 @@ endif
WORK_DIR = $(shell pwd)
BUILD_DIR = $(WORK_DIR)/build
INC_PATH := $(WORK_DIR)/include $(INC_PATH)
INC_PATH := $(WORK_DIR)/include $(BUILD_DIR)/include $(INC_PATH)
OBJ_DIR = $(BUILD_DIR)/obj-$(NAME)$(SO)
BINARY = $(BUILD_DIR)/$(NAME)$(SO)
@ -40,12 +40,34 @@ $(OBJ_DIR)/%.o: %.cc
@$(CXX) $(CFLAGS) $(CXXFLAGS) -c -o $@ $<
$(call call_fixdep, $(@:.o=.d), $@)
$(OBJ_DIR)/%.tag.c: %.y
@echo + YACC $<
@mkdir -p $(dir $@) $(BUILD_DIR)/include
@$(YACC) $(YFLAGS) --header=$(BUILD_DIR)/include/$(notdir $(<:.y=.h)) -o $@ $<
$(OBJ_DIR)/%.yy.c: %.l $(OBJ_DIR)/%.tag.c
@echo + LEX $<
@mkdir -p $(dir $@) $(BUILD_DIR)/include
@$(LEX) $(LFLAGS) --header=$(BUILD_DIR)/include/$(notdir $(<:.l=_lex.h)) -o $@ $<
$(OBJ_DIR)/%.tag.o: $(OBJ_DIR)/%.tag.c
@echo + CC $<
@mkdir -p $(dir $@)
@$(CC) $(CFLAGS) -c -o $@ $<
$(call call_fixdep, $(@:.o=.d), $@)
$(OBJ_DIR)/%.yy.o: $(OBJ_DIR)/%.yy.c
@echo + CC $<
@mkdir -p $(dir $@)
@$(CC) $(CFLAGS) -c -o $@ $<
$(call call_fixdep, $(@:.o=.d), $@)
# Depencies
-include $(OBJS:.o=.d)
# Some convenient rules
.PHONY: app clean
.PHONY: app install clean
app: $(BINARY)
@ -53,5 +75,9 @@ $(BINARY):: $(OBJS) $(ARCHIVES)
@echo + LD $@
@$(LD) -o $@ $(OBJS) $(LDFLAGS) $(ARCHIVES) $(LIBS)
install: $(BINARY)
@mkdir -p $(PREFIX)/bin
@cp $(BINARY) $(PREFIX)/bin/
clean:
-rm -rf $(BUILD_DIR)

View file

@ -31,6 +31,7 @@ static uint64_t g_timer = 0; // unit: us
static bool g_print_step = false;
void device_update();
bool wp_eval_all();
static void trace_and_difftest(Decode *_this, vaddr_t dnpc) {
#ifdef CONFIG_ITRACE_COND
@ -77,6 +78,10 @@ static void execute(uint64_t n) {
exec_once(&s, cpu.pc);
g_nr_guest_inst ++;
trace_and_difftest(&s, cpu.pc);
if (wp_eval_all()) {
puts(s.logbuf);
break;
}
if (nemu_state.state != NEMU_RUNNING) break;
IFDEF(CONFIG_DEVICE, device_update());
}

View file

@ -15,6 +15,7 @@
#include <isa.h>
#include "local-include/reg.h"
#include "macro.h"
const char *regs[] = {
"$0", "ra", "sp", "gp", "tp", "t0", "t1", "t2",
@ -24,8 +25,27 @@ const char *regs[] = {
};
void isa_reg_display() {
int colomn_per_row = 4;
for(int i = 0; i < ARRLEN(regs); i++) {
printf("\e[1;34m%3s\e[0m: " FMT_PADDR, reg_name(i), gpr(i));
if (i % colomn_per_row == 3)
putchar('\n');
else
putchar('|');
}
}
word_t isa_reg_str2val(const char *s, bool *success) {
assert(s);
int i;
for (i = 0; i < 32 && strcmp(s, regs[i]) != 0; i++)
;
if (i == 32) {
*success = false;
return 0;
}
*success = true;
return gpr(i);
}

1
nemu/src/isa/riscv64 Symbolic link
View file

@ -0,0 +1 @@
riscv32

View file

@ -0,0 +1,24 @@
%{
#include <isa.h>
#include <addrexp.h>
static bool success = false;
void yyerror(word_t *result, const char *err);
%}
%option noyywrap
%%
0[xX][0-9a-fA-F]+ { yylval = strtoul(yytext, NULL, 16); return HEX_NUMBER; }
[0-9]+ { yylval = strtoul(yytext, NULL, 10); return NUMBER; }
$[asgprt$][0-9pa][0-9]? {
yylval = isa_reg_str2val(yytext + 1, &success);
if(!success) {
yyerror(NULL, "Failed to convert reg to value");
return YYerror;
}
return REGISTER;
}
[+\-*/<=()] { return *yytext; }
[ \t] { }
. { printf("Unexpected character: %s\n", yytext); return YYerror; }
%%

View file

@ -0,0 +1,59 @@
%code requires {
#include <common.h>
#include <memory/vaddr.h>
#include <stdio.h>
#include <stdlib.h>
extern int yylex(void);
}
%{
#include <common.h>
#include <isa.h>
#include <stdio.h>
#include <stdlib.h>
void yyerror(word_t *result, const char *err) {
Error("%s", err);
}
%}
%token NUMBER HEX_NUMBER
%token REGISTER
%locations
%start input
%define api.value.type { word_t }
%parse-param { uint32_t *result }
%left '-' '+'
%left '*' '/'
%%
input
: expression { *result = $1; }
;
expression
: number { $$ = $1; }
| expression '>' '=' expression { $$ = ($1 >= $4); }
| expression '<' '=' expression { $$ = ($1 <= $4); }
| expression '=' '=' expression { $$ = ($1 == $4); }
| expression '!' '=' expression { $$ = ($1 == $4); }
| expression '>' expression { $$ = ($1 > $3); }
| expression '<' expression { $$ = ($1 < $3); }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression { $$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression {
if($3 == 0) {
fprintf(stderr, "Error: divide by zero at %u / %u\n", $1, $3);
YYABORT;
};
$$ = $1 / $3;
}
| '-' number { $$ = -$2; }
| '*' expression { $$ = vaddr_read($2, WORD_BYTES); }
| '(' expression ')' { $$ = $2; }
number
: REGISTER
| NUMBER
| HEX_NUMBER
%%

View file

@ -1,125 +0,0 @@
/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/
#include <isa.h>
/* We use the POSIX regex functions to process regular expressions.
* Type 'man regex' for more information about POSIX regex functions.
*/
#include <regex.h>
enum {
TK_NOTYPE = 256, TK_EQ,
/* TODO: Add more token types */
};
static struct rule {
const char *regex;
int token_type;
} rules[] = {
/* TODO: Add more rules.
* Pay attention to the precedence level of different rules.
*/
{" +", TK_NOTYPE}, // spaces
{"\\+", '+'}, // plus
{"==", TK_EQ}, // equal
};
#define NR_REGEX ARRLEN(rules)
static regex_t re[NR_REGEX] = {};
/* Rules are used for many times.
* Therefore we compile them only once before any usage.
*/
void init_regex() {
int i;
char error_msg[128];
int ret;
for (i = 0; i < NR_REGEX; i ++) {
ret = regcomp(&re[i], rules[i].regex, REG_EXTENDED);
if (ret != 0) {
regerror(ret, &re[i], error_msg, 128);
panic("regex compilation failed: %s\n%s", error_msg, rules[i].regex);
}
}
}
typedef struct token {
int type;
char str[32];
} Token;
static Token tokens[32] __attribute__((used)) = {};
static int nr_token __attribute__((used)) = 0;
static bool make_token(char *e) {
int position = 0;
int i;
regmatch_t pmatch;
nr_token = 0;
while (e[position] != '\0') {
/* Try all rules one by one. */
for (i = 0; i < NR_REGEX; i ++) {
if (regexec(&re[i], e + position, 1, &pmatch, 0) == 0 && pmatch.rm_so == 0) {
char *substr_start = e + position;
int substr_len = pmatch.rm_eo;
Log("match rules[%d] = \"%s\" at position %d with len %d: %.*s",
i, rules[i].regex, position, substr_len, substr_len, substr_start);
position += substr_len;
/* TODO: Now a new token is recognized with rules[i]. Add codes
* to record the token in the array `tokens'. For certain types
* of tokens, some extra actions should be performed.
*/
switch (rules[i].token_type) {
default: TODO();
}
break;
}
}
if (i == NR_REGEX) {
printf("no match at position %d\n%s\n%*.s^\n", position, e, position, "");
return false;
}
}
return true;
}
word_t expr(char *e, bool *success) {
if (!make_token(e)) {
*success = false;
return 0;
}
/* TODO: Insert codes to evaluate the expression. */
TODO();
return 0;
}

View file

@ -0,0 +1,2 @@
SRCS-y += src/monitor/sdb/addrexp.tag.c src/monitor/sdb/addrexp.yy.c
LFLAGS += -DYY_NO_UNPUT -DYY_NO_INPUT

View file

@ -1,31 +1,77 @@
/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan
*PSL v2. You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
*KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
*NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/
#include <isa.h>
#include <cpu/cpu.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "sdb.h"
#include "common.h"
#include "sys/types.h"
#include <addrexp.h>
#include <addrexp_lex.h>
#include <cpu/cpu.h>
#include <errno.h>
#include <isa.h>
#include <memory/vaddr.h>
#include <readline/history.h>
#include <readline/readline.h>
#include <stdint.h>
static int is_batch_mode = false;
// command handlers
static int cmd_help(char *args);
static int cmd_c(char *args);
static int cmd_p(char *args);
static int cmd_q(char *args);
static int cmd_w(char *args);
static int cmd_x(char *args);
static int cmd_si(char *args);
static int cmd_info(char *args);
static int cmd_info_r(char *args);
static int cmd_info_w(char *args);
static struct CommandTable {
const char *name;
const char *description;
int (*handler)(char *);
struct CommandTable *subcommand;
int nr_subcommand;
} cmd_info_table[] =
{
{"r", "List all registers and their contents", cmd_info_r, NULL, 0},
{"w", "Status of specified watchpoints", cmd_info_w, NULL, 0},
},
cmd_table[] = {
{"help", "Display information about all supported commands", cmd_help,
NULL, 0},
{"c", "Continue the execution of the program", cmd_c, NULL, 0},
{"p", "Print expression result", cmd_p, NULL, 0},
{"q", "Exit NEMU", cmd_q, NULL, 0},
{"x", "Examine content of physical memory address", cmd_x, NULL, 0},
{"w", "Break when expression is changed", cmd_w, NULL, 0},
{"si", "Execute next [n] program line", cmd_si, NULL, 0},
{"info", "Print information of registers or watchpoints", cmd_info,
cmd_info_table, ARRLEN(cmd_info_table)},
};
#define NR_CMD ARRLEN(cmd_table)
void init_regex();
void init_wp_pool();
/* We use the `readline' library to provide more flexibility to read from stdin. */
static char* rl_gets() {
/* We use the `readline' library to provide more flexibility to read from stdin.
*/
static char *rl_gets() {
static char *line_read = NULL;
if (line_read) {
@ -33,7 +79,7 @@ static char* rl_gets() {
line_read = NULL;
}
line_read = readline("(nemu) ");
line_read = readline("\e[1;34m(nemu)\e[0m ");
if (line_read && *line_read) {
add_history(line_read);
@ -42,33 +88,191 @@ static char* rl_gets() {
return line_read;
}
/* Extract Integer from a string. Can handle hex, binary and decimal numbers.
* Print error if meet any error.
* Return `UINTMAX_MAX` if the string is invalid or number exceed the limit of
* uint.
*/
static word_t parse_uint(const char *arg, bool *success) {
if (arg == NULL) {
puts("Invalid uint argument.");
*success = false;
return 0;
}
int base = 10;
int token_length = strnlen(arg, 34);
if (token_length > 2) {
if (arg[0] == '0' && (arg[1] == 'b' || arg[1] == 'B')) {
base = 2;
arg = arg + 2;
} else if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
base = 16;
arg = arg + 2;
}
}
char *endptr;
uintmax_t n = strtoumax(arg, &endptr, base);
if (errno == ERANGE || n > WORD_T_MAX) {
printf("%s exceed the limit of uint\n", arg);
*success = false;
return 0;
} else if (arg == endptr) {
puts("Invalid uint argument.");
*success = false;
return 0;
} else if (n > WORD_T_MAX) {
*success = false;
return WORD_T_MAX;
} else {
*success = true;
return n;
}
}
word_t parse_expr(const char *arg, bool *success) {
if (arg == NULL) {
puts("Invalid expr argument.");
*success = false;
return 0;
} else {
word_t res;
yy_scan_string(arg);
*success = !yyparse(&res);
yylex_destroy();
return res;
}
}
static int cmd_c(char *args) {
cpu_exec(-1);
return 0;
}
static int cmd_p(char *args) {
char *arg = strtok(NULL, "");
bool res = false;
word_t result = parse_expr(arg, &res);
if (!res)
goto wrong_usage;
printf("%s: %u\n", arg, result);
return 0;
wrong_usage:
printf("Invalid argument for command p: %s\n", arg);
printf("Usage: p [EXPR: <expr>]\n");
return 0;
}
static int cmd_q(char *args) {
nemu_state.state = NEMU_QUIT;
return -1;
}
static int cmd_help(char *args);
/* Single stepping
* <step>: execute <step> step
*/
static int cmd_si(char *args) {
char *arg = strtok(NULL, " ");
if (arg == NULL) {
cpu_exec(1);
} else {
bool res = false;
word_t n = parse_uint(arg, &res);
if (!res)
goto wrong_usage;
cpu_exec(n);
}
return 0;
static struct {
const char *name;
const char *description;
int (*handler) (char *);
} cmd_table [] = {
{ "help", "Display information about all supported commands", cmd_help },
{ "c", "Continue the execution of the program", cmd_c },
{ "q", "Exit NEMU", cmd_q },
wrong_usage:
printf("Invalid argument for command si: %s\n", args);
printf("Usage: si [N: uint]\n");
return 0;
}
/* TODO: Add more commands */
static int cmd_info_r(char *args) {
isa_reg_display();
return 0;
}
};
static int cmd_info_w(char *args) {
printf("Not implemented");
return 0;
}
#define NR_CMD ARRLEN(cmd_table)
static int cmd_w(char *args) {
char *expr = strtok(NULL, "");
wp_add(expr);
return 0;
}
static int cmd_x(char *args) {
char *arg = strtok(NULL, " ");
bool res = false;
word_t n = parse_uint(arg, &res);
if (!res)
goto wrong_usage;
// No deliminter here, just pass all the remain argument to `parse_expr()`
arg = strtok(NULL, "");
word_t start_addr = parse_expr(arg, &res);
if (!res)
goto wrong_usage;
start_addr = start_addr & ~(WORD_BYTES - 1);
for (vaddr_t vaddr = start_addr; vaddr < start_addr + n; vaddr += WORD_BYTES) {
word_t value = vaddr_read(vaddr, WORD_BYTES);
printf("\e[1;34m" FMT_PADDR "\e[0m"
" " FMT_WORD "\n",
vaddr, value);
}
return 0;
wrong_usage:
printf("Invalid argument for command x: %s\n", arg);
printf("Usage: x [N: uint] [EXPR: <expr>]\n");
return 0;
}
static int cmd_info(char *args) {
char *arg = strtok(NULL, " ");
int i;
if (arg == NULL) {
goto wrong_usage;
return 0;
}
for (i = 0; i < ARRLEN(cmd_info_table); i++) {
if (strcmp(arg, cmd_info_table[i].name) == 0) {
cmd_info_table[i].handler(args);
return 0;
}
}
wrong_usage:
printf("Invalid argument for command info: %s\n", args);
printf("Usage: info [r | w]\n");
return 0;
}
static int cmd_help_print(char *args, struct CommandTable *cur_cmd_table,
int cur_nr_cmd) {
int i;
char *arg = strtok(NULL, " ");
if (arg == NULL) {
return -1;
} else {
for (i = 0; i < cur_nr_cmd; i++) {
if (strcmp(arg, cur_cmd_table[i].name) == 0) {
printf("%s ", cur_cmd_table[i].name);
if (cmd_help_print(arg, cur_cmd_table[i].subcommand,
cur_cmd_table[i].nr_subcommand) == -1) {
printf("-- %s\n", cur_cmd_table[i].description);
}
return 0;
}
}
return -1;
}
}
static int cmd_help(char *args) {
/* extract the first argument */
@ -77,14 +281,23 @@ static int cmd_help(char *args) {
if (arg == NULL) {
/* no argument given */
for (i = 0; i < NR_CMD; i ++) {
printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
for (i = 0; i < NR_CMD; i++) {
printf("%s -- %s\n", cmd_table[i].name, cmd_table[i].description);
}
}
else {
for (i = 0; i < NR_CMD; i ++) {
} else {
for (i = 0; i < NR_CMD; i++) {
if (strcmp(arg, cmd_table[i].name) == 0) {
printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
printf("%s ", cmd_table[i].name);
if (cmd_help_print(args, cmd_table[i].subcommand,
cmd_table[i].nr_subcommand) == -1) {
printf("-- %s\n", cmd_table[i].description);
// Print available subcommands
for (int j = 0; j < cmd_table[i].nr_subcommand; j++) {
struct CommandTable *sub_cmd_table = cmd_table[i].subcommand;
printf(" > %s -- %s\n", sub_cmd_table[j].name,
sub_cmd_table[j].description);
}
}
return 0;
}
}
@ -93,9 +306,7 @@ static int cmd_help(char *args) {
return 0;
}
void sdb_set_batch_mode() {
is_batch_mode = true;
}
void sdb_set_batch_mode() { is_batch_mode = true; }
void sdb_mainloop() {
if (is_batch_mode) {
@ -103,12 +314,14 @@ void sdb_mainloop() {
return;
}
for (char *str; (str = rl_gets()) != NULL; ) {
for (char *str; (str = rl_gets()) != NULL;) {
char *str_end = str + strlen(str);
/* extract the first token as the command */
char *cmd = strtok(str, " ");
if (cmd == NULL) { continue; }
if (cmd == NULL) {
continue;
}
/* treat the remaining string as the arguments,
* which may need further parsing
@ -124,20 +337,24 @@ void sdb_mainloop() {
#endif
int i;
for (i = 0; i < NR_CMD; i ++) {
for (i = 0; i < NR_CMD; i++) {
if (strcmp(cmd, cmd_table[i].name) == 0) {
if (cmd_table[i].handler(args) < 0) { return; }
if (cmd_table[i].handler(args) < 0) {
return;
}
break;
}
}
if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }
if (i == NR_CMD) {
printf("Unknown command '%s'\n", cmd);
}
}
}
void init_sdb() {
/* Compile the regular expressions. */
init_regex();
// /* Compile the regular expressions. */
// init_regex();
/* Initialize the watchpoint pool. */
init_wp_pool();

View file

@ -18,6 +18,8 @@
#include <common.h>
word_t expr(char *e, bool *success);
word_t parse_expr(const char *arg, bool *success);
int wp_add(char * expr);
int wp_remove_by_number(int number);
#endif

View file

@ -1,36 +1,38 @@
/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan
*PSL v2. You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
*KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
*NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/
#include "sdb.h"
#include <common.h>
#include <stdio.h>
#define NR_WP 32
typedef struct watchpoint {
int NO;
struct watchpoint *next;
/* TODO: Add more members if necessary */
word_t val;
char *expr;
} WP;
static WP wp_pool[NR_WP] = {};
static WP *head = NULL, *free_ = NULL;
static WP *head = NULL, *tail = NULL, *free_ = NULL;
static int wp_count = 0;
void init_wp_pool() {
int i;
for (i = 0; i < NR_WP; i ++) {
for (i = 0; i < NR_WP; i++) {
wp_pool[i].NO = i;
wp_pool[i].next = (i == NR_WP - 1 ? NULL : &wp_pool[i + 1]);
}
@ -39,5 +41,110 @@ void init_wp_pool() {
free_ = wp_pool;
}
/* TODO: Implement the functionality of watchpoint */
static WP *wp_new() {
if (free_ == NULL) {
Error("wp_pool: Watchpoint pool not initialized or is full.");
return NULL;
}
WP *ret = free_;
free_ = free_->next;
ret->NO = 0;
ret->next = NULL;
return ret;
}
static void wp_delete(WP *wp) {
Assert(wp, "Failed to delete watchpoint from pool.");
wp->next = free_;
free_ = wp;
}
int wp_add(char * expr) {
WP *wp = wp_new();
if (wp == NULL) {
Error("watchpoint: Failed to add watchpoint, pool is full.");
goto failed_create;
}
wp->NO = wp_count++;
if (tail == NULL) {
head = wp;
tail = wp;
} else {
tail->next = wp;
tail = wp;
}
bool success = false;
wp->val = parse_expr(expr, &success);
if (!success) {
Error("Failed to parse given expression `%s`", expr);
goto failed_create;
}
int len = strlen(expr);
wp->expr = malloc((len + 1) * sizeof(char));
if (wp->expr == NULL) {
Error("Failed to allocate memory for expression");
goto failed_create;
}
strncpy(wp->expr, expr, len + 1);
wp->expr[len] = '\0';
return 0;
failed_create:
wp_delete(wp);
return 1;
}
int wp_remove_by_number(int number) {
WP *target_prev;
// Find previous node of target number
for (target_prev = head; target_prev != NULL && target_prev->next->NO != number; target_prev = target_prev->next) ;
if (target_prev == NULL) {
Error("Watchpoint not found, you can check current watchpoints with `info w`");
return 1;
}
WP *target = target_prev->next;
target_prev->next = target->next;
if (target == head) {
head = target->next;
} else if (target == tail) {
tail = target_prev;
}
wp_delete(target);
return 0;
}
static bool wp_check_change(WP* wp) {
bool success = false;
word_t result;
result = parse_expr(wp->expr, &success);
if (!success) {
panic("Failed to evaluate expression `%s`", wp->expr);
}
if (result != wp->val) {
wp->val = result;
return true;
}
return false;
}
/*
Check if watchpoint value changed after execution
*/
bool wp_eval_all() {
WP *wp;
bool value_change = false;
for (wp = head; wp != NULL; wp = wp->next) {
int prev_val = wp->val;
if (wp_check_change(wp)) {
printf("Watchpoint %d: %s\n %u -> %u\n", wp->NO, wp->expr, prev_val, wp->val);
value_change = true;
}
}
return value_change;
}

9
nemu/tests/Makefile Normal file
View file

@ -0,0 +1,9 @@
TEST_SRCS += tests/expr_test.c
YACC = bison
$(OBJ_DIR)/%: %.c $(TEST_OBJS) app
@mkdir -p $(dir $@)
@echo + CC $<
@$(CC) $(CFLAGS) -o $@.o -c $<
@echo + LD $@
@$(LD) $(LIBS) $(LDFLAGS) -o $@ $(TEST_OBJS) $@.o

244
nemu/tests/expr_test.c Normal file
View file

@ -0,0 +1,244 @@
#include "macro.h"
#include "sys/types.h"
#include <unistd.h>
#include <assert.h>
#include <check.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <addrexp.h>
#include <addrexp_lex.h>
#include <isa.h>
#include <reg.h>
char buf[65536] = {}, ref_buf[65536] = {};
static char code_buf[65536 + 128] = {}; // a little larger than `buf`
const int buf_start_pos = 0;
char *buf_ptr = buf + buf_start_pos, *ref_buf_ptr = ref_buf;
static char *code_format = "#include <stdio.h>\n"
"#include <stdint.h>\n"
"int main() { "
" uint32_t result = %s; "
" printf(\"%%u\", result); "
" return 0; "
"}";
void gen(char c) {
*(buf_ptr++) = c;
*(ref_buf_ptr++) = c;
}
void gen_num(void) {
uint32_t num = rand();
int len = 0, ref_len = 0;
switch (rand() % 3) {
case 0:
len = snprintf(buf_ptr, 100, "%u", num);
ref_len = snprintf(ref_buf_ptr, 100, "%uU", num);
break;
case 1:
len = snprintf(buf_ptr, 100, "0x%x", num);
ref_len = snprintf(ref_buf_ptr, 100, "%uU", num);
break;
case 2:
len = snprintf(buf_ptr, 100, "%d", num);
ref_len = snprintf(ref_buf_ptr, 100, "%d", num);
break;
default:
assert(0);
}
buf_ptr += len;
ref_buf_ptr += ref_len;
}
void gen_rand_op(void) {
switch (rand() % 4) {
case 0:
gen('+');
break;
case 1:
gen('-');
break;
case 2:
gen('*');
break;
case 3:
gen('/');
break;
}
}
void gen_rand_expr(void) {
int choice = rand() % 3;
if (buf_ptr - buf > 2000) {
choice = 0;
}
switch (choice) {
case 0:
gen_num();
break;
case 1:
gen('(');
gen_rand_expr();
gen(')');
break;
default:
gen_rand_expr();
gen(' ');
gen_rand_op();
gen(' ');
gen_rand_expr();
break;
}
}
START_TEST(test_expr_random_100) {
srand(time(0) + _i * 100);
gen_rand_expr();
sprintf(code_buf, code_format, ref_buf);
FILE *fp = fopen("/tmp/.code.c", "w");
ck_assert(fp != NULL);
fputs(code_buf, fp);
fclose(fp);
int ret =
system("gcc /tmp/.code.c -Werror=div-by-zero -o /tmp/.expr 2>/dev/null");
if (ret == 256) {
// Probably devide by zero. Skip
goto clean_up;
}
ck_assert_msg(!ret, "system ret: %d, error: %s", ret, strerror(ret));
fp = popen("/tmp/.expr", "r");
ck_assert(fp != NULL);
uint32_t reference;
ret = fscanf(fp, "%u", &reference);
ck_assert(ret == 1);
pclose(fp);
// fprintf(stderr, "\n\tbuf = %s\n\taddr = %u, reference = %u", buf, addr,
// reference);
yy_scan_string(buf + buf_start_pos);
uint32_t addr;
ck_assert(!yyparse(&addr));
yylex_destroy();
ck_assert_msg(addr == reference,
"\n\tbuf = %s\n\t(addr = %u) != (reference = %u)\n", buf, addr,
reference);
clean_up:
while (buf_ptr != buf + buf_start_pos) {
*(--buf_ptr) = '\0';
}
while (ref_buf_ptr != ref_buf) {
*(--ref_buf_ptr) = '\0';
}
}
END_TEST
struct {
const char *expr;
uint32_t reference;
} exprs[] = {
{"-1", 0xFFFFFFFFU},
{"-0x1", 0xFFFFFFFFU},
{"0--1", 0x1},
{"0--0x1", 0x1},
}, reg_exprs[] = {
{"$ra", 0x1},
{"0x2 + 4*-$a7", 0xFFFFFFBEU},
{"0x1831/$gp + 13", 2077U},
{"$$0 == 123", 0},
{"$$0 == 0", 1},
};
START_TEST(test_expr_negative_operand) {
yy_scan_string(exprs[_i].expr);
uint32_t addr;
ck_assert(!yyparse(&addr));
yylex_destroy();
ck_assert_msg(addr == exprs[_i].reference,
"\n\texpr = %s\n\t(addr = %u) != (reference = %u)\n", exprs[_i].expr,
addr, exprs[_i].reference);
}
END_TEST
extern const char *regs[];
START_TEST(test_expr_plain_register) {
int i, j, result;
char buf[30] = {};
uint32_t value;
// NOTE: need to fix this if want to support more arch
buf[0] = '$';
for (i = 0; i < 32; i++) {
ck_assert(strncpy(buf + 1, regs[i], 10) != NULL);
gpr(i) = i;
yy_scan_string(buf);
result = yyparse(&value);
yylex_destroy();
ck_assert_msg(result == 0, "expr = %s\n", buf);
ck_assert(value == i);
for (j = 1; j < 10; j++) {
buf[j] = '\0';
}
}
}
END_TEST
START_TEST(test_expr_register) {
int i;
uint32_t value;
for (i = 0; i < 32; i++) {
gpr(i) = i;
}
yy_scan_string(reg_exprs[_i].expr);
ck_assert(!yyparse(&value));
yylex_destroy();
ck_assert_msg(value == reg_exprs[_i].reference,
"\n\texpr = %s\n\t(addr = %u) != (reference = %u)\n", reg_exprs[_i].expr,
value, reg_exprs[_i].reference);
}
END_TEST
Suite *expr_suite(void) {
Suite *s;
TCase *tc_core;
s = suite_create("Expr test");
tc_core = tcase_create("Core");
tcase_add_loop_test(tc_core, test_expr_random_100, 0, 20);
tcase_add_loop_test(tc_core, test_expr_negative_operand, 0,
sizeof(exprs) / sizeof(exprs[0]));
tcase_add_loop_test(tc_core, test_expr_register, 0,
sizeof(reg_exprs) / sizeof(reg_exprs[0]));
tcase_add_test(tc_core, test_expr_plain_register);
suite_add_tcase(s, tc_core);
return s;
}
int main(void) {
int number_failed;
Suite *s;
SRunner *sr;
s = expr_suite();
sr = srunner_create(s);
srunner_run_all(sr, CK_NORMAL);
number_failed = srunner_ntests_failed(sr);
srunner_free(sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}