orccodemem.c 2 KB
Newer Older
1 2 3 4 5 6 7 8 9

#include "config.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
10 11
#include <sys/stat.h>
#include <fcntl.h>
David Schleef's avatar
David Schleef committed
12
#ifdef HAVE_CODEMEM_MMAP
13
#include <sys/mman.h>
David Schleef's avatar
David Schleef committed
14
#endif
15 16

#include <orc/orcprogram.h>
17
#include <orc/orcdebug.h>
18

19

20 21 22
#define SIZE 65536


23
#ifdef HAVE_CODEMEM_MMAP
24
void
25
orc_compiler_allocate_codemem (OrcCompiler *compiler)
26 27
{
  int fd;
28
  int n;
29

30 31 32 33 34 35 36 37 38 39 40
  /* FIXME something combining these two would be ideal */
#if 1
  {
    char filename[32] = "/tmp/orcexecXXXXXX";
    fd = mkstemp (filename);
    if (fd == -1) {
      /* FIXME oh crap */
      ORC_COMPILER_ERROR (compiler, "failed to create temp file");
      return;
    }
    unlink (filename);
41
  }
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#else
  {
    char *filename;

    filename = malloc (strlen ("/tmp/orcexec") +
        strlen (compiler->program->name) + 1);
    sprintf(filename, "/tmp/orcexec%s", compiler->program->name);
    fd = open (filename, O_RDWR | O_CREAT, S_IRWXU);
    if (fd == -1) {
      /* FIXME oh crap */
      ORC_COMPILER_ERROR (compiler, "failed to create temp file");
      return;
    }
    unlink (filename);
    free (filename);
  }
#endif
59

60
  n = ftruncate (fd, SIZE);
61

62 63
  compiler->program->code = mmap (NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  if (compiler->program->code == MAP_FAILED) {
David Schleef's avatar
David Schleef committed
64
    ORC_COMPILER_ERROR(compiler, "failed to create write map");
65 66
    return;
  }
67 68
  compiler->program->code_exec = mmap (NULL, SIZE, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
  if (compiler->program->code_exec == MAP_FAILED) {
David Schleef's avatar
David Schleef committed
69
    ORC_COMPILER_ERROR(compiler, "failed to create exec map");
70 71 72 73 74
    return;
  }

  close (fd);

75 76
  compiler->program->code_size = SIZE;
  compiler->codeptr = compiler->program->code;
77
}
78 79 80 81
#endif

#ifdef HAVE_CODEMEM_MALLOC
void
82
orc_compiler_allocate_codemem (OrcCompiler *compiler)
83 84 85
{
  /* Now you know why Windows has viruses */

86
  compiler->program->code = malloc(SIZE);
David Schleef's avatar
David Schleef committed
87
  compiler->program->code_exec = compiler->program->code;
88 89
  compiler->program->code_size = SIZE;
  compiler->codeptr = compiler->program->code;
90 91
}
#endif
92