-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.c
108 lines (86 loc) · 1.87 KB
/
memory.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* This file is part of John the Ripper password cracker,
* Copyright (c) 1996-98,2010,2012,2016 by Solar Designer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "arch.h"
#include "misc.h"
#include "memory.h"
unsigned int mem_saving_level = 0;
void *mem_alloc(size_t size)
{
void *res;
if (!size)
return NULL;
if (!(res = malloc(size))) {
fprintf(stderr, "malloc: %s\n", strerror(ENOMEM));
error();
}
return res;
}
void *mem_calloc(size_t nmemb, size_t size)
{
void *res;
if (!nmemb || !size)
return NULL;
if (!(res = calloc(nmemb, size))) {
fprintf(stderr, "calloc: %s\n", strerror(ENOMEM));
error();
}
return res;
}
void *mem_alloc_tiny(size_t size, size_t align)
{
static char *buffer = NULL;
static size_t bufree = 0;
size_t mask;
char *p;
#if ARCH_ALLOWS_UNALIGNED
if (mem_saving_level > 2)
align = MEM_ALIGN_NONE;
#endif
mask = align - 1;
do {
if (buffer) {
size_t need =
size + mask - (((size_t)buffer + mask) & mask);
if (bufree >= need) {
p = buffer;
p += mask;
p -= (size_t)p & mask;
bufree -= need;
buffer = p + size;
return p;
}
}
if (size + mask > MEM_ALLOC_SIZE ||
bufree > MEM_ALLOC_MAX_WASTE)
break;
buffer = mem_alloc(MEM_ALLOC_SIZE);
bufree = MEM_ALLOC_SIZE;
} while (1);
p = mem_alloc(size + mask);
p += mask;
p -= (size_t)p & mask;
return p;
}
void *mem_alloc_copy(const void *src, size_t size, size_t align)
{
return memcpy(mem_alloc_tiny(size, align), src, size);
}
char *str_alloc_copy(const char *src)
{
size_t size;
if (!src) return "";
if (!*src) return "";
size = strlen(src) + 1;
return (char *)memcpy(mem_alloc_tiny(size, MEM_ALIGN_NONE), src, size);
}