forked from komh/ksoftseq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmalloc.c
137 lines (105 loc) · 2.67 KB
/
malloc.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/****************************************************************************
**
** malloc.c
**
** Copyright (C) 2020 by KO Myung-Hun <[email protected]>
**
** This file is part of K Soft Sequencer.
**
** $BEGIN_LICENSE$
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
**
** $END_LICENSE$
**
****************************************************************************/
#define INCL_DOS
#include <os2.h>
#include <string.h>
#include <emx/umalloc.h>
#include "mcdtemp.h"
#define MIN_OF_DOSALLOCMEM ( 64 * 1024 )
struct PTRINFO
{
void *magic;
size_t size;
};
void *malloc(size_t size)
{
struct PTRINFO *p;
if (size < MIN_OF_DOSALLOCMEM)
p = _hmalloc(size + sizeof(*p));
else
{
if (DosAllocMem((PPVOID)&p, size + sizeof(*p),
fPERM | PAG_COMMIT | OBJ_ANY))
p = NULL;
LOG_MSG(2, "DosAllocMem(%d) = %p", size, p + 1);
}
if (p)
{
p->magic = size < MIN_OF_DOSALLOCMEM ?
(void *)_hmalloc : (void *)DosAllocMem;
p->size = size;
return p + 1;
}
return NULL;
}
void *calloc(size_t elements, size_t size)
{
void *p = malloc(elements * size);
if (p)
memset(p, 0, elements * size);
return p;
}
void *_std_realloc(void *, size_t);
void *realloc(void *mem, size_t size)
{
if (!mem)
return malloc(size);
if (mem && !size)
{
free(mem);
return NULL;
}
struct PTRINFO *p = mem;
p--;
/*
* If memory block was not allocated by _hmalloc() nor DosAllocMem(),
* use _std_realloc() because it's not possible to know size of mem.
*/
if (p->magic != _hmalloc && p->magic != DosAllocMem)
return _std_realloc(mem, size);
void *newMem = malloc(size);
if (!newMem)
return NULL;
if (size > p->size)
size = p->size;
memcpy(newMem, mem, size);
free(mem);
return newMem;
}
void _std_free(void *);
void free(void *mem)
{
if (!mem)
return;
struct PTRINFO *p = mem;
p--;
if (p->magic == _hmalloc)
_std_free(p);
else if (p->magic == DosAllocMem)
{
int size = p->size;
LOG_MSG(2, "DosFreeMem(%p, %d) = %ld", mem, size, DosFreeMem(p));
}
else
_std_free(mem);
}