| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| #include <cstdio> |
| #include <cstdlib> |
| #include <cstring> |
| #include <cstdint> |
|
|
| |
| |
| class MemoryReadAdapter { |
| public: |
| explicit MemoryReadAdapter(const void* data, int64_t size) |
| : data_(data), size_(size) {} |
|
|
| size_t size() const { |
| return size_; |
| } |
|
|
| |
| size_t read(uint64_t pos, void* buf, size_t n, const char* what = "") const { |
| (void)what; |
| memcpy(buf, (int8_t*)(data_) + pos, n); |
| return n; |
| } |
|
|
| private: |
| const void* data_; |
| int64_t size_; |
| }; |
|
|
| |
| |
| size_t safe_read(const void* data, size_t data_size, uint64_t pos, void* buf, size_t n) { |
| size_t s = (pos >= data_size) ? 0 : (size_t)((data_size - pos < n) ? data_size - pos : n); |
| memcpy(buf, (const uint8_t*)data + pos, s); |
| return s; |
| } |
|
|
| int main() { |
| |
| const size_t BUF_SIZE = 32; |
| char* data = (char*)malloc(BUF_SIZE); |
| if (!data) return 1; |
| memset(data, 'A', BUF_SIZE); |
|
|
| |
| MemoryReadAdapter adapter(data, BUF_SIZE); |
| printf("Buffer size: %zu bytes at %p\n", adapter.size(), data); |
|
|
| char output[256]; |
| memset(output, 0, sizeof(output)); |
|
|
| |
| printf("\n[Test 1] Reading 16 bytes at offset 0 (within bounds)...\n"); |
| adapter.read(0, output, 16); |
| printf(" OK: read 16 bytes\n"); |
|
|
| |
| printf("\n[Test 2] Reading 64 bytes at offset 0 (32 bytes past buffer end)...\n"); |
| printf(" Buffer is %zu bytes, but requesting 64 bytes\n", BUF_SIZE); |
| printf(" MemoryReadAdapter::read() will memcpy 64 bytes - reading 32 bytes of HEAP DATA\n"); |
| adapter.read(0, output, 64); |
| printf(" Leaked %zu bytes past buffer end!\n", (size_t)64 - BUF_SIZE); |
|
|
| |
| printf("\n[Test 3] Reading 16 bytes at offset 128 (entirely past buffer)...\n"); |
| adapter.read(128, output, 16); |
| printf(" Read from offset 128, buffer is only %zu bytes!\n", BUF_SIZE); |
|
|
| free(data); |
| return 0; |
| } |
|
|