Place sections in memory
Assign each section an address in its region, aligned, and report overflows. A medium embedded C problem (Linker scripts), run and graded in the browser.
medium · Linker scripts · linker · memory · alignment
A linker script lists memory regions (origin and length) and places output sections in them in order. Each section starts at the next free address in its region, rounded up to its alignment (a power of two).
Write place(regions, nr, sections, ns): set each region's next to its origin, then place the sections in order, filling in addr. Return 0 if everything fits, or the index + 1 of the first section that does not fit in its region (its end would pass origin + length).
Starter code
int place(region_t *regions, int nr, section_t *sections, int ns) {
for (int i = 0; i < nr; i++) regions[i].next = regions[i].origin;
for (int i = 0; i < ns; i++) {
region_t *r = ®ions[sections[i].region];
sections[i].addr = r->next;
r->next += sections[i].size;
}
return 0;
}Example tests
Flash and RAM
region_t r[] = { {"FLASH", 0x08000000u, 0x10000u}, {"RAM", 0x20000000u, 0x5000u} };
section_t s[] = { {".isr", 0x10C, 4, 0}, {".text", 0x2F31, 8, 0}, {".rodata", 0x220, 4, 0}, {".data", 0x84, 4, 1}, {".bss", 0x3F2, 8, 1} };
show(r, 2, s, 5);Expected output:
.isr 0x08000000
.text 0x08000110
.rodata 0x08003044
.data 0x20000000
.bss 0x20000088
FLASH used 12900 of 65536
RAM used 1146 of 20480Learn it first
- Linker scripts · MEMORY, SECTIONS, the location counter, KEEP and ALIGN.