Skip to content

Commit 78f9142

Browse files
committed
Generate optimal string table for section names; align section headers
1 parent ebea388 commit 78f9142

2 files changed

Lines changed: 25 additions & 8 deletions

File tree

src/LibObjectFile/Elf/ElfObjectFile.cs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -253,12 +253,23 @@ public unsafe void UpdateLayout(DiagnosticBag diagnostics)
253253
shstrTable.Reset();
254254

255255
// Prepare all section names (to calculate the name indices and the size of the SectionNames)
256-
for (var j = 0; j < sections.Count; j++)
256+
// Do it in two passes to generate optimal string table
257+
for (var pass = 0; pass < 2; pass++)
257258
{
258-
var otherSection = sections[j];
259-
if ((j == 0 && otherSection.Type == ElfSectionType.Null)) continue;
260-
if (otherSection.IsShadow) continue;
261-
otherSection.Name = otherSection.Name.WithIndex(shstrTable.GetOrCreateIndex(otherSection.Name));
259+
for (var j = 0; j < sections.Count; j++)
260+
{
261+
var otherSection = sections[j];
262+
if ((j == 0 && otherSection.Type == ElfSectionType.Null)) continue;
263+
if (otherSection.IsShadow) continue;
264+
if (pass == 0)
265+
{
266+
shstrTable.ReserveString(otherSection.Name);
267+
}
268+
else
269+
{
270+
otherSection.Name = otherSection.Name.WithIndex(shstrTable.GetOrCreateIndex(otherSection.Name));
271+
}
272+
}
262273
}
263274
}
264275

@@ -276,9 +287,9 @@ public unsafe void UpdateLayout(DiagnosticBag diagnostics)
276287
}
277288

278289
// The Section Header Table will be put just after all the sections
279-
Layout.OffsetOfSectionHeaderTable = offset;
290+
Layout.OffsetOfSectionHeaderTable = AlignHelper.AlignToUpper(offset, FileClass == ElfFileClass.Is32 ? 4u : 8u);
280291

281-
Layout.TotalSize = offset + (ulong)VisibleSectionCount * Layout.SizeOfSectionHeaderEntry;
292+
Layout.TotalSize = Layout.OffsetOfSectionHeaderTable + (ulong)VisibleSectionCount * Layout.SizeOfSectionHeaderEntry;
282293
}
283294

284295
// Update program headers with offsets from auto layout

src/LibObjectFile/Elf/ElfWriter{TEncoder}.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,10 +227,16 @@ private void WriteSections()
227227
private void WriteSectionHeaderTable()
228228
{
229229
var offset = (ulong)Stream.Position - _startOfFile;
230-
if (offset != Layout.OffsetOfSectionHeaderTable)
230+
var diff = Layout.OffsetOfSectionHeaderTable - offset;
231+
if (diff < 0 || diff > 8)
231232
{
232233
throw new InvalidOperationException("Internal error. Unexpected offset for SectionHeaderTable");
233234
}
235+
else if (diff != 0)
236+
{
237+
// Alignment
238+
Stream.Write(stackalloc byte[(int)diff]);
239+
}
234240

235241
// Then write all regular sections
236242
var sections = ObjectFile.Sections;

0 commit comments

Comments
 (0)