orccodemem.c 2.03 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 35 36 37 38 39 40 41 42
  /* 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);
43
  }
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#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
61

62
  n = ftruncate (fd, SIZE);
63

64 65
  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
66
    ORC_COMPILER_ERROR(compiler, "failed to create write map");
67 68
    return;
  }
69 70
  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
71
    ORC_COMPILER_ERROR(compiler, "failed to create exec map");
72 73 74 75 76
    return;
  }

  close (fd);

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

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

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