Table of Contents

Trimming and feature switches

An ahead-of-time compiler sees the whole program before it runs. Starting from the entry point, it follows every call, every type constructed and every virtual method that might be reached, compiles what it reaches, and leaves everything else out of the image. This is trimming. It keeps a kernel built from large libraries small, and it also means that code has to be reachable to exist: a class that nothing references is not in the image, whatever assembly it came from.

A feature switch decides reachability at build time. It is a named setting fixed when the program is compiled and read through a property the compiler knows about. The compiler replaces each read of that property with the switch's value, so a branch guarded by a switch that is off tests a constant false, can never run, and is removed, along with everything that only that branch reached. Turning a subsystem off this way removes its code from the image instead of skipping it at run time.

The trap is a reference outside the guard. Trimming removes what is unreachable, not what is guarded: if any code that stays in the image references a type, the type stays too, even with its switch off. A switch is also a build setting, so a kernel compiled with a feature off cannot turn it on at run time; the code is not there.

In Cosmos, each CosmosEnable* property in a kernel's .csproj becomes a RuntimeHostConfigurationOption marked Trim="true", which reaches ILC, the NativeAOT compiler (Cosmos.Build.Ilc), as a --feature: argument. The properties ILC replaces are in Core's CosmosFeatures, marked [FeatureSwitchDefinition], and KernelFeatures in Cosmos.Kernel.System is the public view a kernel reads. Some switches turn others off: with CosmosEnableInterrupts off, Sdk.targets also turns off the timer, keyboard, mouse, network, storage, scheduler and PCI switches, and with CosmosEnableScheduler off, the finalizer thread switch (CosmosEnableFinalizerThread). The driver manifest uses the switches as guards: a driver declared [Driver(Feature = DriverFeature.Network)] is registered inside if (KernelFeatures.Network), and since nothing else constructs a shipped driver, a kernel built with CosmosEnableNetwork off carries no network driver at all. See The attribute and the manifest and Feature guards.