1 | /**
|
---|
2 | * @file memory.cpp
|
---|
3 | * @author myusgun@gmail.com
|
---|
4 | * @brief memory
|
---|
5 | */
|
---|
6 | #include "cf/memory.h"
|
---|
7 |
|
---|
8 | #include <stdio.h>
|
---|
9 | #include <stdlib.h>
|
---|
10 | #include <string.h>
|
---|
11 |
|
---|
12 | static const cf::uint8_t gVerifier[4] = {0xcf, '+', '+', 0x00};
|
---|
13 |
|
---|
14 | cf::memory::memory(const cf::size_t size)
|
---|
15 | throw (cf::exception)
|
---|
16 | : mMemory(NULL)
|
---|
17 | {
|
---|
18 | mMemory = cf::memory::alloc(size);
|
---|
19 | }
|
---|
20 |
|
---|
21 | cf::memory::~memory()
|
---|
22 | {
|
---|
23 | cf::memory::free(mMemory);
|
---|
24 | mMemory = NULL;
|
---|
25 | }
|
---|
26 |
|
---|
27 | cf::void_t * cf::memory::buffer()
|
---|
28 | {
|
---|
29 | return mMemory;
|
---|
30 | }
|
---|
31 |
|
---|
32 | cf::void_t * cf::memory::alloc(const cf::size_t size)
|
---|
33 | throw (cf::exception)
|
---|
34 | {
|
---|
35 | cf::uint8_t * mem = (cf::uint8_t *)::calloc(size + sizeof(gVerifier), 1);
|
---|
36 | if (!mem)
|
---|
37 | THROW_EXCEPTION("cannot allocate memory");
|
---|
38 |
|
---|
39 | ::memcpy(mem, gVerifier, sizeof(gVerifier));
|
---|
40 |
|
---|
41 | return reinterpret_cast<cf::void_t *>(mem + sizeof(gVerifier));
|
---|
42 | }
|
---|
43 |
|
---|
44 | cf::void_t cf::memory::free(cf::void_t * mem)
|
---|
45 | throw (cf::exception)
|
---|
46 | {
|
---|
47 | if (!valid(mem))
|
---|
48 | THROW_EXCEPTION("invalid address or verification code");
|
---|
49 |
|
---|
50 | cf::uint8_t * ptr = reinterpret_cast<cf::uint8_t *>(mem);
|
---|
51 |
|
---|
52 | ptr -= sizeof(gVerifier);
|
---|
53 |
|
---|
54 | ::memset(ptr, 0x00, sizeof(gVerifier));
|
---|
55 |
|
---|
56 | ::free(ptr);
|
---|
57 | }
|
---|
58 |
|
---|
59 | cf::bool_t cf::memory::valid(const cf::void_t * mem)
|
---|
60 | {
|
---|
61 | const cf::uint8_t * ptr = reinterpret_cast<const cf::uint8_t *>(mem);
|
---|
62 |
|
---|
63 | /* include checking NULL */
|
---|
64 | if (ptr < (cf::uint8_t *)sizeof(gVerifier))
|
---|
65 | return false;
|
---|
66 |
|
---|
67 | ptr -= sizeof(gVerifier);
|
---|
68 |
|
---|
69 | if (::memcmp(ptr, gVerifier, sizeof(gVerifier)))
|
---|
70 | return false;
|
---|
71 |
|
---|
72 | return true;
|
---|
73 | }
|
---|