diff --git a/elfio/elfio.hpp b/elfio/elfio.hpp index e228776e4..61cb48529 100644 --- a/elfio/elfio.hpp +++ b/elfio/elfio.hpp @@ -632,6 +632,11 @@ class elfio return false; } + std::vector offsets; + for ( const auto &psec : sections) { + offsets.emplace_back( psec->get_offset() ); + } + for ( Elf_Half i = 0; i < num; ++i ) { if ( file_class == ELFCLASS64 ) { segments_.emplace_back( new ( std::nothrow ) @@ -688,6 +693,7 @@ class elfio seg->add_section_index( psec->get_index(), 0 ); } } + seg->sort_sections( offsets ); } return true; diff --git a/elfio/elfio_segment.hpp b/elfio/elfio_segment.hpp index 2c7b08cea..23bf3f818 100644 --- a/elfio/elfio_segment.hpp +++ b/elfio/elfio_segment.hpp @@ -111,6 +111,9 @@ class segment //! \brief Check if the offset is initialized //! \return True if the offset is initialized, false otherwise virtual bool is_offset_initialized() const = 0; + //------------------------------------------------------------------------------ + //! \brief Sort sections in a segment according to offset + virtual void sort_sections( std::vector& offsets ) = 0; protected: //------------------------------------------------------------------------------ @@ -380,6 +383,14 @@ template class segment_impl : public segment //! \brief Set the stream size //! \param value Stream size void set_stream_size( size_t value ) { stream_size = value; } + //------------------------------------------------------------------------------ + //! \brief Sort sections in a segment according to offset + virtual void sort_sections( std::vector &offsets ) + { + std::sort( sections.begin(), sections.end(), [&]( Elf_Half& a, Elf_Half& b) { + return offsets[a] < offsets[b]; + } ); + } //------------------------------------------------------------------------------ private: