BearParser
Portable Executable parsing library (from PE-bear)
Loading...
Searching...
No Matches
ByteBuffer.cpp
Go to the documentation of this file.
1#include "ByteBuffer.h"
2#include <iostream>
3
5 : ByteBuffer()
6{
7 if (v_size == 0) throw BufferException("Zero size requested");
8
9 this->content = allocContent(v_size, v_padding);
10 if (this->content) {
11 this->padding = v_padding;
12 this->contentSize = v_size;
13 this->originalSize = v_size;
14 }
15}
16
17ByteBuffer::ByteBuffer(BYTE* v_content, bufsize_t v_size, bufsize_t v_padding)
18 : ByteBuffer(v_size, v_padding)
19{
20 if (v_size == 0) throw BufferException("Zero size requested");
21 if (this->content && v_content) {
22 ::memcpy(this->content, v_content, v_size);
23 }
24}
25
27 : ByteBuffer()
28{
29 if (!v_parent) throw BufferException("Cannot make subBuffer for NULL buffer!");
30 if (!v_size) throw BufferException("Cannot make 0 size buffer!");
31
32 bufsize_t parentSize = v_parent->getContentSize();
33
34 bufsize_t copySize = v_size < parentSize ? v_size : parentSize;
35 bufsize_t allocSize = v_size > parentSize ? v_size : parentSize;
36
37 BYTE *bContent = v_parent->getContentAt(v_offset, copySize);
38 if (!bContent) throw BufferException("Cannot make Buffer for NULL content!");
39
40 this->content = allocContent(allocSize, v_padding);
41 if (this->content) {
42 this->padding = v_padding;
43 this->contentSize = allocSize;
44 this->originalSize = this->contentSize;
45 ::memcpy(this->content, bContent, copySize);
46 }
47}
48
50{
51 if (!v_size) throw BufferException("Zero size requested");
52
53 const bufsize_t allocSize = v_size + v_padding;
54 const bufsize_t sizeDiff = (allocSize > this->contentSize) ? (allocSize - this->contentSize) : 0;
55
56 BYTE* content = reinterpret_cast<BYTE*>(::realloc((void*)this->content, allocSize));
57 if (!content) {
58 throw BufferException("Cannot allocate buffer of size: 0x" + QString::number(allocSize, 16));
59 }
60 if (sizeDiff) {
61 ::memset(content + this->contentSize, 0, sizeDiff);
62 }
63 return content;
64}
65
67{
68 if (newSize == this->contentSize) {
69 return true;
70 }
71 BYTE *newContent = nullptr;
72 bool isOk = true;
73 try {
74 newContent = allocContent(newSize, this->padding);
75 if (newContent) {
76 this->content = newContent;
77 this->contentSize = newSize;
78 }
79 } catch (const BufferException&) {
80 isOk = false;
81 }
82 return isOk;
83}
84
86{
87 ::free(this->content);
88}
uint32_t bufsize_t
uint64_t offset_t
virtual bufsize_t getContentSize()=0
virtual BYTE * getContentAt(offset_t offset, bufsize_t size, bool allowExceptions=false)
bufsize_t originalSize
Definition ByteBuffer.h:32
BYTE * content
Definition ByteBuffer.h:28
virtual ~ByteBuffer()
bufsize_t contentSize
Definition ByteBuffer.h:29
BYTE * allocContent(bufsize_t v_size, bufsize_t padding)
bufsize_t padding
Definition ByteBuffer.h:30
virtual bool resize(bufsize_t newSize)