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

#include "config.h"

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

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

#include <orc/orcprogram.h>
19
#include <orc/orcdebug.h>
20

21

22 23 24
#define SIZE 65536


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

32 33 34
  {
    char *filename;

35 36 37 38
    filename = malloc (strlen ("/tmp/orcexec..") +
        strlen (compiler->program->name) + 6 + 1);
    sprintf(filename, "/tmp/orcexec.%s.XXXXXX", compiler->program->name);
    fd = mkstemp (filename);
39 40 41 42 43 44 45 46
    if (fd == -1) {
      /* FIXME oh crap */
      ORC_COMPILER_ERROR (compiler, "failed to create temp file");
      return;
    }
    unlink (filename);
    free (filename);
  }
47

48
  n = ftruncate (fd, SIZE);
49

50 51
  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
52
    ORC_COMPILER_ERROR(compiler, "failed to create write map");
53 54
    return;
  }
55 56
  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
57
    ORC_COMPILER_ERROR(compiler, "failed to create exec map");
58 59 60 61 62
    return;
  }

  close (fd);

63 64
  compiler->program->code_size = SIZE;
  compiler->codeptr = compiler->program->code;
65
}
66 67 68 69
#endif

#ifdef HAVE_CODEMEM_MALLOC
void
70
orc_compiler_allocate_codemem (OrcCompiler *compiler)
71 72 73
{
  /* Now you know why Windows has viruses */

74
  compiler->program->code = malloc(SIZE);
David Schleef's avatar
David Schleef committed
75
  compiler->program->code_exec = compiler->program->code;
76 77
  compiler->program->code_size = SIZE;
  compiler->codeptr = compiler->program->code;
78 79
}
#endif
80