Skip to content

Instantly share code, notes, and snippets.

@Nephos
Created July 28, 2017 15:10
Show Gist options
  • Save Nephos/8b3f1b6e00157d68366218eaf774c8f1 to your computer and use it in GitHub Desktop.
Save Nephos/8b3f1b6e00157d68366218eaf774c8f1 to your computer and use it in GitHub Desktop.
#include <dirent.h>
#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
/* Open the .so */
int file_fd = open("module.so", O_RDONLY, O_RDONLY);
if (file_fd < 0) {
perror("open");
return 10;
}
printf("Open module.so: %i\n", file_fd);
/* Get the siez of the .so */
int file_size = lseek(file_fd, 0, SEEK_END);
printf("File size: %i\n", file_size);
lseek(file_fd, 0, SEEK_SET);
/* Allocate a buffer */
char *buffer = malloc(file_size);
if (buffer == NULL) {
perror("malloc");
return 20;
}
/* Open the shm_file to write on */
int shm_fd = shm_open("shm_module.so", O_RDWR | O_CREAT, 0644);
if (shm_fd < 0) {
perror("shm_open");
return 4;
}
printf("Open shm module.so: %i\n", shm_fd);
/* Read the .so to the buffer and Write the buffer to the shm */
int read_size = read(file_fd, buffer, file_size);
printf("Read size: %i\n", read_size);
int write_size = write(shm_fd, buffer, file_size);
printf("Write size: %i\n", write_size);
/* Free the buffer */
free(buffer);
/* Close the file */
close(file_fd);
/* Prepare the shm .so to be read */
#define shm_path_size sizeof("/proc/self/fd/65536")
char shm_path[shm_path_size] = {0};
snprintf(shm_path, shm_path_size, "/proc/self/fd/%i", shm_fd);
printf("shm path: %s\n", shm_path);
/* Load the .so */
void *module_so = dlopen(shm_path, RTLD_NOW);
if (module_so == NULL) {
perror("dlopen");
return 1;
}
int (*module_run)(int*) = dlsym(module_so, "run");
if (module_run == NULL) {
perror("dlsym");
return 2;
}
/* Execute some sym from the .so */
int var = 4;
module_run(&var);
printf("var = %i\n", var);
/* remove the shm */
if (shm_unlink("shm_module.so") < 0) {
perror("shm_error");
return 5;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment