Zero Initialized Memory

Uninitialized memory in C and C++ is a common cause of reliability problems, memory safety bugs and information leaks. To avoid these issues, Android initializes as much memory as possible.

Zero initialized userspace memory

Since Android 12, stack memory is zero initialized in all platform native code (including JNI) and heap memory is zero initialized in all platform native processes (such as netd) but not in the zygote or in apps.

First and third-party applications built with the NDK are strongly recommended to use the -ftrivial-auto-var-init=zero compiler flag to zero-initialize their stack local variables. The compiler optimizes away any zeroing that is unnecessary. For example, when a local variable is explicitly initialized (such as, int x = 123; variable x is initialized only once). If the program has a large stack buffer in a performance hotspot, the developer can disable initialization using a compiler attribute:

__attribute__((__uninitialized__)) char buf[BUFSIZ];

Applications can also opt in to heap zero initialization by using the android:nativeHeapZeroInitialized manifest attribute. Alternatively, heap zero initialization can be controlled at runtime with:

int mallopt(M_BIONIC_ZERO_INIT, level)

Where level is 0 or 1.

Zero initialized kernel memory

The kernel stack and heap is zero initialized for GKI kernels, which is strongly recommended by the CDD.

For stack initialization, GKI uses the CONFIG_INIT_STACK_ALL_ZERO config, which results in building the kernel using the -ftrivial-auto-var-init=zero compiler flag. For heap initialization, GKI uses the CONFIG_INIT_ON_ALLOC_DEFAULT_ON, which makes all page heap, SLAB and SLUB allocations zero-initialized when they are created. This option is effectively similar to passing init_on_alloc=1 as a kernel boot-time option.

Bug reports

Our tools generate insightful bug reports that contain additional information to aid with debugging. The additional allocation and deallocation stack trace help better understand the life cycle of a given allocation and lead to root-causing memory safety bugs much faster.

Example of a bug report generated
  by memory safety tool
Figure 1: Bug reports generated by memory safety tools

During development, vendors should monitor the presence of bugs by checking /data/tombstones and logcat for native crashes. For more information on debugging Android native code see the information here.