Skip to content

Commit

Permalink
fix: shmoverride hooks in presence of other constructors calling fstat
Browse files Browse the repository at this point in the history
  • Loading branch information
CertainLach committed Sep 30, 2024
1 parent 9966538 commit e7d4a0c
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions shmoverride/shmoverride.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ static int (*real_munmap) (void *shmaddr, size_t len);
static int (*real_fstat64) (VER_ARG int fd, struct stat64 *buf);
static int (*real_fstat)(VER_ARG int fd, struct stat *buf);

static int try_init(void);

static struct stat global_buf;
static int gntdev_fd = -1;

Expand All @@ -84,7 +86,7 @@ static int xc_hnd;
static xengnttab_handle *xgt;
static char __shmid_filename[SHMID_FILENAME_LEN];
static char *shmid_filename = NULL;
static int idfd = -1, display = -1;
static int idfd = -1, display = -1, init_called = 0;

static uint8_t *mmap_mfns(struct shm_args_hdr *shm_args) {
uint8_t *map;
Expand Down Expand Up @@ -151,6 +153,8 @@ ASM_DEF(void *, mmap,
real_fstat = FSTAT;
}

try_init();

#if defined MAP_ANON && defined MAP_ANONYMOUS && (MAP_ANONYMOUS) != (MAP_ANON)
# error header bug (def mismatch)
#endif
Expand Down Expand Up @@ -217,6 +221,9 @@ ASM_DEF(int, munmap, void *addr, size_t len)
{
if (len > SIZE_MAX - XC_PAGE_SIZE)
abort();

try_init();

const uintptr_t addr_int = (uintptr_t)addr;
const uintptr_t rounded_addr = addr_int & ~(uintptr_t)(XC_PAGE_SIZE - 1);
return real_munmap((void *)rounded_addr, len + (addr_int - rounded_addr));
Expand Down Expand Up @@ -438,6 +445,7 @@ static int assign_off(off_t *off) {

#define STAT(id) \
ASM_DEF(int, f ## id, int filedes, struct id *buf) { \
try_init(); \
int res = real_f ## id(VER filedes, buf); \
if (res || \
!S_ISCHR(buf->st_mode) || \
Expand All @@ -454,6 +462,7 @@ STAT(stat64)
#ifdef _STAT_VER
#define STAT(id) \
ASM_DEF(int, __fx ## id, int ver, int filedes, struct id *buf) { \
try_init(); \
if (ver != _STAT_VER) { \
fprintf(stderr, \
"Wrong _STAT_VER: got %d, expected %d, libc has incompatibly changed\n", \
Expand All @@ -467,8 +476,13 @@ STAT(stat64)
#undef STAT
#endif

int __attribute__ ((constructor)) initfunc(void)
static int try_init(void)
{
// Ideally it is being called in constructor, if something is calling this before
// constructor - we're assuming it is not multi-threaded code.
if (__builtin_expect(init_called, 1)) return 0;
init_called = 1;

unsetenv("LD_PRELOAD");
fprintf(stderr, "shmoverride constructor running\n");
dlerror();
Expand Down Expand Up @@ -581,6 +595,10 @@ int __attribute__ ((constructor)) initfunc(void)
shm_args = NULL;
return 0;
}
int __attribute__ ((constructor)) initfunc(void)
{
return try_init();
}

int __attribute__ ((destructor)) descfunc(void)
{
Expand Down

0 comments on commit e7d4a0c

Please sign in to comment.