Skip to content

Commit

Permalink
Add printVal() hypercall
Browse files Browse the repository at this point in the history
  • Loading branch information
cw00h committed Jan 26, 2023
1 parent df9f147 commit ab50a51
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 10 deletions.
2 changes: 2 additions & 0 deletions defs.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#define PORT_PRINT_CHAR 0xE9
#define PORT_PRINT_VALUE 0xEA
18 changes: 14 additions & 4 deletions guest.c
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
#include <stddef.h>
#include <stdint.h>
#include "defs.h"

static void outb(uint16_t port, uint8_t value) {
asm("outb %0,%1" : /* empty */ : "a" (value), "Nd" (port) : "memory");
static inline void outb(uint16_t port, uint32_t value) {
asm("out %0,%1" : /* empty */ : "a" (value), "Nd" (port) : "memory");
}

void printVal(uint32_t val) {
outb(PORT_PRINT_VALUE, val);
}

void
Expand All @@ -11,11 +16,16 @@ __attribute__((section(".start")))
_start(void) {
const char *p;

/* Print Hello world */
for (p = "Hello, world!\n"; *p; ++p)
outb(0xE9, *p);
outb(PORT_PRINT_CHAR, *p);

*(long *) 0x400 = 42;
/* Test printVal() */
printVal(0x1234);
outb(PORT_PRINT_CHAR, '\n');

/* Halt after setting 0x400 & rax as 42 */
*(long *) 0x400 = 42;
for (;;)
asm("hlt" : /* empty */ : "a" (42) : "memory");
}
22 changes: 16 additions & 6 deletions kvm-hello-world.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <string.h>
#include <stdint.h>
#include <linux/kvm.h>
#include "defs.h"

/* CR0 bits */
#define CR0_PE 1u
Expand Down Expand Up @@ -164,17 +165,26 @@ int run_vm(struct vm *vm, struct vcpu *vcpu, size_t sz)
exit(1);
}

// Guest exited.

switch (vcpu->kvm_run->exit_reason) {
case KVM_EXIT_HLT:
goto check;

case KVM_EXIT_IO:
if (vcpu->kvm_run->io.direction == KVM_EXIT_IO_OUT
&& vcpu->kvm_run->io.port == 0xE9) {
char *p = (char *)vcpu->kvm_run;
fwrite(p + vcpu->kvm_run->io.data_offset,
vcpu->kvm_run->io.size, 1, stdout);
fflush(stdout);
if(vcpu->kvm_run->io.direction == KVM_EXIT_IO_OUT) {
char *p = (char *)vcpu->kvm_run + vcpu->kvm_run->io.data_offset;
switch(vcpu->kvm_run->io.port) {
case PORT_PRINT_CHAR:
fwrite(p, vcpu->kvm_run->io.size, 1, stdout);
fflush(stdout);
break;

case PORT_PRINT_VALUE:
printf("%d", *((uint32_t *)p));
fflush(stdout);
break;
}
continue;
}

Expand Down

0 comments on commit ab50a51

Please sign in to comment.