Skip to content

Instantly share code, notes, and snippets.

@tomtzook
Created January 16, 2021 09:50
Show Gist options
  • Save tomtzook/2b2b98448682baeb617c81934d48c681 to your computer and use it in GitHub Desktop.
Save tomtzook/2b2b98448682baeb617c81934d48c681 to your computer and use it in GitHub Desktop.
Compiling C EFI application with Make and GNU-EFI, and running in QEMU
#include <efi.h>
#include <efilib.h>
EFI_STATUS EFIAPI
efi_main (EFI_HANDLE image_handle, EFI_SYSTEM_TABLE* system_table)
{
InitializeLib(image_handle, system_table);
Print(L"Hello from the UEFI\n");
return EFI_SUCCESS;
}
ARCH=x86_64
OBJS=main.o
TARGET=main.efi
CC=gcc
EFI_INCLUDE_PATH=/usr/local/include/efi
EFI_INCLUDES=-I$(EFI_INCLUDE_PATH) -I$(EFI_INCLUDE_PATH)/$(ARCH) -I$(EFI_INCLUDE_PATH)/protocol
CFLAGS=$(EFI_INCLUDES) -fno-stack-protector -fpic \
-fshort-wchar -mno-red-zone -Wall -DEFI_FUNCTION_WRAPPER
LIB_PATH=/usr/local/lib
EFI_LIB_PATH=/usr/local/lib/
EFI_CRT_OBJS=$(EFI_LIB_PATH)/crt0-efi-$(ARCH).o
EFI_LDS=$(EFI_LIB_PATH)/elf_$(ARCH)_efi.lds
LDFLAGS=-nostdlib -znocombreloc -T $(EFI_LDS) -shared \
-Bsymbolic -L $(EFI_LIB_PATH) -L $(LIB_PATH) $(EFI_CRT_OBJS)
all: $(TARGET)
main.so: $(OBJS)
ld $(LDFLAGS) $(OBJS) -o $@ -lefi -lgnuefi
%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS)
%.efi: %.so
objcopy -j .text -j .sdata -j .data -j .dynamic \
-j .dynsym -j .rel -j .rela -j .reloc \
--target=efi-app-$(ARCH) $^ $@
clean:
rm *.so *.o *.efi
#!/bin/bash
RUN_PATH=build/qemu
OVMF_DISK_IMG=/usr/share/ovmf/OVMF.fd
BINARY_PATH=main.efi
DISK_PATH=${RUN_PATH}/uefi.img
# clean previous
make clean
# build
make
# make image
mkdir -p ${RUN_PATH}
## prepare disk image
## prepare files for efi partition (application binary + startup script)
dd if=/dev/zero of=/tmp/part.img bs=512 count=91669
mformat -i /tmp/part.img -h 32 -t 32 -n 64 -c 1
mcopy -i /tmp/part.img ${BINARY_PATH} ::app.efi
echo app.efi > startup.nsh
mcopy -i /tmp/part.img startup.nsh ::/
## make full image (with format and efi partition)
dd if=/dev/zero of=${DISK_PATH} bs=512 count=93750
parted ${DISK_PATH} -s -a minimal mklabel gpt
parted ${DISK_PATH} -s -a minimal mkpart EFI FAT16 2048s 93716s
parted ${DISK_PATH} -s -a minimal toggle 1 boot
## copy files into the image
dd if=/tmp/part.img of=${DISK_PATH} bs=512 count=91669 seek=2048 conv=notrunc
# run
qemu-system-x86_64 \
-cpu qemu64 \
-enable-kvm \
-net none \
-drive if=pflash,format=raw,unit=0,file=${OVMF_DISK_IMG},readonly=on \
-drive if=ide,format=raw,file=${DISK_PATH}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment