Compare commits

...

10 Commits

Author SHA1 Message Date
dd8c65ef79 loop.tasm 2025-03-12 21:27:40 +05:00
0fa4e24421 main section compilation fix 2025-03-12 21:27:34 +05:00
ee162a70ed jump 2025-03-12 12:57:42 +05:00
b9fa669fd1 fixed bugs 2025-03-12 12:57:16 +05:00
ad5c2b856a logical operators 2025-03-11 14:01:47 +05:00
4de066b6c1 test render loop 2025-03-09 18:35:56 +05:00
0291279f1a sdl3 2025-02-27 22:53:27 +05:00
c2bd5922ff syntax error 2025-02-27 22:47:45 +05:00
3e3f01db4e register struct update 2025-02-13 22:17:55 +05:00
a69d68f69c instructions rename and uninitialized memory error fix 2025-02-12 14:27:50 +05:00
31 changed files with 558 additions and 130 deletions

2
.vscode/launch.json vendored
View File

@@ -7,7 +7,7 @@
"request": "launch", "request": "launch",
"program": "${workspaceFolder}/bin/tcpu", "program": "${workspaceFolder}/bin/tcpu",
"windows": { "program": "${workspaceFolder}/bin/tcpu.exe" }, "windows": { "program": "${workspaceFolder}/bin/tcpu.exe" },
"args": [ "-c", "../examples/s.tasm", "o.bin", "--debug" ], "args": [ "-c", "../examples/conditional_jump.tasm", "o.bin", "--debug", "-i", "o.bin" ],
"cwd": "${workspaceFolder}/bin", "cwd": "${workspaceFolder}/bin",
"preLaunchTask": "build_exec_dbg", "preLaunchTask": "build_exec_dbg",
"stopAtEntry": false, "stopAtEntry": false,

View File

@@ -3,7 +3,8 @@ Machine code interpreter written in pure C. Can execute programs up to 1 MEGABYT
## Building ## Building
1. Install [cbuild](https://timerix.ddns.net:3322/Timerix/cbuild.git) 1. Install [cbuild](https://timerix.ddns.net:3322/Timerix/cbuild.git)
2. ```sh 2. Install [SDL3](https://github.com/libsdl-org/SDL) and [SDL3_image](https://github.com/libsdl-org/SDL_image) from package manager or source.
3. ```sh
cbuild build_exec_dbg cbuild build_exec_dbg
``` ```
@@ -12,8 +13,8 @@ Machine code interpreter written in pure C. Can execute programs up to 1 MEGABYT
| code | name | arguments | details | | code | name | arguments | details |
|------|------|-----------|---------| |------|------|-----------|---------|
| 00 | NOP | | ignored instruction | | 00 | NOP | | ignored instruction |
| 01 | PUSH | `dst_register`, `value_size(bytes)`, `value` | push constant value into `dst_register` | | 01 | MOVC | `dst_register`, `value` | push constant value into `dst_register` |
| 02 | MOV | `dst_register`, `src_register` | copy value from `src_register` to `dst_register` | 02 | MOVR | `dst_register`, `src_register` | copy value from `src_register` to `dst_register`
| 03 | ADD | `dst_register`, `src_register` | `dst` += `src` | | 03 | ADD | `dst_register`, `src_register` | `dst` += `src` |
| 04 | SUB | `dst_register`, `src_register` | `dst` -= `src` | | 04 | SUB | `dst_register`, `src_register` | `dst` -= `src` |
| 05 | MUL | `dst_register`, `src_register` | `dst` *= `src` | | 05 | MUL | `dst_register`, `src_register` | `dst` *= `src` |
@@ -25,10 +26,10 @@ Machine code interpreter written in pure C. Can execute programs up to 1 MEGABYT
### Registers ### Registers
| code | name | size (bits) | | code | name | size (bits) |
|------|------|-------------| |------|------|-------------|
| 00 | ax | 32 | | 01 | ax | 32 |
| 01 | bx | 32 | | 02 | bx | 32 |
| 02 | cx | 32 | | 03 | cx | 32 |
| 03 | dx | 32 | | 04 | dx | 32 |
### System functions ### System functions
To call a system function you need to push values to registers and write `SYS` opcode. The return value of a function will will be avaliable in `ax` after call. To call a system function you need to push values to registers and write `SYS` opcode. The return value of a function will will be avaliable in `ax` after call.

9
TODO.md Normal file
View File

@@ -0,0 +1,9 @@
# TODO List
- add negative number arguments support
- change section binary format:
1. code
2. exit instruction with code ERR_U_FORGOT_TO_CALL_EXIT
3. data
- add padding to compilation
- arguments validation for each instruction
- VM debug mode

View File

@@ -0,0 +1,32 @@
/*
Example of behavior change depending on some condition
*/
.main:
movc ax 1
movc bx 2
gt cx ax bx
jnz @true cx
jz @false cx
.true:
const8 true.msg "true\n"
movc cx @true.msg
movc dx #true.msg
jmp @print
.false
const8 false.msg "false\n"
movc cx @false.msg
movc dx #false.msg
jmp @print
.print:
movc ax 1
movc bx 1
sys
jmp @end
.end:
movc ax 0
exit

14
examples/loop.tasm Normal file
View File

@@ -0,0 +1,14 @@
/*
Example of self-repeating code section
*/
.main:
.loop
const8 datum "ITERATION!!! "
movc ax 1
movc bx 1
movc cx @datum
movc dx #datum
sys
jmp @loop

View File

@@ -1,16 +0,0 @@
/*
"hello world" program in my assembly language
*/
.data:
// named array of 8-bit values
const8 msg "Hello, World :3\0"
.main:
push ax 1; // sys_write
push bx 1; // stdout
push cx @msg; // address of msg data
push dx #msg; // size of msg data
sys
push ax 0
exit

16
examples/stdout.tasm Normal file
View File

@@ -0,0 +1,16 @@
/*
"hello world" program in my assembly language
*/
.data:
// named array of 8-bit values
const8 msg "Hello, World"
.main:
movc ax 1; // sys_write
movc bx 1; // stdout
movc cx @msg; // address of msg data
movc dx #msg; // size of msg data
sys
movc ax 0
exit

9
examples/window.tasm Normal file
View File

@@ -0,0 +1,9 @@
/*
Example of graphical application
*/
.main:
jif
jel
exit

View File

@@ -32,12 +32,13 @@ case "$OS" in
WINDOWS) WINDOWS)
EXEC_FILE="$PROJECT.exe" EXEC_FILE="$PROJECT.exe"
SHARED_LIB_FILE="$PROJECT.dll" SHARED_LIB_FILE="$PROJECT.dll"
# example: "-I./" LINKER_LIBS="-lSDL3_image -lSDL3"
INCLUDE="" INCLUDE=""
;; ;;
LINUX) LINUX)
EXEC_FILE="$PROJECT" EXEC_FILE="$PROJECT"
SHARED_LIB_FILE="$PROJECT.so" SHARED_LIB_FILE="$PROJECT.so"
LINKER_LIBS="-lSDL3_image -lSDL3"
INCLUDE="" INCLUDE=""
;; ;;
*) *)
@@ -57,7 +58,7 @@ case "$TASK" in
# -fdata-sections -ffunction-sections -Wl,--gc-sections removes unused code # -fdata-sections -ffunction-sections -Wl,--gc-sections removes unused code
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-use -fprofile-prefix-path=$(realpath $OBJDIR)/objects -fdata-sections -ffunction-sections -Wl,--gc-sections" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-use -fprofile-prefix-path=$(realpath $OBJDIR)/objects -fdata-sections -ffunction-sections -Wl,--gc-sections"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_exec.sh TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -66,7 +67,7 @@ case "$TASK" in
build_exec_dbg) build_exec_dbg)
C_ARGS="-O0 -g3" C_ARGS="-O0 -g3"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_exec.sh TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -75,7 +76,7 @@ case "$TASK" in
build_shared_lib) build_shared_lib)
C_ARGS="-O2 -fpic -flto -shared" C_ARGS="-O2 -fpic -flto -shared"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS -Wl,-soname,$SHARED_LIB_FILE" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS -Wl,-soname,$SHARED_LIB_FILE"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -84,7 +85,7 @@ case "$TASK" in
build_shared_lib_dbg) build_shared_lib_dbg)
C_ARGS="-O0 -g3 -fpic -shared" C_ARGS="-O0 -g3 -fpic -shared"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS -Wl,-soname,$SHARED_LIB_FILE" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS -Wl,-soname,$SHARED_LIB_FILE"
PRE_TASK_SCRIPT= PRE_TASK_SCRIPT=
TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh TASK_SCRIPT=cbuild/default_tasks/build_shared_lib.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -125,7 +126,7 @@ case "$TASK" in
# -fprofile-prefix-path sets path where profiling info about objects will be saved # -fprofile-prefix-path sets path where profiling info about objects will be saved
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-generate -fprofile-prefix-path=$(realpath $OBJDIR)/objects" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -fprofile-generate -fprofile-prefix-path=$(realpath $OBJDIR)/objects"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/profile.sh TASK_SCRIPT=cbuild/default_tasks/profile.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -138,7 +139,7 @@ case "$TASK" in
# -pg adds code to executable, that generates file containing function call info (gmon.out) # -pg adds code to executable, that generates file containing function call info (gmon.out)
C_ARGS="-O2 -flto=auto -fuse-linker-plugin -pg" C_ARGS="-O2 -flto=auto -fuse-linker-plugin -pg"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/gprof.sh TASK_SCRIPT=cbuild/default_tasks/gprof.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -152,7 +153,7 @@ case "$TASK" in
# -pg adds code to executable, that generates file containing function call info (gmon.out) # -pg adds code to executable, that generates file containing function call info (gmon.out)
C_ARGS="-O2 -flto=auto -fuse-linker-plugin" C_ARGS="-O2 -flto=auto -fuse-linker-plugin"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/callgrind.sh TASK_SCRIPT=cbuild/default_tasks/callgrind.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=
@@ -162,7 +163,7 @@ case "$TASK" in
OUTDIR="$OUTDIR/sanitize" OUTDIR="$OUTDIR/sanitize"
C_ARGS="-O0 -g3 -fsanitize=undefined,address" C_ARGS="-O0 -g3 -fsanitize=undefined,address"
CPP_ARGS="$C_ARGS" CPP_ARGS="$C_ARGS"
LINKER_ARGS="$CPP_ARGS" LINKER_ARGS="$CPP_ARGS $LINKER_LIBS"
PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh PRE_TASK_SCRIPT=cbuild/default_tasks/build_exec.sh
TASK_SCRIPT=cbuild/default_tasks/exec.sh TASK_SCRIPT=cbuild/default_tasks/exec.sh
POST_TASK_SCRIPT= POST_TASK_SCRIPT=

90
src/VM/Display/Display.c Normal file
View File

@@ -0,0 +1,90 @@
#include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h>
#include "Display.h"
typedef struct Display {
str name;
i32 width;
i32 height;
SDL_Window* window;
SDL_Renderer* renderer;
} Display;
static SDL_InitState sdl_init_state = {0};
Display* Display_create(str name, i32 w, i32 h, DisplayFlags flags){
Display* d = malloc(sizeof(Display));
d->name = str_copy(name);
d->width = w;
d->height = h;
d->window = NULL;
d->renderer = NULL;
if (SDL_ShouldInit(&sdl_init_state)) {
bool sdl_initialized = SDL_Init(SDL_INIT_VIDEO);
SDL_SetInitialized(&sdl_init_state, sdl_initialized);
if(!sdl_initialized)
return false;
}
SDL_WindowFlags window_flags = SDL_WINDOW_ALWAYS_ON_TOP;
if(!SDL_CreateWindowAndRenderer(d->name.data, d->width, d->height, window_flags, &d->window, &d->renderer)){
return false;
}
return d;
}
void Display_destroy(Display* d){
free(d->name.data);
SDL_DestroyRenderer(d->renderer);
SDL_DestroyWindow(d->window);
free(d);
// if (SDL_ShouldQuit(&sdl_init_state)) {
// SDL_Quit();
// SDL_SetInitialized(&sdl_init_state, false);
// }
}
bool Display_setName(Display* d, str name){
d->name = str_copy(name);
return SDL_SetWindowTitle(d->window, name.data);
}
bool Display_setSize(Display* d, u32 w, u32 h){
d->width = w;
d->height = h;
return SDL_SetWindowSize(d->window, w, h);
}
bool Display_setDrawingColor(Display* d, ColorRGBA color){
return SDL_SetRenderDrawColor(d->renderer, color.r, color.g, color.b, color.a);
}
bool Display_clear(Display* d){
return SDL_RenderClear(d->renderer);
}
#define Rect_copy(DST, SRC) {\
DST.x = SRC.x;\
DST.y = SRC.y;\
DST.w = SRC.w;\
DST.h = SRC.h;\
}
bool Display_fillRect(Display* d, Rect rect) {
SDL_FRect sdl_rect;
Rect_copy(sdl_rect, rect);
return SDL_RenderFillRect(d->renderer, &sdl_rect);
}
bool Display_swapBuffers(Display* d){
return SDL_RenderPresent(d->renderer);
}
NULLABLE(cstr) Display_getError(){
return SDL_GetError();
}

32
src/VM/Display/Display.h Normal file
View File

@@ -0,0 +1,32 @@
#pragma once
#include "../../std.h"
#include "../../string/str.h"
typedef struct Rect {
i32 x, y;
i32 w, h;
} Rect;
#define Rect_create(X, Y, W, H) ((Rect){ .x = X, .y = Y, .w = W, .h = H})
typedef struct ColorRGBA {
u8 r, g, b, a;
} ColorRGBA;
#define ColorRGBA_create(R, G, B, A) ((ColorRGBA){ .r = R, .g = G, .b = B, .a = A })
typedef enum DisplayFlags {
DisplayFlags_Default = 0
} DisplayFlags;
typedef struct Display Display;
Display* Display_create(str name, i32 w, i32 h, DisplayFlags flags);
void Display_destroy(Display* d);
bool Display_setName(Display* d, str name);
bool Display_setSize(Display* d, u32 w, u32 h);
bool Display_setDrawingColor(Display* d, ColorRGBA color);
bool Display_clear(Display* d);
bool Display_fillRect(Display* d, Rect rect);
bool Display_swapBuffers(Display* d);
NULLABLE(cstr) Display_getError();

View File

@@ -72,7 +72,7 @@ i32 VM_boot(VM* vm){
} }
// exit code of the program should be in ax register // exit code of the program should be in ax register
return vm->ax.i32v; return vm->registers.a.u32v0;
} }
bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){ bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){

View File

@@ -3,28 +3,31 @@
#include "../string/str.h" #include "../string/str.h"
typedef union Register { typedef union Register {
u32 u32v; u64 u64v;
i32 i32v; f64 f64v;
f32 f32v; struct {
u32 u32v0;
u32 u32v1;
};
struct {
f32 f32v0;
f32 f32v1;
};
struct { struct {
u16 u16v0; u16 u16v0;
u16 u16v1; u16 u16v1;
}; u16 u16v2;
struct { u16 u16v3;
i16 i16v0;
i16 i16v1;
}; };
struct { struct {
u8 u8v0; u8 u8v0;
u8 u8v1; u8 u8v1;
u8 u8v2; u8 u8v2;
u8 u8v3; u8 u8v3;
}; u8 u8v4;
struct { u8 u8v5;
i8 i8v0; u8 u8v6;
i8 i8v1; u8 u8v7;
i8 i8v2;
i8 i8v3;
}; };
} Register; } Register;
@@ -38,13 +41,13 @@ typedef enum VMState {
typedef struct VM { typedef struct VM {
union { union {
struct { struct {
Register ax; Register a;
Register bx; Register b;
Register cx; Register c;
Register dx; Register d;
};
Register registers[4];
}; };
Register array[4];
} registers;
VMState state; VMState state;
char* NULLABLE(error_message); // not null on if state == VMState_InternalError char* NULLABLE(error_message); // not null on if state == VMState_InternalError

18
src/VM/time.c Normal file
View File

@@ -0,0 +1,18 @@
#include <SDL3/SDL_timer.h>
#include "time.h"
void time_sleepMS(u32 ms){
SDL_Delay(ms);
}
void time_sleepNS(u64 ns){
SDL_DelayNS(ns);
}
u64 time_getMonotonicMS(){
return SDL_GetTicks();
}
u64 time_getMonotonicNS(){
return SDL_GetTicksNS();
}

8
src/VM/time.h Normal file
View File

@@ -0,0 +1,8 @@
#pragma once
#include "../std.h"
void time_sleepMS(u32 ms);
void time_sleepNS(u64 ns);
u64 time_getMonotonicMS();
u64 time_getMonotonicNS();

View File

@@ -27,6 +27,8 @@ void BinaryObject_construct(BinaryObject* ptr){
ptr->section_list = List_CompiledSection_alloc(64); ptr->section_list = List_CompiledSection_alloc(64);
HashMap_CompiledSectionPtr_alloc(&ptr->section_map); HashMap_CompiledSectionPtr_alloc(&ptr->section_map);
HashMap_ConstDataProps_alloc(&ptr->const_data_map); HashMap_ConstDataProps_alloc(&ptr->const_data_map);
ptr->main_section = NULL;
ptr->total_size = 0;
} }
void BinaryObject_free(BinaryObject* ptr){ void BinaryObject_free(BinaryObject* ptr){

View File

@@ -57,6 +57,7 @@ HashMap_declare(CompiledSectionPtr);
typedef struct BinaryObject { typedef struct BinaryObject {
List_CompiledSection section_list; List_CompiledSection section_list;
HashMap_CompiledSectionPtr section_map; HashMap_CompiledSectionPtr section_map;
NULLABLE(CompiledSection*) main_section;
HashMap_ConstDataProps const_data_map; HashMap_ConstDataProps const_data_map;
u32 total_size; u32 total_size;
} BinaryObject; } BinaryObject;

View File

@@ -68,7 +68,7 @@ static bool compileSection(Compiler* cmp, Section* sec){
CompiledSection* cs = List_CompiledSection_expand(&cmp->binary.section_list, 1); CompiledSection* cs = List_CompiledSection_expand(&cmp->binary.section_list, 1);
CompiledSection_construct(cs, sec->name); CompiledSection_construct(cs, sec->name);
if(!HashMap_CompiledSectionPtr_tryPush(&cmp->binary.section_map, cs->name, cs)){ if(!HashMap_CompiledSectionPtr_tryPush(&cmp->binary.section_map, cs->name, cs)){
returnError("duplicate section '%s'", str_copy(sec->name)); returnError("duplicate section '%s'", str_copy(sec->name).data);
} }
// compile code // compile code
@@ -124,6 +124,9 @@ static bool compileSection(Compiler* cmp, Section* sec){
} }
static bool compileBinary(Compiler* cmp){ static bool compileBinary(Compiler* cmp){
returnErrorIf_auto(cmp->state != CompilerState_Parsing);
cmp->state = CompilerState_Compiling;
for(u32 i = 0; i < cmp->ast.sections.len; i++){ for(u32 i = 0; i < cmp->ast.sections.len; i++){
SectionPtr sec = &cmp->ast.sections.data[i]; SectionPtr sec = &cmp->ast.sections.data[i];
if(!compileSection(cmp, sec)){ if(!compileSection(cmp, sec)){
@@ -137,6 +140,7 @@ static bool compileBinary(Compiler* cmp){
if(main_sec_ptrptr == NULL){ if(main_sec_ptrptr == NULL){
returnError("no 'main' section was defined"); returnError("no 'main' section was defined");
} }
cmp->binary.main_section = *main_sec_ptrptr;
// create linked list of CompiledSection where main is the first // create linked list of CompiledSection where main is the first
CompiledSection* prev_sec = *main_sec_ptrptr; CompiledSection* prev_sec = *main_sec_ptrptr;
@@ -144,10 +148,6 @@ static bool compileBinary(Compiler* cmp){
for(u32 i = 0; i < cmp->binary.section_list.len; i++){ for(u32 i = 0; i < cmp->binary.section_list.len; i++){
CompiledSection* sec = &cmp->binary.section_list.data[i]; CompiledSection* sec = &cmp->binary.section_list.data[i];
total_size += sec->bytes.len; total_size += sec->bytes.len;
if(str_equals(sec->name, main_sec_name))
continue;
prev_sec->next = sec;
sec->offset = prev_sec->offset + prev_sec->bytes.len;
ConstDataProps cd = ConstDataProps_construct(sec->name, sec->bytes.len, sec->offset); ConstDataProps cd = ConstDataProps_construct(sec->name, sec->bytes.len, sec->offset);
if(!HashMap_ConstDataProps_tryPush(&cmp->binary.const_data_map, cd.name, cd)){ if(!HashMap_ConstDataProps_tryPush(&cmp->binary.const_data_map, cd.name, cd)){
@@ -160,6 +160,12 @@ static bool compileBinary(Compiler* cmp){
returnError("duplicate named data '%s'", str_copy(cd.name).data); returnError("duplicate named data '%s'", str_copy(cd.name).data);
} }
} }
if(str_equals(sec->name, main_sec_name))
continue;
prev_sec->next = sec;
sec->offset = prev_sec->offset + prev_sec->bytes.len;
prev_sec = sec;
} }
// insert calculated offsets into sections // insert calculated offsets into sections
@@ -194,26 +200,16 @@ static bool compileBinary(Compiler* cmp){
} }
static bool writeBinaryFile(Compiler* cmp, FILE* f){ static bool writeBinaryFile(Compiler* cmp, FILE* f){
returnErrorIf_auto(cmp->state != CompilerState_Parsing); returnErrorIf_auto(cmp->state != CompilerState_Compiling);
cmp->state = CompilerState_Compiling;
if(!compileBinary(cmp)){ CompiledSection* sec = cmp->binary.main_section;
return false;
}
CompiledSection** main_sec_ptrptr = HashMap_CompiledSectionPtr_tryGetPtr(&cmp->binary.section_map, STR("main"));
if(main_sec_ptrptr == NULL){
returnError("no 'main' section was defined");
}
CompiledSection* sec = *main_sec_ptrptr;
while(sec){ while(sec){
fwrite(sec->bytes.data, 1, sec->bytes.len, f); fwrite(sec->bytes.data, 1, sec->bytes.len, f);
fflush(f);
sec = sec->next; sec = sec->next;
} }
//TODO: print warnings for unused sections //TODO: print warnings for unused sections
return true; return true;
} }
@@ -289,6 +285,7 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
if(debug_log) if(debug_log)
printf("===================================[parsing]===================================\n"); printf("===================================[parsing]===================================\n");
success = Compiler_parse(cmp); success = Compiler_parse(cmp);
if (debug_log){ if (debug_log){
printf("-------------------------------------[AST]-------------------------------------\n"); printf("-------------------------------------[AST]-------------------------------------\n");
for(u32 i = 0; i < cmp->ast.sections.len; i++){ for(u32 i = 0; i < cmp->ast.sections.len; i++){
@@ -308,6 +305,11 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
for(u32 j = 0; j < sec->code.len; j++){ for(u32 j = 0; j < sec->code.len; j++){
Operation* op = &sec->code.data[j]; Operation* op = &sec->code.data[j];
const Instruction* instr = Instruction_getByOpcode(op->opcode); const Instruction* instr = Instruction_getByOpcode(op->opcode);
if(instr == NULL){
fclose(f);
returnError("unknown opcode: %i", op->opcode)
}
printf(" %s", instr->name.data); printf(" %s", instr->name.data);
for(u32 k = 0; k < op->args.len; k++){ for(u32 k = 0; k < op->args.len; k++){
Argument* arg = &op->args.data[k]; Argument* arg = &op->args.data[k];
@@ -348,6 +350,7 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
} }
} }
} }
if(!success){ if(!success){
fclose(f); fclose(f);
return false; return false;
@@ -355,6 +358,25 @@ bool Compiler_compile(Compiler* cmp, cstr source_file_name, cstr out_file_name,
if(debug_log) if(debug_log)
printf("==================================[compiling]==================================\n"); printf("==================================[compiling]==================================\n");
success = compileBinary(cmp);
if(debug_log){
for(u32 i = 0; i < cmp->binary.section_list.len; i++){
CompiledSection* sec = &cmp->binary.section_list.data[i];
str tmpstr = str_copy(sec->name);
printf("compiled section '%s' to %u bytes with offset 0x%x\n", tmpstr.data, sec->bytes.len, sec->offset);
free(tmpstr.data);
}
}
if(!success){
fclose(f);
return false;
}
if(debug_log)
printf("----------------------------[writing output to file]---------------------------\n");
success = writeBinaryFile(cmp, f); success = writeBinaryFile(cmp, f);
fclose(f); fclose(f);
if(success){ if(success){

View File

@@ -130,7 +130,7 @@ static void readArguments(Compiler* cmp){
// string argument reading // string argument reading
if(quot != '\0'){ if(quot != '\0'){
if(c == quot && cmp->code.data[cmp->pos - 1] != '\\'){ if(c == quot && (cmp->code.data[cmp->pos - 1] != '\\' || cmp->code.data[cmp->pos - 2] == '\\')){
quot = '\0'; quot = '\0';
} }
else if(c == '\r' || c == '\n'){ else if(c == '\r' || c == '\n'){

View File

@@ -44,6 +44,7 @@ static NULLABLE(str) resolveEscapeSequences(Compiler* cmp, str src){
c = src.data[i]; c = src.data[i];
if(c == '\\'){ if(c == '\\'){
escaped = !escaped; escaped = !escaped;
if(escaped)
continue; continue;
} }
@@ -69,11 +70,17 @@ static NULLABLE(str) resolveEscapeSequences(Compiler* cmp, str src){
case 'e': case 'e':
StringBuilder_append_char(&sb, '\e'); StringBuilder_append_char(&sb, '\e');
break; break;
case '"':
case '\'':
StringBuilder_append_char(&sb, c);
break;
default: default:
setError_unexpectedTokenChar(cmp->tokens.data[cmp->tok_i], i); setError_unexpectedTokenChar(cmp->tokens.data[cmp->tok_i], i);
StringBuilder_free(&sb); StringBuilder_free(&sb);
return str_null; return str_null;
} }
escaped = false;
} }
return StringBuilder_getStr(&sb); return StringBuilder_getStr(&sb);
@@ -259,10 +266,12 @@ bool Compiler_parse(Compiler* cmp){
// data definition starts with const // data definition starts with const
if(str_startsWith(instr_name, STR("const"))){ if(str_startsWith(instr_name, STR("const"))){
DataDefinition* dataDefPtr = List_DataDefinition_expand(&sec->data, 1); DataDefinition* dataDefPtr = List_DataDefinition_expand(&sec->data, 1);
memset(dataDefPtr, 0, sizeof(DataDefinition));
parseDataDefinition(cmp, instr_name, dataDefPtr); parseDataDefinition(cmp, instr_name, dataDefPtr);
} }
else { else {
Operation* operPtr = List_Operation_expand(&sec->code, 1); Operation* operPtr = List_Operation_expand(&sec->code, 1);
memset(operPtr, 0, sizeof(Operation));
parseOperation(cmp, instr_name, operPtr); parseOperation(cmp, instr_name, operPtr);
} }
break; break;

View File

@@ -0,0 +1,40 @@
#include "impl_macros.h"
// JUMP [destination address]
i32 JMP_impl(VM* vm){
u32 dst_addr = 0;
readVar(dst_addr);
vm->current_pos = dst_addr;
return sizeof(dst_addr);
}
// JNZ [destination address] [condition register]
i32 JNZ_impl(VM* vm){
u32 dst_addr = 0;
readVar(dst_addr);
u8 cond_register_i = 0;
readRegisterVar(cond_register_i);
if(vm->registers.array[cond_register_i].u32v0 != 0){
vm->current_pos = dst_addr;
}
return sizeof(dst_addr) + sizeof(cond_register_i);
}
// JZ [destination address] [condition register]
i32 JZ_impl(VM* vm){
u32 dst_addr = 0;
readVar(dst_addr);
u8 cond_register_i = 0;
readRegisterVar(cond_register_i);
if(vm->registers.array[cond_register_i].u32v0 == 0){
vm->current_pos = dst_addr;
}
return sizeof(dst_addr) + sizeof(cond_register_i);
}

View File

@@ -1,15 +1,15 @@
#include "impl_macros.h" #include "impl_macros.h"
/// PUSH [dst_register] [value_size] [value] /// MOVC [dst_register] [value_size] [value]
i32 PUSH_impl(VM* vm){ i32 MOVC_impl(VM* vm){
u8 dst_register_i = 0; u8 dst_register_i = 0;
readRegisterVar(dst_register_i); readRegisterVar(dst_register_i);
/*u8 value_size = 0; /*u8 value_size = 0;
readValueSizeVar(value_size);*/ readValueSizeVar(value_size);*/
u8 value_size = 4;\ u8 value_size = 4;\
vm->registers[dst_register_i].u32v = 0; vm->registers.array[dst_register_i].u64v = 0;
if(!VM_dataRead(vm, &vm->registers[dst_register_i].u32v, vm->current_pos, value_size)) if(!VM_dataRead(vm, &vm->registers.array[dst_register_i].u64v, vm->current_pos, value_size))
return -1; return -1;
vm->current_pos += value_size; vm->current_pos += value_size;

View File

@@ -1,7 +1,7 @@
#include "impl_macros.h" #include "impl_macros.h"
/// MOV [dst_register] [src_register] /// MOVR [dst_register] [src_register]
i32 MOV_impl(VM* vm){ i32 MOVR_impl(VM* vm){
u8 dst_register_i = 0; u8 dst_register_i = 0;
readRegisterVar(dst_register_i); readRegisterVar(dst_register_i);
u8 src_register_i = 0; u8 src_register_i = 0;
@@ -11,6 +11,6 @@ i32 MOV_impl(VM* vm){
return -1; return -1;
} }
vm->registers[dst_register_i].u32v = vm->registers[src_register_i].u32v; vm->registers.array[dst_register_i].u64v = vm->registers.array[src_register_i].u64v;
return sizeof(dst_register_i) + sizeof(src_register_i); return sizeof(dst_register_i) + sizeof(src_register_i);
} }

View File

@@ -19,9 +19,9 @@ FILE* NULLABLE(fileFromN)(VM* vm, u32 file_n){
// cx - buffer ptr // cx - buffer ptr
// dx - buffer size // dx - buffer size
i32 SYS_read(VM* vm){ i32 SYS_read(VM* vm){
const u32 file_n = vm->bx.u32v; const u32 file_n = vm->registers.b.u32v0;
u8* const buf = vm->data + vm->cx.u32v; u8* const buf = vm->data + vm->registers.c.u32v0;
const u32 size = vm->dx.u32v; const u32 size = vm->registers.d.u32v0;
if(buf + size > vm->data + vm->data_size) if(buf + size > vm->data + vm->data_size)
return 40; return 40;
@@ -35,9 +35,9 @@ i32 SYS_read(VM* vm){
// cx - buffer ptr // cx - buffer ptr
// dx - buffer size // dx - buffer size
i32 SYS_write(VM* vm){ i32 SYS_write(VM* vm){
const u32 file_n = vm->bx.u32v; const u32 file_n = vm->registers.b.u32v0;
u8* const buf = vm->data + vm->cx.u32v; u8* const buf = vm->data + vm->registers.c.u32v0;
const u32 size = vm->dx.u32v; const u32 size = vm->registers.d.u32v0;
if(buf + size > vm->data + vm->data_size) if(buf + size > vm->data + vm->data_size)
return 41; return 41;
@@ -50,13 +50,13 @@ i32 SYS_write(VM* vm){
/// before call: ax - func code /// before call: ax - func code
/// after call: ax - result code /// after call: ax - result code
i32 SYS_impl(VM* vm){ i32 SYS_impl(VM* vm){
u8 func_code = vm->ax.u8v0; u32 func_code = vm->registers.a.u32v0;
u32 result_code = 0; i32 result_code = 0;
switch(func_code){ switch(func_code){
case 0: case 0:
result_code = SYS_read(vm); result_code = SYS_read(vm);
break; break;
case 1:; case 1:
result_code = SYS_write(vm); result_code = SYS_write(vm);
break; break;
default: default:
@@ -64,6 +64,6 @@ i32 SYS_impl(VM* vm){
return -1; return -1;
} }
vm->ax.u32v = result_code; vm->registers.a.u64v = result_code;
return 0; return 0;
} }

View File

@@ -23,7 +23,7 @@
/* /*
#define validateValueSize(VAR) {\ #define validateValueSize(VAR) {\
if(VAR < 1 || VAR > 4){\ if(VAR < 1 || VAR > 8){\
VM_setError(vm, "invalid value_size (%x)", VAR);\ VM_setError(vm, "invalid value_size (%x)", VAR);\
return -1;\ return -1;\
}\ }\

View File

@@ -0,0 +1,93 @@
#include "impl_macros.h"
#define logicalOperator1Impl(NAME, OPERATOR)\
i32 NAME##_impl (VM* vm) {\
u8 src_register_i = 0;\
readRegisterVar(src_register_i);\
/*u8 value_size = 0;\
readValueSizeVar(value_size);*/\
u8 value_size = 4;\
\
switch(value_size){\
case 1: \
vm->registers.array[src_register_i].u8v0 = OPERATOR vm->registers.array[src_register_i].u8v0;\
break;\
case 2: \
vm->registers.array[src_register_i].u16v0 = OPERATOR vm->registers.array[src_register_i].u16v0;\
break;\
case 4: \
vm->registers.array[src_register_i].u32v0 = OPERATOR vm->registers.array[src_register_i].u32v0;\
break;\
case 8: \
vm->registers.array[src_register_i].u64v = OPERATOR vm->registers.array[src_register_i].u64v;\
break;\
}\
return sizeof(src_register_i) /*+ sizeof(value_size)*/;\
}
#define logicalOperator2Impl(NAME, OPERATOR)\
i32 NAME##_impl (VM* vm) {\
u8 dst_register_i = 0, src_register_i = 0;\
readRegisterVar(dst_register_i);\
readRegisterVar(src_register_i);\
/*u8 value_size = 0;\
readValueSizeVar(value_size);*/\
u8 value_size = 4;\
\
switch(value_size){\
case 1: \
vm->registers.array[dst_register_i].u8v0 OPERATOR##= vm->registers.array[src_register_i].u8v0;\
break;\
case 2: \
vm->registers.array[dst_register_i].u16v0 OPERATOR##= vm->registers.array[src_register_i].u16v0;\
break;\
case 4: \
vm->registers.array[dst_register_i].u32v0 OPERATOR##= vm->registers.array[src_register_i].u32v0;\
break;\
case 8: \
vm->registers.array[dst_register_i].u64v OPERATOR##= vm->registers.array[src_register_i].u64v;\
break;\
}\
return sizeof(dst_register_i) + sizeof(src_register_i) /*+ sizeof(value_size)*/;\
}
#define logicalOperator3Impl(NAME, OPERATOR)\
i32 NAME##_impl (VM* vm) {\
u8 dst_register_i = 0, src0_register_i = 0, src1_register_i = 0;\
readRegisterVar(dst_register_i);\
readRegisterVar(src0_register_i);\
readRegisterVar(src1_register_i);\
/*u8 value_size = 0;\
readValueSizeVar(value_size);*/\
u8 value_size = 4;\
\
switch(value_size){\
case 1: \
vm->registers.array[dst_register_i].u8v0 = vm->registers.array[src0_register_i].u8v0 OPERATOR vm->registers.array[src1_register_i].u8v0;\
break;\
case 2: \
vm->registers.array[dst_register_i].u16v0 = vm->registers.array[src0_register_i].u16v0 OPERATOR vm->registers.array[src1_register_i].u16v0;\
break;\
case 4: \
vm->registers.array[dst_register_i].u32v0 = vm->registers.array[src0_register_i].u32v0 OPERATOR vm->registers.array[src1_register_i].u32v0;\
break;\
case 8: \
vm->registers.array[dst_register_i].u64v = vm->registers.array[src0_register_i].u64v OPERATOR vm->registers.array[src1_register_i].u64v;\
break;\
}\
return sizeof(dst_register_i) + sizeof(src0_register_i) + sizeof(src1_register_i) /*+ sizeof(value_size)*/;\
}
logicalOperator3Impl(EQ, ==)
logicalOperator3Impl(NE, !=)
logicalOperator3Impl(LT, <)
logicalOperator3Impl(LE, <=)
logicalOperator3Impl(GT, >)
logicalOperator3Impl(GE, >=)
logicalOperator1Impl(NOT, !)
logicalOperator1Impl(INV, ~)
logicalOperator2Impl(OR, |)
logicalOperator2Impl(XOR, ^)
logicalOperator2Impl(AND, &)

View File

@@ -1,6 +1,7 @@
#include "impl_macros.h" #include "impl_macros.h"
#define mathOperatorImpl(OPERATOR){\ #define mathOperator2Impl(NAME, OPERATOR)\
i32 NAME##_impl (VM* vm) {\
u8 dst_register_i = 0, src_register_i = 0;\ u8 dst_register_i = 0, src_register_i = 0;\
readRegisterVar(dst_register_i);\ readRegisterVar(dst_register_i);\
readRegisterVar(src_register_i);\ readRegisterVar(src_register_i);\
@@ -10,39 +11,32 @@
\ \
switch(value_size){\ switch(value_size){\
case 1: \ case 1: \
vm->registers[dst_register_i].u8v0 OPERATOR##= vm->registers[src_register_i].u8v0;\ vm->registers.array[dst_register_i].u8v0 OPERATOR##= vm->registers.array[src_register_i].u8v0;\
break;\ break;\
case 2: \ case 2: \
vm->registers[dst_register_i].u16v0 OPERATOR##= vm->registers[src_register_i].u16v0;\ vm->registers.array[dst_register_i].u16v0 OPERATOR##= vm->registers.array[src_register_i].u16v0;\
break;\ break;\
case 4: \ case 4: \
vm->registers[dst_register_i].u32v OPERATOR##= vm->registers[src_register_i].u32v;\ vm->registers.array[dst_register_i].u32v0 OPERATOR##= vm->registers.array[src_register_i].u32v0;\
break;\
case 8: \
vm->registers.array[dst_register_i].u64v OPERATOR##= vm->registers.array[src_register_i].u64v;\
break;\ break;\
}\ }\
return sizeof(dst_register_i) + sizeof(src_register_i) + sizeof(value_size);\ return sizeof(dst_register_i) + sizeof(src_register_i) /*+ sizeof(value_size)*/;\
} }
/// ADD [dst_register] [src_register] /// ADD [dst_register] [src_register]
i32 ADD_impl(VM* vm){ mathOperator2Impl(ADD, +)
mathOperatorImpl(+);
}
/// SUB [dst_register] [src_register] /// SUB [dst_register] [src_register]
i32 SUB_impl(VM* vm){ mathOperator2Impl(SUB, -)
mathOperatorImpl(-);
}
/// MUL [dst_register] [src_register] /// MUL [dst_register] [src_register]
i32 MUL_impl(VM* vm){ mathOperator2Impl(MUL, *)
mathOperatorImpl(*)
}
/// DIV [dst_register] [src_register] /// DIV [dst_register] [src_register]
i32 DIV_impl(VM* vm){ mathOperator2Impl(DIV, /)
mathOperatorImpl(/)
}
/// MOD [dst_register] [src_register] /// MOD [dst_register] [src_register]
i32 MOD_impl(VM* vm){ mathOperator2Impl(MOD, %)
mathOperatorImpl(%)
}

View File

@@ -2,32 +2,65 @@
#include "../collections/HashMap.h" #include "../collections/HashMap.h"
i32 NOP_impl(VM* vm); i32 NOP_impl(VM* vm);
i32 PUSH_impl(VM* vm); i32 EXIT_impl(VM* vm);
i32 MOV_impl(VM* vm); i32 SYS_impl(VM* vm);
i32 MOVC_impl(VM* vm);
i32 MOVR_impl(VM* vm);
i32 ADD_impl(VM* vm); i32 ADD_impl(VM* vm);
i32 SUB_impl(VM* vm); i32 SUB_impl(VM* vm);
i32 MUL_impl(VM* vm); i32 MUL_impl(VM* vm);
i32 DIV_impl(VM* vm); i32 DIV_impl(VM* vm);
i32 MOD_impl(VM* vm); i32 MOD_impl(VM* vm);
i32 SYS_impl(VM* vm);
i32 EXIT_impl(VM* vm); i32 EQ_impl(VM* vm);
i32 NE_impl(VM* vm);
i32 LT_impl(VM* vm);
i32 LE_impl(VM* vm);
i32 GT_impl(VM* vm);
i32 GE_impl(VM* vm);
i32 NOT_impl(VM* vm);
i32 INV_impl(VM* vm);
i32 OR_impl(VM* vm);
i32 XOR_impl(VM* vm);
i32 AND_impl(VM* vm);
i32 JMP_impl(VM* vm); i32 JMP_impl(VM* vm);
i32 CALL_impl(VM* vm); i32 JNZ_impl(VM* vm);
i32 JZ_impl(VM* vm);
Array_declare(Instruction); Array_declare(Instruction);
static const Array_Instruction instructions_array = ARRAY(Instruction, { static const Array_Instruction instructions_array = ARRAY(Instruction, {
Instruction_construct(NOP), Instruction_construct(NOP),
Instruction_construct(PUSH), Instruction_construct(EXIT),
Instruction_construct(MOV), Instruction_construct(SYS),
Instruction_construct(MOVC),
Instruction_construct(MOVR),
Instruction_construct(ADD), Instruction_construct(ADD),
Instruction_construct(SUB), Instruction_construct(SUB),
Instruction_construct(MUL), Instruction_construct(MUL),
Instruction_construct(DIV), Instruction_construct(DIV),
Instruction_construct(MOD), Instruction_construct(MOD),
Instruction_construct(SYS),
Instruction_construct(EXIT), Instruction_construct(EQ),
// Instruction_construct(JMP), Instruction_construct(NE),
// Instruction_construct(CALL), Instruction_construct(LT),
Instruction_construct(LE),
Instruction_construct(GT),
Instruction_construct(GE),
Instruction_construct(NOT),
Instruction_construct(INV),
Instruction_construct(OR),
Instruction_construct(XOR),
Instruction_construct(AND),
Instruction_construct(JMP),
Instruction_construct(JNZ),
Instruction_construct(JZ),
}); });
const Instruction* Instruction_getByOpcode(Opcode opcode){ const Instruction* Instruction_getByOpcode(Opcode opcode){

View File

@@ -7,15 +7,33 @@ typedef i32 (*InstructionImplFunc_t)(VM* vm);
typedef enum __attribute__((__packed__)) Opcode { typedef enum __attribute__((__packed__)) Opcode {
Opcode_NOP, Opcode_NOP,
Opcode_PUSH, Opcode_EXIT,
Opcode_MOV, Opcode_SYS,
Opcode_MOVC,
Opcode_MOVR,
Opcode_ADD, Opcode_ADD,
Opcode_SUB, Opcode_SUB,
Opcode_MUL, Opcode_MUL,
Opcode_DIV, Opcode_DIV,
Opcode_MOD, Opcode_MOD,
Opcode_SYS,
Opcode_EXIT, Opcode_EQ,
Opcode_NE,
Opcode_LT,
Opcode_LE,
Opcode_GT,
Opcode_GE,
Opcode_NOT,
Opcode_INV,
Opcode_OR,
Opcode_XOR,
Opcode_AND,
Opcode_JMP,
Opcode_JNZ,
Opcode_JZ,
} Opcode; } Opcode;
typedef struct Instruction { typedef struct Instruction {

View File

@@ -2,6 +2,8 @@
#include "instructions/instructions.h" #include "instructions/instructions.h"
#include "collections/List.h" #include "collections/List.h"
#include "compiler/Compiler.h" #include "compiler/Compiler.h"
#include "VM/Display/Display.h"
#include <SDL3/SDL.h>
#define arg_is(STR) (strcmp(argv[argi], STR) == 0) #define arg_is(STR) (strcmp(argv[argi], STR) == 0)

View File

@@ -8,6 +8,7 @@
#include <time.h> #include <time.h>
#include <math.h> #include <math.h>
#include <string.h> #include <string.h>
#include <stdbool.h>
typedef int8_t i8; typedef int8_t i8;
typedef uint8_t u8; typedef uint8_t u8;
@@ -20,10 +21,6 @@ typedef uint64_t u64;
typedef float f32; typedef float f32;
typedef double f64; typedef double f64;
typedef u8 bool;
#define true 1
#define false 0
typedef const char* cstr; typedef const char* cstr;
#if defined(_WIN64) || defined(_WIN32) #if defined(_WIN64) || defined(_WIN32)