orccodemem.c 2.06 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 19
#ifdef HAVE_CODEMEM_VIRTUALALLOC
#include <windows.h>
#endif
20 21

#include <orc/orcprogram.h>
22
#include <orc/orcdebug.h>
23

24

25 26 27
#define SIZE 65536


28
#ifdef HAVE_CODEMEM_MMAP
29
void
30
orc_compiler_allocate_codemem (OrcCompiler *compiler)
31 32
{
  int fd;
33
  int n;
34

35 36 37
  {
    char *filename;

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

51
  n = ftruncate (fd, SIZE);
52

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

  close (fd);

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

71
#ifdef HAVE_CODEMEM_VIRTUALALLOC
72
void
73
orc_compiler_allocate_codemem (OrcCompiler *compiler)
74
{
75 76 77 78 79 80
  compiler->program->code = VirtualAlloc(NULL, SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  compiler->program->code_exec = compiler->program->code;
  compiler->program->code_size = SIZE;
  compiler->codeptr = compiler->program->code;
}
#endif
81

82 83 84 85
#ifdef HAVE_CODEMEM_MALLOC
void
orc_compiler_allocate_codemem (OrcCompiler *compiler)
{
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