Skip to content

Instantly share code, notes, and snippets.

@benaryorg
Last active July 5, 2022 23:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benaryorg/4b5ecd1c298b15fe8cba to your computer and use it in GitHub Desktop.
Save benaryorg/4b5ecd1c298b15fe8cba to your computer and use it in GitHub Desktop.
execute binary file in c
int foo(void)
{
return 666;
}
OUTPUT_FORMAT(binary)
#include <assert.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int fd;
struct stat sb;
void *addr;
assert((fd = open("binary",O_RDONLY)) != -1);
assert(fstat(fd,&sb) != -1);
assert(addr = mmap(NULL,sb.st_size,PROT_EXEC|PROT_READ,MAP_PRIVATE,fd,0));
printf("%d\n",(*((int (**)(void))&addr))());
munmap(addr,sb.st_size);
close(fd);
return 0;
}
CC := cc
LD := ld
CFLAGS := -pedantic -Wall -Werror -Wextra -std=c89 -fno-stack-protector
LDFLAGS :=
default: main binary
all: clean main binary
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $^
main: main.c
$(CC) $(CFLAGS) -o $@ $^
binary: binary.o
$(LD) $(LDFLAGS) -o $@ -T linker.ld $^
run: main binary
./main
clean:
rm -f main binary binary.o
.PHONY: clean run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment