common and ocpu: Implemented stack, added PUSH and POP instructions

This commit is contained in:
g1n 2022-05-10 17:28:29 +03:00
parent 055f16d956
commit ae8ba5d80b
Signed by: g1n
GPG Key ID: 8D352193D65D4E2C
4 changed files with 65 additions and 0 deletions

View File

@ -61,6 +61,8 @@
#define INS_NAND_REG 0xC5
#define INS_CMP_IM 0x26
#define INS_CMP_REG 0xC6
#define INS_PUSH_IM 0x30
#define INS_POP 0x31
#define INS_OCPU_NOP 0x90
#define INS_OCPU_SEC 0x61
#define INS_OCPU_CLC 0x62

10
src/include/yemu/stack.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef YEMU_STACK_H
#define YEMU_STACK_H
typedef int stack_t;
int get_last_item_from_stack();
int pop();
void push(int value);
#endif

View File

@ -1,8 +1,13 @@
#include <yemu/ocpu.h>
#include <yemu/stack.h>
#include <stdbool.h>
#include <stdlib.h>
struct OCPU ocpu;
struct OCPU_MEMORY ocpu_mem;
int stack_size = 64000;
stack_t *stack;
byte *sp;
void ocpu_memory_init () {
for (int i = 0; i < MAX_MEMORY; i++){
@ -448,6 +453,13 @@ void ocpu_execute() {
ocpu.CF = 0;
}
break;
case INS_PUSH_IM:
push(ocpu_fetch_byte());
printf("STACK: push 0x%x to stack address 0x%x\n", get_last_item_from_stack(), ocpu.SP);
break;
case INS_POP:
printf("STACK: pop 0x%x from stack address 0x%x\n", pop(), ocpu.SP);
break;
case INS_OCPU_NOP:
break;
case INS_OCPU_SEC:
@ -469,6 +481,9 @@ void initOCPU(FILE *infile) {
ocpu_reset();
int ch;
int pos = 0;
stack = malloc(stack_size*sizeof(byte));
ocpu.SP = 0;
sp = &ocpu.SP;
while (1) { // FIXME
ch = fgetc(infile);
if (ch == EOF)
@ -479,5 +494,6 @@ void initOCPU(FILE *infile) {
ocpu_execute();
ocpu_dump_ocpu(ocpu);
free(stack);
return;
}

37
src/stack.c Normal file
View File

@ -0,0 +1,37 @@
#include <yemu/stack.h>
#include <yemu/common.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
extern stack_t *stack;
extern unsigned int stack_size;
extern byte *sp;
int get_last_item_from_stack() {
if ((int)(*sp) <= 0) {
printf("Stack Underflow\n");
return -1;
}
return stack[(*sp)];
}
void push(int value) {
if (*sp >= stack_size-1) {
printf("Stack Overflow\n");
} else {
(*sp)++;
stack[*sp] = value;
}
}
int pop() {
int value = -1;
if ((int)(*sp) <= 0) {
printf("Stack Underflow\n");
} else {
value = stack[*sp];
(*sp)--;
}
return value;
}