Skip to content

Commit 83c5b03

Browse files
authored
feat: add support for linker scripts (#1332)
* feat: add support for linker scripts Adds support to use a linker script. By default the ld linker script is used, this can be changed with the `--script` command or disabled with the `--no-linker-script` command. * Use arch specific scripts * Use contains in tests because the triple does not start with arch * Use different script for aarch64 with pie
1 parent 28f7349 commit 83c5b03

File tree

6 files changed

+534
-1
lines changed

6 files changed

+534
-1
lines changed

compiler/plc_driver/src/cli.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,24 @@ pub struct CompileParameters {
9999
#[clap(name = "include", long, short = 'i', help = "Include source files for external functions")]
100100
pub includes: Vec<String>,
101101

102+
#[clap(
103+
name = "script",
104+
long,
105+
global = true,
106+
group = "linker_script",
107+
help = "Specify a linker script to use"
108+
)]
109+
pub linker_script: Option<String>,
110+
111+
#[clap(
112+
name = "no-linker-script",
113+
long,
114+
global = true,
115+
group = "linker_script",
116+
help = "Specify that no linker script should be used"
117+
)]
118+
pub no_linker_script: bool,
119+
102120
#[clap(
103121
name = "hardware-conf",
104122
long,

compiler/plc_driver/src/lib.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,15 @@ pub struct LinkOptions {
8080
pub format: FormatOption,
8181
pub linker: LinkerType,
8282
pub lib_location: Option<PathBuf>,
83+
pub linker_script: LinkerScript,
84+
}
85+
86+
#[derive(Clone, Default, Debug)]
87+
pub enum LinkerScript {
88+
#[default]
89+
Builtin,
90+
Path(String),
91+
None,
8392
}
8493

8594
#[derive(Debug)]
@@ -199,12 +208,20 @@ pub fn get_compilation_context<T: AsRef<str> + AsRef<OsStr> + Debug>(
199208

200209
library_paths.extend_from_slice(project.get_library_paths());
201210

211+
//Get the specified linker script or load the default linker script in a temp file
212+
let linker_script = if compile_parameters.no_linker_script {
213+
LinkerScript::None
214+
} else {
215+
compile_parameters.linker_script.clone().map(LinkerScript::Path).unwrap_or_default()
216+
};
217+
202218
let link_options = LinkOptions {
203219
libraries,
204220
library_paths,
205221
format: output_format,
206222
linker: compile_parameters.linker.as_deref().into(),
207223
lib_location,
224+
linker_script,
208225
};
209226

210227
Ok(CompilationContext { compile_parameters, project, diagnostician, compile_options, link_options })

compiler/plc_driver/src/pipelines.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ use std::{
77
sync::Mutex,
88
};
99

10-
use crate::{CompileOptions, LinkOptions};
10+
use crate::{CompileOptions, LinkOptions, LinkerScript};
1111
use ast::{
1212
ast::{pre_process, CompilationUnit, LinkageType},
1313
provider::IdProvider,
1414
};
1515

16+
use log::debug;
1617
use plc::{
1718
codegen::{CodegenContext, GeneratedModule},
1819
index::{FxIndexSet, Index},
@@ -39,6 +40,7 @@ use rayon::prelude::*;
3940
use source_code::{source_location::SourceLocation, SourceContainer};
4041

4142
use serde_json;
43+
use tempfile::NamedTempFile;
4244
use toml;
4345

4446
pub fn read_got_layout(location: &str, format: ConfigFormat) -> Result<HashMap<String, u64>, Diagnostic> {
@@ -626,6 +628,34 @@ impl GeneratedProject {
626628
linker.add_lib_path(&loc.to_string_lossy());
627629
}
628630

631+
//HACK: Create a temp file that would contain the bultin linker script
632+
//FIXME: This has to be done regardless if the file is used or not because it has
633+
//to be in scope by the time we call the linker
634+
let mut file = NamedTempFile::new()?;
635+
match link_options.linker_script {
636+
LinkerScript::Builtin => {
637+
let target = self.target.get_target_triple().to_string();
638+
//Only do this on linux systems
639+
if target.contains("linux") {
640+
if target.contains("x86_64") {
641+
let content = include_str!("../../../scripts/linker/x86_64.script");
642+
writeln!(file, "{content}")?;
643+
linker.set_linker_script(file.get_location_str().to_string());
644+
} else if target.contains("aarch64") {
645+
let content = include_str!("../../../scripts/linker/aarch64.script");
646+
writeln!(file, "{content}")?;
647+
linker.set_linker_script(file.get_location_str().to_string());
648+
} else {
649+
debug!("No script for target : {target}");
650+
}
651+
} else {
652+
debug!("No script for target : {target}");
653+
}
654+
}
655+
LinkerScript::Path(script) => linker.set_linker_script(script),
656+
LinkerScript::None => {}
657+
};
658+
629659
match link_options.format {
630660
FormatOption::Static => linker.build_exectuable(output_location).map_err(Into::into),
631661
FormatOption::Shared | FormatOption::PIC | FormatOption::NoPIC => {

scripts/linker/aarch64.script

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
/* Script for -pie -z combreloc -z relro -z now */
2+
/* Copyright (C) 2014-2024 Free Software Foundation, Inc.
3+
Copying and distribution of this script, with or without modification,
4+
are permitted in any medium without royalty provided the copyright
5+
notice and this notice are preserved. */
6+
OUTPUT_FORMAT("elf64-littleaarch64", "elf64-bigaarch64",
7+
"elf64-littleaarch64")
8+
OUTPUT_ARCH(aarch64)
9+
ENTRY(_start)
10+
SEARCH_DIR("=/usr/local/lib/aarch64-linux-gnu"); SEARCH_DIR("=/lib/aarch64-linux-gnu"); SEARCH_DIR("=/usr/lib/aarch64-linux-gnu"); SEARCH_DIR("=/usr/local/lib"); SEARCH_DIR("=/lib"); SEARCH_DIR("=/usr/lib"); SEARCH_DIR("=/usr/aarch64-linux-gnu/lib");
11+
SECTIONS
12+
{
13+
/* Read-only sections, merged into text segment: */
14+
PROVIDE (__executable_start = SEGMENT_START("text-segment", 0)); . = SEGMENT_START("text-segment", 0) + SIZEOF_HEADERS;
15+
.interp : { *(.interp) }
16+
.note.gnu.build-id : { *(.note.gnu.build-id) }
17+
.hash : { *(.hash) }
18+
.gnu.hash : { *(.gnu.hash) }
19+
.dynsym : { *(.dynsym) }
20+
.dynstr : { *(.dynstr) }
21+
.gnu.version : { *(.gnu.version) }
22+
.gnu.version_d : { *(.gnu.version_d) }
23+
.gnu.version_r : { *(.gnu.version_r) }
24+
.rela.dyn :
25+
{
26+
*(.rela.init)
27+
*(.rela.text .rela.text.* .rela.gnu.linkonce.t.*)
28+
*(.rela.fini)
29+
*(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*)
30+
*(.rela.data .rela.data.* .rela.gnu.linkonce.d.*)
31+
*(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*)
32+
*(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*)
33+
*(.rela.ctors)
34+
*(.rela.dtors)
35+
*(.rela.got)
36+
*(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*)
37+
*(.rela.ifunc)
38+
}
39+
.rela.plt :
40+
{
41+
*(.rela.plt)
42+
*(.rela.iplt)
43+
}
44+
.init :
45+
{
46+
KEEP (*(SORT_NONE(.init)))
47+
} =0x1f2003d5
48+
.plt : ALIGN(16) { *(.plt) *(.iplt) }
49+
.text :
50+
{
51+
*(.text.unlikely .text.*_unlikely .text.unlikely.*)
52+
*(.text.exit .text.exit.*)
53+
*(.text.startup .text.startup.*)
54+
*(.text.hot .text.hot.*)
55+
*(SORT(.text.sorted.*))
56+
*(.text .stub .text.* .gnu.linkonce.t.*)
57+
/* .gnu.warning sections are handled specially by elf.em. */
58+
*(.gnu.warning)
59+
} =0x1f2003d5
60+
.fini :
61+
{
62+
KEEP (*(SORT_NONE(.fini)))
63+
} =0x1f2003d5
64+
PROVIDE (__etext = .);
65+
PROVIDE (_etext = .);
66+
PROVIDE (etext = .);
67+
.rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) }
68+
.rodata1 : { *(.rodata1) }
69+
.eh_frame_hdr : { *(.eh_frame_hdr) *(.eh_frame_entry .eh_frame_entry.*) }
70+
.eh_frame : ONLY_IF_RO { KEEP (*(.eh_frame)) *(.eh_frame.*) }
71+
.sframe : ONLY_IF_RO { *(.sframe) *(.sframe.*) }
72+
.gcc_except_table : ONLY_IF_RO { *(.gcc_except_table .gcc_except_table.*) }
73+
.gnu_extab : ONLY_IF_RO { *(.gnu_extab*) }
74+
/* These sections are generated by the Sun/Oracle C++ compiler. */
75+
.exception_ranges : ONLY_IF_RO { *(.exception_ranges*) }
76+
/* Adjust the address for the data segment. We want to adjust up to
77+
the same address within the page on the next page up. */
78+
. = DATA_SEGMENT_ALIGN (CONSTANT (MAXPAGESIZE), CONSTANT (COMMONPAGESIZE));
79+
/* Exception handling */
80+
.eh_frame : ONLY_IF_RW { KEEP (*(.eh_frame)) *(.eh_frame.*) }
81+
.sframe : ONLY_IF_RW { *(.sframe) *(.sframe.*) }
82+
.gnu_extab : ONLY_IF_RW { *(.gnu_extab) }
83+
.gcc_except_table : ONLY_IF_RW { *(.gcc_except_table .gcc_except_table.*) }
84+
.exception_ranges : ONLY_IF_RW { *(.exception_ranges*) }
85+
/* Thread Local Storage sections */
86+
.tdata :
87+
{
88+
PROVIDE_HIDDEN (__tdata_start = .);
89+
*(.tdata .tdata.* .gnu.linkonce.td.*)
90+
}
91+
.tbss : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) }
92+
.preinit_array :
93+
{
94+
PROVIDE_HIDDEN (__preinit_array_start = .);
95+
KEEP (*(.preinit_array))
96+
PROVIDE_HIDDEN (__preinit_array_end = .);
97+
}
98+
.init_array :
99+
{
100+
PROVIDE_HIDDEN (__init_array_start = .);
101+
KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*)))
102+
KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors))
103+
PROVIDE_HIDDEN (__init_array_end = .);
104+
}
105+
.fini_array :
106+
{
107+
PROVIDE_HIDDEN (__fini_array_start = .);
108+
KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*)))
109+
KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors))
110+
PROVIDE_HIDDEN (__fini_array_end = .);
111+
}
112+
.ctors :
113+
{
114+
/* gcc uses crtbegin.o to find the start of
115+
the constructors, so we make sure it is
116+
first. Because this is a wildcard, it
117+
doesn't matter if the user does not
118+
actually link against crtbegin.o; the
119+
linker won't look for a file to match a
120+
wildcard. The wildcard also means that it
121+
doesn't matter which directory crtbegin.o
122+
is in. */
123+
KEEP (*crtbegin.o(.ctors))
124+
KEEP (*crtbegin?.o(.ctors))
125+
/* We don't want to include the .ctor section from
126+
the crtend.o file until after the sorted ctors.
127+
The .ctor section from the crtend file contains the
128+
end of ctors marker and it must be last */
129+
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors))
130+
KEEP (*(SORT(.ctors.*)))
131+
KEEP (*(.ctors))
132+
}
133+
.dtors :
134+
{
135+
KEEP (*crtbegin.o(.dtors))
136+
KEEP (*crtbegin?.o(.dtors))
137+
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors))
138+
KEEP (*(SORT(.dtors.*)))
139+
KEEP (*(.dtors))
140+
}
141+
.jcr : { KEEP (*(.jcr)) }
142+
.data.rel.ro : { *(.data.rel.ro.local* .gnu.linkonce.d.rel.ro.local.*) *(.data.rel.ro .data.rel.ro.* .gnu.linkonce.d.rel.ro.*) }
143+
.dynamic : { *(.dynamic) }
144+
.got : { *(.got.plt) *(.igot.plt) *(.got) *(.igot) }
145+
. = DATA_SEGMENT_RELRO_END (0, .);
146+
.data :
147+
{
148+
PROVIDE (__data_start = .);
149+
*(.data .data.* .gnu.linkonce.d.*)
150+
SORT(CONSTRUCTORS)
151+
}
152+
.data1 : { *(.data1) }
153+
_edata = .; PROVIDE (edata = .);
154+
/*. = ALIGN(ALIGNOF(NEXT_SECTION));*/
155+
__bss_start = .;
156+
__bss_start__ = .;
157+
.bss :
158+
{
159+
*(.dynbss)
160+
*(.bss .bss.* .gnu.linkonce.b.*)
161+
*(COMMON)
162+
/* Align here to ensure that the .bss section occupies space up to
163+
_end. Align after .bss to ensure correct alignment even if the
164+
.bss section disappears because there are no input sections.
165+
FIXME: Why do we need it? When there is no .bss section, we do not
166+
pad the .data section. */
167+
. = ALIGN(. != 0 ? 64 / 8 : 1);
168+
}
169+
_bss_end__ = .; __bss_end__ = .;
170+
. = ALIGN(64 / 8);
171+
. = SEGMENT_START("ldata-segment", .);
172+
. = ALIGN(64 / 8);
173+
__end__ = .;
174+
_end = .; PROVIDE (end = .);
175+
. = DATA_SEGMENT_END (.);
176+
/* Stabs debugging sections. */
177+
.stab 0 : { *(.stab) }
178+
.stabstr 0 : { *(.stabstr) }
179+
.stab.excl 0 : { *(.stab.excl) }
180+
.stab.exclstr 0 : { *(.stab.exclstr) }
181+
.stab.index 0 : { *(.stab.index) }
182+
.stab.indexstr 0 : { *(.stab.indexstr) }
183+
.comment 0 (INFO) : { *(.comment); LINKER_VERSION; }
184+
.gnu.build.attributes : { *(.gnu.build.attributes .gnu.build.attributes.*) }
185+
/* DWARF debug sections.
186+
Symbols in the DWARF debugging sections are relative to the beginning
187+
of the section so we begin them at 0. */
188+
/* DWARF 1. */
189+
.debug 0 : { *(.debug) }
190+
.line 0 : { *(.line) }
191+
/* GNU DWARF 1 extensions. */
192+
.debug_srcinfo 0 : { *(.debug_srcinfo) }
193+
.debug_sfnames 0 : { *(.debug_sfnames) }
194+
/* DWARF 1.1 and DWARF 2. */
195+
.debug_aranges 0 : { *(.debug_aranges) }
196+
.debug_pubnames 0 : { *(.debug_pubnames) }
197+
/* DWARF 2. */
198+
.debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) }
199+
.debug_abbrev 0 : { *(.debug_abbrev) }
200+
.debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end) }
201+
.debug_frame 0 : { *(.debug_frame) }
202+
.debug_str 0 : { *(.debug_str) }
203+
.debug_loc 0 : { *(.debug_loc) }
204+
.debug_macinfo 0 : { *(.debug_macinfo) }
205+
/* SGI/MIPS DWARF 2 extensions. */
206+
.debug_weaknames 0 : { *(.debug_weaknames) }
207+
.debug_funcnames 0 : { *(.debug_funcnames) }
208+
.debug_typenames 0 : { *(.debug_typenames) }
209+
.debug_varnames 0 : { *(.debug_varnames) }
210+
/* DWARF 3. */
211+
.debug_pubtypes 0 : { *(.debug_pubtypes) }
212+
.debug_ranges 0 : { *(.debug_ranges) }
213+
/* DWARF 5. */
214+
.debug_addr 0 : { *(.debug_addr) }
215+
.debug_line_str 0 : { *(.debug_line_str) }
216+
.debug_loclists 0 : { *(.debug_loclists) }
217+
.debug_macro 0 : { *(.debug_macro) }
218+
.debug_names 0 : { *(.debug_names) }
219+
.debug_rnglists 0 : { *(.debug_rnglists) }
220+
.debug_str_offsets 0 : { *(.debug_str_offsets) }
221+
.debug_sup 0 : { *(.debug_sup) }
222+
.ARM.attributes 0 : { KEEP (*(.ARM.attributes)) KEEP (*(.gnu.attributes)) }
223+
.note.gnu.arm.ident 0 : { KEEP (*(.note.gnu.arm.ident)) }
224+
/DISCARD/ : { *(.note.GNU-stack) *(.gnu_debuglink) *(.gnu.lto_*) }
225+
}

0 commit comments

Comments
 (0)