add linux dlsym hook

This commit is contained in:
king
2024-08-10 12:24:02 +00:00
parent 55a71164b7
commit 8400493329
3 changed files with 170 additions and 1 deletions

79
test_so/posix.c Executable file
View File

@@ -0,0 +1,79 @@
// hook -->
// open
// write
// read
// close
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
typedef int (*open_t)(const char *pathname, int flags);
open_t open_f = NULL;
typedef ssize_t (*read_t)(int fd, void *buf, size_t count);
read_t read_f = NULL;
typedef ssize_t (*write_t)(int fd, const void *buf, size_t count);
write_t write_f = NULL;
typedef int (*close_t)(int fd);
close_t close_f = NULL;
int open(const char *pathname, int flags) {
if (open_f == NULL) {
open_f = dlsym(RTLD_NEXT, "open");
}
printf("open .. %s\n", pathname);
return open_f(pathname, flags);
}
ssize_t read(int fd, void *buf, size_t count) {
if (read_f == NULL) {
read_f = dlsym(RTLD_NEXT, "read");
}
printf("read ..\n");
return read_f(fd, buf, count);
}
ssize_t write(int fd, const void *buf, size_t count) {
if (write_f == NULL) {
write_f = dlsym(RTLD_NEXT, "write");
}
printf("write ..\n");
return write_f(fd, buf, count);
}
int close(int fd) {
if (close_f == NULL) {
close_f = dlsym(RTLD_NEXT, "close");
}
printf("close ..\n");
return close_f(fd);
}

29
test_so/test_so.c Executable file
View File

@@ -0,0 +1,29 @@
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// posix
int main() {
int fd = open("a.txt", O_CREAT | O_RDWR);
char *buffer = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
write(fd, buffer, strlen(buffer));
char rbuffer[128] = {0};
read(fd, buffer, 128);
printf("rbuffer: %s\n", buffer);
close(fd);
}

View File

@@ -255,12 +255,73 @@ int main(int argc, char *argv[]) {
}
#else
typedef int (*open_t)(const char *pathname, int flags);
open_t open_f = NULL;
typedef ssize_t (*read_t)(int fd, void *buf, size_t count);
read_t read_f = NULL;
typedef ssize_t (*write_t)(int fd, const void *buf, size_t count);
write_t write_f = NULL;
typedef int (*close_t)(int fd);
close_t close_f = NULL;
int open(const char *pathname, int flags) {
if (open_f == NULL) {
open_f = dlsym(RTLD_NEXT, "open");
}
printf("open .. %s\n", pathname);
return open_f(pathname, flags);
}
ssize_t read(int fd, void *buf, size_t count) {
if (read_f == NULL) {
read_f = dlsym(RTLD_NEXT, "read");
}
printf("read ..\n");
return read_f(fd, buf, count);
}
ssize_t write(int fd, const void *buf, size_t count) {
if (write_f == NULL) {
write_f = dlsym(RTLD_NEXT, "write");
}
printf("write ..\n");
return write_f(fd, buf, count);
}
int close(int fd) {
if (close_f == NULL) {
close_f = dlsym(RTLD_NEXT, "close");
}
printf("close ..\n");
return close_f(fd);
}
// posix
int main() {
int fd = open("a.txt", O_CREAT | O_READ);
int fd = open("a.txt", O_CREAT | O_RDWR);
char *buffer = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";