From bd5f2128ae7a19014b17691260af436d7a674f0e Mon Sep 17 00:00:00 2001 From: alvaro Date: Tue, 4 Jul 2017 22:35:24 +0200 Subject: [PATCH] Check size for segment Fix crash b82f05b0b25c8fdc98480e6d76b6d5f9164ae2bc Running: crash-b82f05b0b25c8fdc98480e6d76b6d5f9164ae2bc ==2850==WARNING: AddressSanitizer failed to allocate 0x400000004000001 bytes ==2850==AddressSanitizer's allocator is terminating the process instead of returning 0 ==2850==If you don't like this behavior set allocator_may_return_null=1 ==2850==AddressSanitizer CHECK failed: /home/alvaro/tools/llvm/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cc:22 1 "((0)) != (0)" (0x0, 0x0) --- elfio/elfio_segment.hpp | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/elfio/elfio_segment.hpp b/elfio/elfio_segment.hpp index 35f17e9..4d95a2f 100644 --- a/elfio/elfio_segment.hpp +++ b/elfio/elfio_segment.hpp @@ -92,6 +92,21 @@ class segment_impl : public segment ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz ); ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz ); ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset ); + size_t stream_size; + +//------------------------------------------------------------------------------ + const size_t + get_stream_size() const + { + return stream_size; + } + +//------------------------------------------------------------------------------ + void + set_stream_size(size_t value) + { + stream_size = value; + } //------------------------------------------------------------------------------ Elf_Half @@ -176,6 +191,10 @@ class segment_impl : public segment load( std::istream& stream, std::streampos header_offset ) { + + stream.seekg ( 0, stream.end ); + set_stream_size ( stream.tellg() ); + stream.seekg( header_offset ); stream.read( reinterpret_cast( &ph ), sizeof( ph ) ); is_offset_set = true; @@ -183,14 +202,19 @@ class segment_impl : public segment if ( PT_NULL != get_type() && 0 != get_file_size() ) { stream.seekg( (*convertor)( ph.p_offset ) ); Elf_Xword size = get_file_size(); - try { - data = new char[size]; - } catch (const std::bad_alloc&) { - data = 0; - } - if ( 0 != data ) { - stream.read( data, size ); - } + if ( size > get_stream_size() ) { + data = 0; + } else { + try { + data = new char[size + 1]; + } catch (const std::bad_alloc&) { + data = 0; + } + if ( 0 != data ) { + stream.read( data, size ); + data[size] = 0; + } + } } }