#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <limits.h>
#include <errno.h>
#include <malloc.h>
#include <unistd.h>
#include <string.h>
#ifndef PAGE_SIZE
#  define PAGE_SIZE getpagesize()
#endif
#
/* test for exec privs */

/*
 * c equiv:
  int t() {
  return 1;
}
*/

char code[] = {
   0xB8,0x01,0,0,0,      /* movl $1, %eax */
   0xC3                  /* ret */
};

typedef int (*pf)(void);

int main(int argc, char *argv[])
{
    pf t;
    char *p;
    int rc;
    int prot = PROT_READ;

    if (argc != 2) {
        fprintf(stderr, "usage: test 0 | 1\n");
        exit(1);
    }

    if (atoi(argv[1]))
        prot |= PROT_EXEC;

    p = memalign(PAGE_SIZE, PAGE_SIZE);
    memcpy(p, code, sizeof(code));

    t  = (pf) p;
    rc = mprotect(p, PAGE_SIZE, prot);

    if (rc) {
        fprintf(stderr, "p = %p  PAGE_SIZE = %d (0x%x)\n", p,
            PAGE_SIZE, PAGE_SIZE);
        perror("failure");
    }

    if (t() == 1)
        puts("ok");

    else
        return 1;

    return 0;
}
