- /* Now swap the first and last PT_LOAD segments'
- positions in segment_map. */
- struct elf_segment_map *first = *first_load;
- struct elf_segment_map *last = *last_load;
- *first_load = first->next;
- first->next = last->next;
- last->next = first;
+ struct elf_segment_map **last_load = NULL;
+ struct elf_segment_map *seg;
+
+ m = first_load;
+ while ((seg = *m) != NULL)
+ {
+ if (seg->p_type == PT_LOAD)
+ {
+ /* Clear the flags on any previous segment that
+ included the file header and phdrs. */
+ seg->includes_filehdr = 0;
+ seg->includes_phdrs = 0;
+ seg->no_sort_lma = 1;
+ /* Also strip out empty segments. */
+ if (seg->count == 0)
+ {
+ if (headers == &seg->next)
+ headers = m;
+ *m = seg->next;
+ continue;
+ }
+ last_load = m;
+ }
+ m = &seg->next;
+ }
+
+ /* This segment will include those headers instead. */
+ seg = *headers;
+ seg->includes_filehdr = 1;
+ seg->includes_phdrs = 1;
+
+ if (last_load != NULL && first_load != last_load && first_load != headers)
+ {
+ /* Put the first PT_LOAD header last. */
+ struct elf_segment_map *first = *first_load;
+ struct elf_segment_map *last = *last_load;
+ *first_load = first->next;
+ first->next = last->next;
+ last->next = first;
+ }