Skip to content

Performance comparison: Function pointers in memory-protected global struct #19

@robertdfrench

Description

@robertdfrench

from @nekopsykose

#include <err.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>

struct myfuncs {
  unsigned (*multiply)(unsigned, unsigned);
};

static struct myfuncs *page;


unsigned multiply_base(unsigned x, unsigned y) {
  return x * y;
}

unsigned multiply_sse42(unsigned x, unsigned y) {
  return x + y; /* lol */
}

void initfuncs(void) {
  int pagesize = getpagesize();
  page = mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0);

  if (page == MAP_FAILED)
    err(123, "mmap");
  

  /* magical runtime check */
  if (0) {
    page->multiply = multiply_sse42;
  } else {
    page->multiply = multiply_base;
  }

  if(mprotect(page, pagesize, PROT_READ))
    err(123, "mprotect");


  /* segfaults */
  // page->multiply = multiply_sse42;
}


int main(void) {
  initfuncs();

  unsigned x = page->multiply(4, 4);

  printf("%u\n", x);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions