Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion libwild/src/elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,9 @@ pub(crate) fn link_for_arch<'data, F: FileSystem>(
}
}

pub(crate) trait ElfWord: Copy + FromBytes + IntoBytes + Into<u64> + Send + Sync {
pub(crate) trait ElfWord:
Copy + FromBytes + IntoBytes + Into<u64> + Send + Sync + object::Pod
{
fn from_u64(value: u64) -> Result<Self>;
fn from_le_bytes(bytes: &[u8]) -> Self;
}
Expand Down
5 changes: 2 additions & 3 deletions libwild/src/elf_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -773,11 +773,10 @@ impl<'layout, 'out, C: ElfClass> TableWriter<'layout, 'out, C> {
buffers.take(part_id::GNU_VERSION_R),
versym.is_empty().not().then_some(versym),
);

TableWriter {
output_kind,
got: <[elf::Word<C>]>::mut_from_bytes(buffers.take(part_id::GOT)).unwrap(),
got_relr: <[elf::Word<C>]>::mut_from_bytes(buffers.take(part_id::GOT_RELR)).unwrap(),
got: slice_from_all_bytes_mut(buffers.take(part_id::GOT)),
got_relr: slice_from_all_bytes_mut(buffers.take(part_id::GOT_RELR)),
plt_got: buffers.take(part_id::PLT_GOT),
rela_plt: slice_from_all_bytes_mut(buffers.take(part_id::RELA_PLT)),
tls,
Expand Down
110 changes: 72 additions & 38 deletions libwild/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,29 +371,28 @@ fn compute_address_layout<'data, P: Platform, A: Arch<Platform = P>>(
location_counters.extend(script.parsed.location_counters.iter().cloned());
}

let (output_order, program_segments) =
output_sections.output_order(symbol_db.output_kind, &linker_scripts, &location_counters)?;

tracing::trace!(
"Output order:\n{}",
output_order.display::<A::Platform>(&output_sections, &program_segments)
);

let TotalSectionSizes {
mut section_part_sizes,
gdb_index_data,
partial_link,
output_order,
program_segments,
} = compute_total_section_part_sizes(
&mut group_states,
&mut output_sections,
&output_order,
&program_segments,
&linker_scripts,
&location_counters,
per_symbol_flags,
must_keep_sections,
&finalise_sizes_resources,
partial_link_plan.as_ref(),
)?;

tracing::trace!(
"Output order:\n{}",
output_order.display::<A::Platform>(&output_sections, &program_segments)
);

let thunk_blocks = thunk_layout_builder.map_or_default(|builder| {
builder.build(
&mut group_states,
Expand Down Expand Up @@ -2622,13 +2621,15 @@ struct TotalSectionSizes<'data, P: Platform> {
section_part_sizes: OutputSectionPartMap<u64>,
gdb_index_data: Option<P::GdbIndexScanResult<'data>>,
partial_link: PartialLinkSingletons,
output_order: OutputOrder<'data>,
program_segments: ProgramSegments<P::ProgramSegmentDef>,
}

fn compute_total_section_part_sizes<'data, P: Platform>(
group_states: &mut [GroupState<'data, P>],
output_sections: &mut OutputSections<P>,
output_order: &OutputOrder<'data>,
program_segments: &ProgramSegments<P::ProgramSegmentDef>,
output_sections: &mut OutputSections<'data, P>,
linker_scripts: &[&SequencedLinkerScript<'data, P>],
location_counters: &[crate::layout_rules::LocationCounter<'data>],
per_symbol_flags: &mut PerSymbolFlags,
must_keep_sections: OutputSectionMap<bool>,
resources: &FinaliseSizesResources<'data, '_, P>,
Expand Down Expand Up @@ -2678,13 +2679,27 @@ fn compute_total_section_part_sizes<'data, P: Platform>(
unreachable!();
};

let keep_sections = prelude.determine_kept_sections(
&total_sizes,
must_keep_sections,
output_sections,
resources,
per_symbol_flags,
);
let (output_order, program_segments) = output_sections.output_order(
resources.symbol_db.output_kind,
linker_scripts,
location_counters,
&keep_sections,
)?;

let partial_link = prelude.apply_late_size_adjustments(
&mut first_group.common,
&mut total_sizes,
must_keep_sections,
keep_sections,
output_sections,
output_order,
program_segments,
&output_order,
&program_segments,
per_symbol_flags,
resources,
partial_link_plan,
Expand All @@ -2706,6 +2721,8 @@ fn compute_total_section_part_sizes<'data, P: Platform>(
section_part_sizes: total_sizes,
gdb_index_data,
partial_link,
output_order,
program_segments,
})
}

Expand Down Expand Up @@ -3810,7 +3827,7 @@ impl<'data, P: Platform> PreludeLayoutState<'data, P> {
&mut self,
common: &mut CommonGroupState<'data, P>,
total_sizes: &mut OutputSectionPartMap<u64>,
must_keep_sections: OutputSectionMap<bool>,
keep_sections: OutputSectionMap<bool>,
output_sections: &mut OutputSections<P>,
output_order: &OutputOrder<'data>,
program_segments: &ProgramSegments<P::ProgramSegmentDef>,
Expand All @@ -3824,14 +3841,12 @@ impl<'data, P: Platform> PreludeLayoutState<'data, P> {
let mut extra_sizes = common.mem_sizes.new_empty_like();

let partial_link = self.determine_header_sizes(
total_sizes,
&mut extra_sizes,
must_keep_sections,
keep_sections,
output_sections,
program_segments,
output_order,
resources,
per_symbol_flags,
partial_link_plan,
);

Expand Down Expand Up @@ -3942,20 +3957,14 @@ impl<'data, P: Platform> PreludeLayoutState<'data, P> {
)
}

fn determine_header_sizes(
&mut self,
fn determine_kept_sections(
&self,
total_sizes: &OutputSectionPartMap<u64>,
extra_sizes: &mut OutputSectionPartMap<u64>,
must_keep_sections: OutputSectionMap<bool>,
output_sections: &mut OutputSections<P>,
program_segments: &ProgramSegments<P::ProgramSegmentDef>,
output_order: &OutputOrder<'data>,
output_sections: &OutputSections<P>,
resources: &FinaliseSizesResources<'data, '_, P>,
symbol_flags: &PerSymbolFlags,
partial_link_plan: Option<&PartialLinkPlan>,
) -> PartialLinkSingletons {
use output_section_id::OrderEvent;

) -> OutputSectionMap<bool> {
// Determine which sections to keep. To start with, we keep all sections that we've
// previously marked as needing to be kept. These may include sections that are empty, but
// into which we've loaded an empty input section.
Expand All @@ -3971,12 +3980,6 @@ impl<'data, P: Platform> PreludeLayoutState<'data, P> {
// Keep any sections that we've said we want to keep regardless.
P::apply_force_keep_sections(&mut keep_sections, resources.symbol_db.args);

if output_order.has_custom_layout()
&& let Some(relro_padding_id) = P::RELRO_PADDING_SECTION_ID
{
*keep_sections.get_mut(relro_padding_id) = false;
}

// Keep any sections that have a start/stop symbol which is referenced.
symbol_flags
.raw_range(self.symbol_id_range())
Expand All @@ -3999,6 +4002,31 @@ impl<'data, P: Platform> PreludeLayoutState<'data, P> {
let keep_secondary = replace(keep_sections.get_mut(section_id), false);
*keep_sections.get_mut(primary_id) |= keep_secondary;
}
}

keep_sections
}

fn determine_header_sizes(
&mut self,
extra_sizes: &mut OutputSectionPartMap<u64>,
mut keep_sections: OutputSectionMap<bool>,
output_sections: &mut OutputSections<P>,
program_segments: &ProgramSegments<P::ProgramSegmentDef>,
output_order: &OutputOrder<'data>,
resources: &FinaliseSizesResources<'data, '_, P>,
partial_link_plan: Option<&PartialLinkPlan>,
) -> PartialLinkSingletons {
use output_section_id::OrderEvent;

if output_order.has_custom_layout()
&& let Some(relro_padding_id) = P::RELRO_PADDING_SECTION_ID
{
*keep_sections.get_mut(relro_padding_id) = false;
}

for i in 0..output_sections.num_sections() {
let section_id = OutputSectionId::from_usize(i);

// Remove any built-in sections without a type except for section 0 (the file header).
// This should just be the .phdr and .shdr sections which contain the program headers
Expand Down Expand Up @@ -7263,8 +7291,14 @@ fn test_no_disallowed_overlaps() {
let output_kind =
crate::output_kind::OutputKind::StaticExecutable(crate::args::RelocationModel::Fixed);
let mut output_sections = OutputSections::<Elf64>::with_base_address(0x1000, output_kind);
let (output_order, program_segments) =
output_sections.output_order(output_kind, &[], &[]).unwrap();
let (output_order, program_segments) = output_sections
.output_order(
output_kind,
&[],
&[],
&output_sections.new_section_map_with(|| true),
)
.unwrap();
let mut args = crate::args::elf::ElfArgs::default();
if args.architecture() == crate::arch::Architecture::Unsupported {
args.set_architecture(crate::arch::Architecture::X86_64);
Expand Down
10 changes: 10 additions & 0 deletions libwild/src/output_section_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,7 @@ impl<'data, P: Platform> OutputSections<'data, P> {
output_kind: OutputKind,
linker_scripts: &[&SequencedLinkerScript<'data, P>],
location_counters: &[crate::layout_rules::LocationCounter<'data>],
keep_sections: &OutputSectionMap<bool>,
) -> Result<(OutputOrder<'data>, ProgramSegments<P::ProgramSegmentDef>)> {
verbose_timing_phase!("Compute output order");

Expand Down Expand Up @@ -1065,6 +1066,15 @@ impl<'data, P: Platform> OutputSections<'data, P> {
return;
}

// Absent orphans must not split segments or switch memory regions. Explicit section
// addresses still need to take effect even when the section is empty.
if info.section_attributes.is_alloc()
&& !*keep_sections.get(id)
&& info.location_info.is_none()
{
return;
}

if id == FILE_HEADER
|| P::CUSTOM_PHDR_EXCLUDED_SECTION_IDS.contains(&id)
|| Some(id) == P::RELRO_PADDING_SECTION_ID
Expand Down
3 changes: 3 additions & 0 deletions libwild/src/output_section_part_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ fn test_merge_parts() {
crate::output_kind::OutputKind::StaticExecutable(crate::args::RelocationModel::Fixed),
&[],
&[],
&output_sections.new_section_map_with(|| true),
)
.unwrap();

Expand Down Expand Up @@ -451,6 +452,7 @@ fn test_output_order_map_consistent() {
crate::output_kind::OutputKind::StaticExecutable(crate::args::RelocationModel::Fixed),
&[],
&[],
&output_sections.new_section_map_with(|| true),
)
.unwrap();
let mut part_map = output_sections.new_part_map::<u32>();
Expand Down Expand Up @@ -518,6 +520,7 @@ fn test_output_order_map() {
crate::output_kind::OutputKind::StaticExecutable(crate::args::RelocationModel::Fixed),
&[],
&[],
&output_sections.new_section_map_with(|| true),
)
.unwrap();
let mut part_map = output_sections.new_part_map::<u32>();
Expand Down
4 changes: 4 additions & 0 deletions linker-utils/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ pub fn slice_from_all_bytes<T: object::Pod>(data: &[u8]) -> &[T] {

#[must_use]
pub fn slice_from_all_bytes_mut<T: object::Pod>(data: &mut [u8]) -> &mut [T] {
// Skip alignment check if the slice is empty.
if data.is_empty() {
return &mut [];
}
object::slice_from_bytes_mut(data, data.len() / size_of::<T>())
.unwrap()
.0
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//#LinkerScript:regions.ld
//#ReferenceLinkers:bfd,lld
//#RunEnabled:false
//#CompArgs:-fPIE -fno-unwind-tables -fno-asynchronous-unwind-tables
//#LinkArgs:-no-pie -z max-page-size=0x10000
//#ExpectProgramHeader:LOAD flags=RX,sections=[.text,*],vaddr=0x100000,paddr=0x100000
//#ExpectProgramHeader:LOAD flags=RW,sections=[.first,.bss,*],vaddr=0x200000,paddr=0x200000
//#MaxFileSize:150000

int data __attribute__((section(".first"))) = 42;
int bss;

void _start(void) {}
10 changes: 10 additions & 0 deletions wild/tests/sources/elf/linker-script-absent-orphans/regions.ld
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
MEMORY {
ROM : ORIGIN = 0x100000, LENGTH = 64K
RAM : ORIGIN = 0x200000, LENGTH = 64K
}

SECTIONS {
.text : { KEEP(*(.text .text.*)) } > ROM
.first : { KEEP(*(.first)) } > RAM
.bss : { KEEP(*(.bss .bss.*)) } > RAM
}