From 167624783651842a7cc295760088cb223078ad32 Mon Sep 17 00:00:00 2001
From: Mario Werner <mario.werner@iaik.tugraz.at>
Date: Wed, 3 Dec 2014 09:27:56 +0100
Subject: [PATCH] fix alignment of segments during saving -> copied elfs are
 working

The old implementation aligned the segment start. However, the
intended behaviour is to align the offset and the vaddr
(p_vaddr % p_align == p_offset % p_align). This is required for the
loader which can then operate on memory pages.
---
 elfio/elfio.hpp | 21 ++++++++++-----------
 1 file changed, 10 insertions(+), 11 deletions(-)

diff --git a/elfio/elfio.hpp b/elfio/elfio.hpp
index f64163c..41413f4 100644
--- a/elfio/elfio.hpp
+++ b/elfio/elfio.hpp
@@ -581,7 +581,7 @@ class elfio
         for ( unsigned int i = 0; i < worklist.size(); ++i ) {
             Elf_Xword segment_memory   = 0;
             Elf_Xword segment_filesize = 0;
-            Elf_Xword seg_start_pos = 0;
+            Elf_Xword seg_start_pos = current_file_pos;
             segment* seg = worklist[i];
             
             // special case: PHDR segments
@@ -595,18 +595,17 @@ class elfio
                 seg_start_pos = 0;
                 if( seg->get_sections_num() )
                     segment_memory = segment_filesize = current_file_pos;
-            // new segments (no sections or not generated sections)
+            // new segments with not generated sections
             // have to be aligned
-            } else if( !seg->get_sections_num()
-                || ( seg->get_sections_num()
-                     && !section_generated[seg->get_section_index_at( 0 )] )) {
-                Elf64_Off error = current_file_pos % seg->get_align();
-
-                // this alignment seems to be optional
-                // many of the input files are not aligned in the elf file...
-                current_file_pos += ( seg->get_align() - error ) % seg->get_align();
+            } else if( seg->get_sections_num()
+                     && !section_generated[seg->get_section_index_at( 0 )] ) {
+                Elf64_Off cur_page_alignment = current_file_pos % seg->get_align();
+                Elf64_Off req_page_alignment = seg->get_virtual_address() % seg->get_align();
+                Elf64_Off error = req_page_alignment - cur_page_alignment;
+
+                current_file_pos += ( seg->get_align() + error ) % seg->get_align();
                 seg_start_pos = current_file_pos;
-            } else {
+            } else if(seg->get_sections_num()) {
                 seg_start_pos = sections[seg->get_section_index_at( 0 )]->get_offset();
             }
 
-- 
GitLab