java-llvm/instruction.c

65 lines
1.5 KiB
C
Raw Normal View History

2024-05-16 17:01:49 +00:00
#include "instruction.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "classfile.h"
Instruction* Instruction_parse(uint32_t bytes_length, uint8_t* bytes) {
Instruction* start = (Instruction*)malloc(sizeof(Instruction));
Instruction* current = start;
u4 i = 0, n = 0;
while (i < bytes_length) {
current->opcode = bytes[i++];
switch (current->opcode) {
case ALOAD_0:
case RETURN:
current->operands = NULL;
break;
case LDC:
*(u1*)&current->operands = bytes[i++];
break;
case GETSTATIC:
case INVOKESPECIAL:
case INVOKEVIRTUAL:
// current->operands = malloc(sizeof(u2));
*(u2*)&current->operands = (*(u2*)&bytes[i] << 8) | bytes[i + 1];
i += 2;
break;
}
if (i < bytes_length) {
current->next = (Instruction*)malloc(sizeof(Instruction));
current = current->next;
} else {
current->next = NULL;
}
}
return start;
}
void Instruction_print_code(Instruction* code) {
u4 i = 0;
while (code) {
printf("\t\t%hx ", (u1)code[i].opcode);
switch (code[i].opcode) {
case ALOAD_0:
case RETURN:
putchar('\n');
break;
case LDC:
printf("#%hhu\n", *(u1*)&code[i].operands);
break;
case GETSTATIC:
case INVOKESPECIAL:
case INVOKEVIRTUAL:
printf("#%hu\n", *(u2*)&code[i].operands);
break;
}
code = code->next;
}
}