summaryrefslogtreecommitdiff
path: root/src/alloc.c
blob: 7e4ccb440ed834ba5c938675e2ee8257e0c7ab9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "alloc.h"

#include <errno.h>
#include <limits.h>
#include <stdlib.h>

#include "byte.h"

#define ALIGNMENT 16   /* XXX: assuming that this alignment is enough */
#define SPACE     4096 /* must be multiple of ALIGNMENT */

typedef union {
  char irrelevant[ALIGNMENT];
  double d;
} aligned;
static aligned realspace[SPACE / ALIGNMENT];
#define space ((char *)realspace)
static unsigned int avail = SPACE; /* multiple of ALIGNMENT; 0<=avail<=SPACE */

void *alloc(unsigned int n)
{
  char *x;

  /* Guninski exploit + patch from Qualys (CVE-2005-1513) */

  if (n >= (INT_MAX >> 3)) {
    errno = ENOMEM;
    return 0;
  }

  n = ALIGNMENT + n - (n & (ALIGNMENT - 1)); /* XXX: could overflow */
  if (n <= avail) {
    avail -= n;
    return space + avail;
  }
  x = malloc(n);
  if (!x) errno = ENOMEM;
  return x;
}

void alloc_free(void *x)
{
  if (x >= space)
    if (x < space + SPACE) return; /* XXX: assuming that pointers are flat */
  free(x);
}

int alloc_re(void *a, unsigned int m, unsigned int n)
{
  char **x = a;
  char *y;

  y = alloc(n);
  if (!y) return 0;
  byte_copy(y, m, *x);
  qfree(*x);
  *x = y;
  return 1;
}