Module 4 · Lesson 120 of 156

Boot phases, the toolchain and applications

Attribute delays to boot phases, choose which build changes to test, and measure how static and dynamic linking affect application startup.

  • Beginner to advanced
  • 9 min read
  • 35 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, GCC, libc6-dev, binutils, GNU make, Python 3 and a BusyBox source tree supported by the host toolchain. A board is optional for measuring product boot.

Your place in the module
By the end you can 4 objectives
  • Attribute common boot delays to the bootloader, kernel or userspace phase.
  • Explain how C library choice and build flags affect the binaries in a boot image.
  • Verify static and dynamic BusyBox builds using ELF metadata.
  • Measure and interpret the startup delta between matched builds.
Video coming soonBoot phases, the toolchain and applications
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Defining boot time and measuring it
  • Product boot time runs from a defined start event to a verified readiness event.
  • A serial capture measures when the host receives output and can miss silent startup time.
  • Consecutive markers on one time base give phase intervals that can be compared with a budget.
01

Attribute time to the three boot phases

3 min read

Measurement shows where time goes; now you attack the biggest contributors. This lesson answers the three boot phases, the C library and build flag effect, and static versus dynamic linking and relocation cost.

An early application can exist on disk and still fail to start. Linux reads the interpreter path recorded in a dynamically linked ELF executable. If that path is missing from the current root filesystem, execve() can report ENOENT even when the executable itself exists. The same interpreter, when present, contributes to the time before the application's own code runs. This behavior is documented in execve(2).

Bootloader. Before kernel entry, board firmware and bootloader stages prepare enough hardware to start Linux, locate the boot image and read the files they need. A configured U-Boot autoboot delay or a slow read of the kernel image belongs here. For a power-on measurement, account for earlier firmware and ROM time in the pre-kernel interval, or record it separately if your markers distinguish it. On a BeagleBone using U-Boot, a delay spent waiting for autoboot occurs before PID 1 can run.

Kernel. From kernel entry, Linux brings up its core facilities, initializes built-in drivers and prepares the root environment required to start init. A wait for the root device before the first userspace program runs belongs here. If the kernel starts /init from an initramfs, PID 1 is already in userspace. A wait in that /init script for the final root device is therefore userspace time, even if the console still looks like early boot.

Userspace. PID 1 runs init and starts the programs required for the product's readiness condition. This interval includes application loading, configuration reads and any startup activity the ready event depends on. If a process exists while it is still waiting for hardware or a response from another process, its execution has begun but the product may still be unavailable. Attribute the wait using the event that ends it. A driver can also do work after PID 1 starts, so the phase identifies the time interval and the trace or logs help identify who caused the delay.

Boot phases and their boundariesFirmwareandbootloaderPreparehardwareand loadLinuxKernelentryKernelsetupInitializeand preparerootPID 1startsUserspacestartupInit andrequired applicationsProductreadyFirmwareandbootloaderPreparehardwareand loadLinuxKernelentryKernelsetupInitializeand preparerootPID 1startsUserspacestartupInit andrequired applicationsProductready
Kernel entry and the first userspace program divide the three measured intervals

Consider a boot image that contains an initramfs. Rebuilding BusyBox can change how quickly its applets start after the kernel launches init. It can also change the size of the packed image, which may change how much data the bootloader reads and how much the kernel unpacks. To distinguish these effects, record the application interval and the full boot result separately. A launch benchmark isolates a much narrower question than timing the entire image from power-on.

02

Choose a C library and build flags for the workload

2 min read

The target toolchain produces the machine code and links userspace programs against a C library. Ubuntu 24.04 uses glibc, so it is the natural baseline for the native BusyBox comparison. A target distribution can choose musl, whose compact implementation makes it a candidate for a small userspace or static binaries, or uClibc, commonly encountered in embedded toolchains as uClibc-ng, where build-time configuration determines which library features are included. Linux itself uses its own kernel facilities. The userspace C library matters directly when init and applications start, and indirectly when their bytes are packaged in a boot image.

Choose a library against the software you must ship. Check whether your applications use glibc-specific interfaces or depend on particular behavior for locale or name resolution. For dynamic binaries, the root filesystem must supply the interpreter at the recorded path and compatible shared libraries. A binary built against glibc can require specific symbol versions. Copying a musl or uClibc-ng library into its place cannot satisfy those requirements. Compare C libraries using separate, coherent builds with the same application features. Test the real startup operation as well as the size of the application and its dependencies.

Build choices and deployed bytesCompilerflagsShapegeneratedcodeC librarychoiceSet libraryinterfacesand implementationLinkeroutputIncludecode orrecord dependenciesBoot imagePackagebinariesandrequiredlibrariesCompilerflagsShapegeneratedcodeC librarychoiceSet libraryinterfacesand implementationLinkeroutputIncludecode orrecord dependenciesBoot imagePackagebinariesandrequiredlibraries
Three build choices affect program code, dependencies and the deployed image

Compiler options can change both the number of instructions executed and the amount of code the system needs to read. GCC's -Os optimizes for size and is a useful comparison with -O2 for an early application on a storage-constrained device. Smaller code can reduce the number of pages touched during a cold launch. A build that favors size can also spend more CPU time doing application work. Measure both the bytes deployed and the time to the same readiness event.

For a program with unused routines pulled in at link time, try compiling with -ffunction-sections -fdata-sections and linking with -Wl,--gc-sections. The compiler places functions and data in separate sections and the linker can discard eligible sections that it finds unreachable. Inspect the result and exercise the required features, especially if the program uses custom sections or a linker script. Likewise, remove unused shared library dependencies from the link and verify the resulting DT_NEEDED entries with readelf -d. Changing library choice, optimization level and linkage together makes a timing difference difficult to attribute. Start with one change and use the same executable inputs for both runs.

03

Measure what linking changes at application startup

5 min read

A lets separately built objects refer to each other. In a normal dynamically linked program, the kernel starts the interpreter named in PT_INTERP. The interpreter, commonly referred to as ld.so, loads the required shared libraries and performs startup relocations before control reaches the application's main. Static linking includes the needed code from static libraries in the executable. A conventional static executable starts without an external ELF interpreter.

Startup work by link modeDynamicConventionalstaticExternalinterpreterUsedAbsentLibrary codeSharedobjectsIn executableStartup fixupsLoaderappliesrelocationsExternalloader absentAcross differentprogramsLibrary pagesshareableCode can beduplicated
Static and dynamic linking place different work and bytes at application launch

Static linking can help when one small early program runs repeatedly and its own work is short. Dynamic linking can be attractive when many programs use the same library, because they can share its file-backed code pages. Statically linking many separate binaries can duplicate library code on storage, and larger binaries can increase image loading or unpacking time. BusyBox is useful for this comparison because the same multicall executable can provide the same applets in both builds. An explicit ./busybox true in a timed loop starts an executable each time. Calling the shell's bare true can instead run a builtin and bypass that startup work.

Going deeperExplore the mechanism

When ld.so applies a relative relocation, it can compute the value from the object's load address and the relocation data. A relocation that needs a named symbol can also require a search through the applicable symbol tables. Some function bindings may be deferred until first use, depending on the platform and link settings. A relocation count from readelf -r therefore gives context but does not directly predict startup time. Removing a genuinely unused shared dependency can reduce library loading and relocation work. On a dynamic glibc build, LD_DEBUG=statistics can help investigate the loader; run it separately because diagnostics change the workload.

A conventional static build removes external loader startup. A static PIE can still perform self-relocation, so an absent PT_INTERP alone says nothing about the total number of runtime fixups. Historical prelink tooling prepared ELF files at preferred addresses and resolved eligible relocations in advance. Its benefit depended on compatible loader support and an unchanged library set, and preferred addresses complicate address randomization. Treat prelink as historical context for this Ubuntu 24.04 lab.

For a matched BusyBox comparison, start from one source revision and one .config with CONFIG_TRUE=y. Build with native GCC in two clean copies of the source tree. In make menuconfig, disable CONFIG_STATIC in one copy and enable it in the other. Build each with make. Warning from a real build: BusyBox 1.36.1 with make defconfig did not compile on Ubuntu 24.04 (kernel headers 6.8), because networking/tc.c failed with errors such as 'TCA_CBQ_MAX' undeclared. Disabling the tc applet fixed it: set # CONFIG_TC is not set in .config (menuconfig: Networking Utilities, tc) before running make. With that change the dynamic build took a few seconds with make -j2 and the static build under half a minute on the test machine. Then copy the resulting executables into the same benchmark directory as busybox-dynamic and busybox-static. Use the same applets, compiler and optimization settings. Keeping both files on the same filesystem avoids comparing, for example, a WSL Linux filesystem with a Windows-mounted directory.

bash
readelf -lW ./busybox-dynamic ./busybox-static
readelf -dW ./busybox-dynamic ./busybox-static
wc -c ./busybox-dynamic ./busybox-static

In the real build the dynamic executable was 1059432 bytes, with Requesting program interpreter: /lib64/ld-linux-x86-64.so.2 and NEEDED entries libm.so.6, libresolv.so.2 and libc.so.6; the static one was 2464864 bytes, had no INTERP header and readelf -d printed There is no dynamic section in this file. The sizes depend on your configuration and compiler. Look for INTERP in the dynamic build's program headers and NEEDED in its dynamic entries. The ordinary static build should have neither. Check that both execute the true applet successfully before interpreting timings. Missing archives can prevent the static build from linking. A missing interpreter or shared library can prevent the dynamic build from running. Resolve build or runtime errors before collecting samples.

bash
python3 - <<'PY'
from statistics import median
from subprocess import run
from time import perf_counter_ns

paths = ("./busybox-dynamic", "./busybox-static")
samples = {path: [] for path in paths}

for path in paths:
    run([path, "true"], check=True)

for trial in range(7):
    order = paths if trial % 2 == 0 else paths[::-1]
    for path in order:
        start = perf_counter_ns()
        for _ in range(300):
            run([path, "true"], check=True)
        samples[path].append((perf_counter_ns() - start) / 300 / 1000)

for path in paths:
    print(f"{path}: {median(samples[path]):.2f} us/launch, samples={samples[path]}")
print(f"dynamic minus static: {median(samples[paths[0]]) - median(samples[paths[1]]):.2f} us/launch")
PY

The script reports warm-cache startup and exit together, including Python's process launch and wait overhead. Both builds pay that overhead. Repeated batches reduce the influence of a single noisy launch, and alternating the order reduces bias from changes in system load over the run. Compare the delta with the spread of the batches. A positive dynamic-minus-static delta means the static build had a lower median in this test. Example from one real run of exactly this script inside a Docker container (your numbers will differ): ./busybox-dynamic: 501.68 us/launch, ./busybox-static: 235.98 us/launch, dynamic minus static: 265.70 us/launch, with batch samples between about 497 and 520 for the dynamic build and 223 and 256 for the static one. A run of LD_DEBUG=statistics ./busybox-dynamic true in the same container printed number of relocations: 584, number of relative relocations: 1282 and a loader time of 248019 cycles, of which relocation was 28.6 percent. If the difference is small compared with the spread, report that the result is inconclusive. A cold boot on the target can behave differently because storage, caches and the startup workload differ.

When evaluating a real application, choose an event that means it can do its job, such as the first valid sensor sample. If a faster launch finishes while the same required device is still unavailable, the measured product readiness time may stay the same. The next lesson, Optimising init and reducing services, examines which programs init starts and which of them the device needs before it can report ready.

Key takeaways

  • Bootloader time ends at kernel entry, and userspace begins when Linux starts PID 1.
  • The target C library affects userspace compatibility, code size and startup work.
  • Static linking can remove external loader work, while dynamic linking lets programs share library code.
  • A per-launch improvement changes boot time only if it advances the chosen readiness event.
Reflect
  1. Explain to a colleague, in two sentences: attribute common boot delays to the bootloader, kernel or userspace phase.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close