Skip to content

Instantly share code, notes, and snippets.

@alex-pat
Last active June 6, 2018 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-pat/22f9f2d4a797906aaa7efc45cc46545d to your computer and use it in GitHub Desktop.
Save alex-pat/22f9f2d4a797906aaa7efc45cc46545d to your computer and use it in GitHub Desktop.
library call from scratch
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
long filepid()
{
long (*func)() = NULL;
long ret;
int fd = open("lib.hex", O_RDONLY);
if (fd == -1) {
perror("open");
return -1;
}
func = mmap(NULL, 21, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
if (func == MAP_FAILED) {
perror("mmap");
return -1;
}
if (close(fd) == -1) {
perror("close");
return -1;
}
ret = func();
if (munmap(func, 21) == -1) {
perror("munmap");
return -1;
}
return ret;
}
int main()
{
assert(getpid() == filepid());
puts("Correct");
return 0;
}
@alex-pat
Copy link
Author

alex-pat commented Jun 6, 2018

$ hexdump lib.hex 
0000000 4855 e589 27b8 0000 0f00 4805 4589 48f8
0000010 458b 5df8 00c3                         
0000015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment