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
4
5ByteBuffer::ByteBuffer(BYTE *v_content, bufsize_t v_size, bufsize_t v_padding)
6 : content(nullptr), contentSize(0), padding(v_padding),
8{
9 if (v_size == 0) throw BufferException("Zero size requested");
10
11 this->content = allocContent(v_size, v_padding);
12 if (this->content) {
13 this->contentSize = v_size;
14 this->originalSize = v_size;
15 if (v_content) {
16 ::memcpy(this->content, v_content, v_size);
17 }
18 }
19}
20
22 : ByteBuffer(nullptr, v_size, v_padding)
23{
24}
25
27 : content(nullptr), contentSize(0), padding(0),
28 originalSize(0), m_refs(0)
29{
30 if (!v_parent) throw BufferException("Cannot make subBuffer for NULL buffer!");
31 if (!v_size) throw BufferException("Cannot make 0 size buffer!");
32
33 bufsize_t parentSize = v_parent->getContentSize();
34
35 bufsize_t copySize = v_size < parentSize ? v_size : parentSize;
36 bufsize_t allocSize = v_size > parentSize ? v_size : parentSize;
37
38 BYTE *bContent = v_parent->getContentAt(v_offset, copySize);
39 if (!bContent) throw BufferException("Cannot make Buffer for NULL content!");
40
41 this->content = allocContent(allocSize, v_padding);
42 if (this->content) {
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:44
BYTE * content
Definition ByteBuffer.h:40
virtual ~ByteBuffer()
bufsize_t contentSize
Definition ByteBuffer.h:41
ByteBuffer(bufsize_t v_size, bufsize_t padding=DEFAULT_PADDING)
size_t m_refs
Definition ByteBuffer.h:46
BYTE * allocContent(bufsize_t v_size, bufsize_t padding)
bufsize_t padding
Definition ByteBuffer.h:42
virtual bool resize(bufsize_t newSize)