← Dart snapshot
Dart·Snapshot format
All tools

How a Flutter app's Dart code is stored

A release Flutter build compiles all Dart code ahead of time (AOT) into one snapshot: a serialized copy of the Dart VM heap (classes, functions, strings, constants…) plus the machine code. This page describes that format as the Dart tool reads it, from the binary container down to single instructions.

The format belongs to the Dart VM (runtime/vm/app_snapshot.cc, snapshot.h, raw_object.h in the Dart SDK). It is not stable: it changes with almost every Dart SDK release. The tool decodes the versions listed under Version identification, for arm64 with compressed pointers, which is what Flutter release builds for Android and iOS produce.

Contents

  1. The ELF container
  2. Snapshot header
  3. Version identification
  4. Stream encoding
  5. Snapshot data layout
  6. Clusters and object records
  7. Roots and the object store
  8. Class IDs
  9. Program model: libraries, classes, functions
  10. Types and signatures
  11. Code, instructions image and instructions table
  12. The object pool
  13. arm64 machine-code conventions
  14. What the tool shows, and its limits
  15. DartSnapshot (lib/dart-snapshot.js)

1The ELF container

libapp.so is a normal ELF shared object, but it is not built by a C linker: the Dart precompiler writes it directly (runtime/vm/elf.cc). It has very few sections (about 10) and exports a handful of dynamic symbols that point at the snapshot pieces. The Flutter engine finds the snapshot by looking these symbols up with dlsym.

Two layouts

Dart SDK Symbols Contents
≤ 3.12
(e.g. 3.11)
_kDartVmSnapshotData
_kDartVmSnapshotInstructions
_kDartIsolateSnapshotData
_kDartIsolateSnapshotInstructions
Two separate snapshots. The VM snapshot holds objects shared by every isolate (predefined classes, common symbols, the VM stubs). The isolate snapshot holds the program and refers back to VM objects. Each has a data part (in .rodata) and an instructions part (in .text).
≥ 3.13 _kDartSnapshotData
_kDartSnapshotText
One merged program snapshot: the VM objects and the program objects are in a single data stream, and all machine code is in one instructions image.
both _kDartSnapshotBuildId An ELF note (NT_GNU_BUILD_ID) with the build ID; it matches the one in the split debug info (--split-debug-info), if the developer kept it.

The *Data symbols point at a snapshot header; the *Instructions / Text symbols point at an instructions image.

Finding the symbols

The tool tries three methods in order:

  1. The section headers: .dynsym and .dynstr.
  2. If the section headers are missing or stripped: the PT_DYNAMIC program header, whose DT_SYMTAB, DT_STRTAB and DT_HASH entries lead to the same symbol table.
  3. As a last resort, a byte signature: the snapshot magic f5 f5 dc dc followed by a valid kind and a 32-character hex hash. With one match it is a merged snapshot (its code starts at the start of the executable segment). With two, the first is the VM snapshot and the second the isolate snapshot; the VM instructions start at the executable segment, and the isolate instructions start at the next 64-byte boundary after them.

3Version identification

The version hash is the MD5 of a fixed list of VM source files (tools/make_version.py, VM_SNAPSHOT_FILES). Any change to those files changes the hash, so the hash pins one exact snapshot format. It does not contain the SDK version number; the tool maps it with a table built by recomputing the hash over the dart-lang/sdk release tags:

Hash Dart SDK Layout
78da37fed6bf1489361a312568249f3f 3.11.x Separate VM + isolate snapshots
0451907c2eaa8467e848c0067bfe8ed4 3.13.x Merged program snapshot

For any other hash the tool still shows the container, header and features, but does not try to decode the objects: the cluster layouts, class IDs and root lists differ between versions, and reading with the wrong layout produces garbage.

To check the version yourself: strings -n 32 libapp.so | grep -E '^[0-9a-f]{32}' prints the hash, followed by the feature string.

4Stream encoding

After the header, the snapshot is a byte stream (runtime/vm/datastream.h) made of three kinds of values.

Unsigned integers — ReadUnsigned

Little-endian base-128: 7 bits per byte, least significant group first. Bytes 0–127 are continuation bytes; the last byte has the high bit set and contributes byte − 128.

300 = 0b10_0101100   →   2c 82
       2c        = 44        (continuation)
       82 − 128  = 2  × 128  (terminator)
       44 + 256  = 300

Signed integers — Read<int32_t>, Read<int64_t>…

The same encoding, but the terminator byte is biased by 192 instead of 128, so its value is in −64…63 and carries the sign. Read<uint8_t>, int8_t and bool are single raw bytes.

Object references — ReadRefId

A reference to another object is its ref ID: big-endian base-128 in at most 4 bytes, where the last byte has the high bit set. Ref ID 0 is unused; 1 is the first base object.

Raw bytes

String characters, typed-data payloads and the encoded PC descriptors / code source maps are copied as-is, sometimes after aligning the stream.

5Snapshot data layout

The stream after the features string has this layout:

num_base_objects                  unsigned
num_objects                       unsigned
num_clusters                      unsigned
instructions_table_len            unsigned
instructions_table_data_offset    unsigned
clusters × num_clusters           alloc sections (cid, count, sizes)
clusters × num_clusters           fill sections  (fields of every object)
roots                             ref IDs

Every object gets a ref ID in the order it is allocated, which lets later objects refer to it, including forward references (cycles are normal: a class refers to its functions, each function to its owner).

Base objects

The first num_base_objects ref IDs are not in the stream: they are objects the reader already has.

Two passes

Alloc: for each cluster, the reader learns how many objects it holds (and, for variable-size objects, each object's length) and allocates them, giving each a ref ID. Fill: in the same cluster order, the reader fills in each object's fields, which can now reference any object. Splitting the passes means objects can be allocated without knowing their contents and references never need patching.

Data image

Right after the snapshot data, at the next 64-byte boundary, is a read-only data image: objects that are used in place, straight from the mapped file, and never copied into the heap. The instructions table lives here, at instructions_table_data_offset.

6Clusters and object records

A cluster groups all objects of one class ID, so the per-object type tag is written once. Each cluster's alloc section starts with a u32 tags word:

tags  bit 1        canonical   (objects are canonicalized, e.g. a type or constant table)
      bits 12–31   class ID

Canonical clusters of types, type arguments and (outside the VM snapshot) strings also write the layout of their canonical hash table after the counts.

Below are the fill records the tool decodes, field by field, for the 3.11/3.13 AOT PRODUCT configuration. ref is a ref ID; the other types are encoded integers. Fields the precompiler drops in AOT (source positions, kernel offsets, usage counters) are not present at all.

Class

alloc  (3.11) count of predefined classes, each: i32 cid       (3.13: none)
       count
fill   name, functions, functions_hash_table, fields, offset_to_field,
       interfaces, script, library, type_parameters, super_type,
       constants, declaration_type, invocation_dispatcher_cache   13 × ref
       id                         i32   class ID
       host_instance_size         i32   (in words)
       host_next_field_offset     i32   (in words)
       host_type_arguments_field  i32
       num_type_arguments         i16
       num_native_fields          u16
       state_bits                 u32
       unboxed_fields_bitmap      u64   (only for real classes, id < 2²⁰)

Top-level functions and fields of a library are owned by a pseudo-class whose ID is ≥ 2²⁰ (kTopLevelCidOffset); the tool shows it as ::.

Function

fill   name, owner, signature, data                   4 × ref
       code_index                 unsigned   0 = no code, else index + 1
       kind_tag                   u32        see “Program model”

owner is a Class or a PatchClass (for code from patch files); data is a ClosureData for closures, which records the parent function and the closure object.

Field

fill   name, owner, type, initializer_function        4 × ref
       kind_bits                  u32   bit 0 const · bit 1 static · bit 2 final
       offset_or_field_id         ref   Smi: instance offset or static field-table index

Library and Script

Library  name, url, private_key, dictionary, metadata, toplevel_class,
         used_scripts, loading_unit, imports, exports       10 × ref
         index i32 · num_imports u16 · load_state u8 · flags u8
Script   url ref · flags_and_max_position i32

private_key is the suffix appended to private names (_foo@12345); the tool strips @nnn when it shows names.

Code

alloc  count, then state_bits i32 per object
       count of deferred codes (deferred loading units), state_bits i32 each
fill   (3.13 only, once per cluster) lazy_compile ref, unknown_dart_code ref
       per object:
         payload_info   unsigned   bit 0 has monomorphic entry
                                   bits 1– unchecked-entry offset
         (deferred codes have no payload_info)
         owner, exception_handlers, pc_descriptors, catch_entry,
         inlined_id_to_function, code_source_map              6 × ref

The Code object does not contain the machine code; its instructions are found through the instructions table, in allocation order. owner is a Function, or a Class (allocation stub) or an AbstractType (type-testing stub).

ObjectPool

alloc  count, then length per pool
fill   length, then per entry:
         bits   u8    type = bits & 15        0 immediate · 1 object · 2 native function
                      behavior = bits >> 5    2 reset to CallBootstrapNative
                                              3 reset to SwitchableCallMiss entry
                                              4 set to zero
         value        object: ref · immediate: i64 · otherwise nothing

Strings

alloc  count, then per string: encoded = length × 2 + (two-byte ? 1 : 0)
fill   encoded again, then length bytes (Latin-1) or length × 2 bytes (UTF-16LE)

All string literals, identifiers, URIs and names in the program are in this cluster; the tool's Strings section lists them and finds the code that loads each one.

Other clusters

Cluster Fill record
Array, ImmutableArray length, type_arguments ref, length × ref
GrowableObjectArray type_arguments, length (Smi), data (Array)
TypeArguments length, hash i32, nullability unsigned, instantiations ref, length × type ref
Type 2 refs (header fields), arguments ref, flags unsigned
FunctionType 2 refs, type_parameters, result_type, parameter_types, named_parameter_names; flags u8, packed_parameter_counts u32, packed_type_parameter_counts u16
RecordType 2 refs, shape, field_types; flags u8
TypeParameter 2 refs, owner; base u16, index u16, flags u8
Closure 3.11: 3 refs (type args), function, context, hash. 3.13: length, 2 refs, function, length × captured-value ref
Mint · Double i64 value in the alloc section · i64 bit pattern of the double
PcDescriptors, CodeSourceMap length, then length raw bytes (delta-encoded tables)
ExceptionHandlers packed length (count × 2 + async flag), handled_types ref, then per handler: pc u32, outer_try_index i16, needs_stacktrace u8, catch_all u8, generated u8
ICData, MegamorphicCache, UnlinkedCall target_name, arguments_descriptor, … — a call site's selector
Instance (user classes) alloc: count, next_field_offset i32, instance_size i32. Fill: a u64 bitmap of unboxed fields, then for every 4-byte field slot, a ref or (if unboxed) a raw 8-byte value
TypedData length, then length × element size raw bytes

7Roots and the object store

After the last fill section come the roots: ref IDs that tell the VM where to find the objects it needs by name.

Dart 3.11

Dart 3.13

  1. 302 raw VM roots (constants, argument descriptors, ICData arrays and the 256 one-character symbols).
  2. 876 handle roots (VM handles and predefined symbols).
  3. 173 VM stub Code objects, in stub-list order.
  4. 6 API handles.
  5. One Class for every predefined class ID, skipping the abstract ones (Object, Error, CallSiteData, AbstractType, FinalizerBase, TypedDataBase, TypedData, ExternalTypedData, TypedDataView, String, FfiStruct). This is how predefined classes get their IDs.
  6. The object store: 171 fields, from list_class to ffi_callback_functions.

The object store holds, among other things, the core classes and types (list_class, map_class, string_type, int_type…), the per-isolate stubs, and global_object_pool: the single object pool that all AOT code uses.

8Class IDs

Every object's header carries a class ID (cid). The first IDs are predefined by the VM (runtime/vm/class_id.h) and identify internal objects (Function, Code…), core types (Smi, Double, String…) and typed data. User classes get IDs from NumPredefined upwards in the order the compiler finalized them; top-level pseudo-classes use IDs ≥ 2²⁰.

The list below is generated from the tool's own table. Dart 3.13 inserted LinkedHashBase after TwoByteString, which shifts every later ID by one; where the IDs differ, both are shown as 3.11/3.13.

Loading…

Typed-data IDs come in groups of four for each element type: TypedData…Array, …ArrayView, ExternalTypedData…Array, UnmodifiableTypedData…ArrayView.

9Program model: libraries, classes, functions

The tool rebuilds the program's structure from the decoded objects:

Function kind_tag

Bits Meaning
0–4 Kind:
14–15 Async modifier: 0 none · 1 async · 2 sync* · 3 async*
16 static
17 const
18 abstract
23 native
24 external

What is not in the snapshot

An AOT build keeps only what the program needs at run time:

10Types and signatures

Object Encoding
Type flags: bit 0 is the nullability (clear = nullable T?, set = non-nullable); bits 3–22 are the class ID of the type's class. arguments is a TypeArguments vector, which for a subclass covers all the type parameters up the hierarchy: the class's own arguments are the last num_type_arguments.
FunctionType packed_parameter_counts: bit 0 number of implicit parameters (the receiver), bit 1 has named parameters, bits 2–15 fixed parameter count, bits 16–29 optional parameter count. parameter_types holds all of them in order; named_parameter_names the names of the optional ones when named.
TypeParameter index into the owning class's or function's type parameters; shown as T0, T1… because names are dropped.
RecordType shape (field count and names) and field_types.

So the signature Future<String?> fetch(Uri, {int timeout}) is a FunctionType with result Future<String?>, 1 implicit + 1 fixed parameter, has-named set, and one optional parameter named timeout.

11Code, instructions image and instructions table

Instructions image

The instructions symbol points at an image that starts with its total size (u64), followed by the machine code of every Code object, back to back. AOT uses bare instructions: code has no per-function header, and calls go straight from one function's instructions to another's.

Instructions table

To map code back to objects, the snapshot has an instructions table in the data image, at data_image_start + instructions_table_data_offset. It is stored as a string-shaped object; its payload starts 16 bytes in:

+0    canonical_stack_map_entries_offset   u32
+4    length                               u32   number of entries
+8    first_entry_with_code                u32
+12   (padding)
+16   entries[length]                      8 bytes each:
        pc_offset          u32   start of the code, from the image start
        stack_map_offset   u32

Entry i covers [image + pc_offset[i], image + pc_offset[i+1]); the last one runs to the end of the image. The first first_entry_with_code entries are code without a Code object (stubs, in 3.11 the VM ones); the rest correspond, in order, to the Code objects of the Code cluster.

From a Function to its machine code

idx = function.code_index − 1          (code_index 0: no code)
if idx < first_entry_with_code:  table entry = idx
else:                            code = Code cluster object #(idx − first_entry_with_code)
                                 table entry = code's position in the table

Code whose owner is not a Function is a stub: [Stub] Allocate X (allocation stub of class X), [Stub] TypeTest T (type-testing stub), or a named VM / object-store stub.

12The object pool

AOT code does not embed object addresses. Every object it needs (strings, constants, classes, fields, call targets that need dispatch, stubs) is an entry in the global object pool, and code loads it through the PP register (x27), which holds the pool's untagged address.

The pool header (tags and length) is 16 bytes and entries are 8 bytes, so a load [PP, #imm] reads entry (imm − 16) / 8:

ldr   x1, [PP, #0x1a8]          ; entry (0x1a8 − 16) / 8 = 51
add   x17, PP, #0x12, lsl #12   ; large index: high part first…
ldr   x1, [x17, #0x340]         ; …entry (0x12340 − 16) / 8 = 9318

The tool resolves both forms and writes the entry next to the instruction: "a string", Class Foo, Function Foo.bar, Field Foo.baz, Type List<int>, Stub …, or an immediate value.

13arm64 machine-code conventions

Dart does not follow the platform C ABI inside Dart code. These registers have fixed roles (runtime/vm/constants_arm64.h), and the tool's listing uses these names:

Register Name Role
x15 SP Dart stack pointer (the hardware sp is used only for C calls).
x16, x17 TMP, TMP2 Scratch registers.
x21 DISPATCH_TABLE Global dispatch table for instance calls: ldr lr, [DISPATCH_TABLE, x?, lsl #3]; blr lr, indexed by receiver cid + selector offset.
x22 NULL The null object; cmp x0, NULL is a null check.
x26 THR The current Thread. [THR, #off] reads runtime state and entry points; the tool names the field (e.g. THR.stack_limit, THR.object_null, THR.allocate_object_entry_point).
x27 PP The object pool (see above).
x28 HEAP_BITS The heap base's upper 32 bits (and the write-barrier mask), used to decompress pointers.
x29, x30 fp, lr Frame pointer, link register.

Patterns worth knowing

14What the tool shows, and its limits

Decoding is supported only for the Dart versions listed under Version identification, and only for arm64 with compressed pointers. Other snapshots show the header and metadata only. Deferred loading units (loadLibrary() parts shipped as separate .so files) are not loaded.

15DartSnapshot

The parser is lib/dart-snapshot.js, a JavaScript module with no dependencies and no user interface, which exports the class DartSnapshot (it also runs in a module worker and in jsc). DartSnapshot.parse returns a DartSnapshot, the model: its fields plus the methods below. It reads the container (ELF, 64-bit Mach-O, or a universal Mach-O's arm64 slice), finds the snapshot by its symbols (or by the byte signature when they are stripped), and deserializes the Dart 3.11 and 3.13 layouts described above. The disassembly is not part of it: the tool decodes instructions with lib/arm64-disasm.js and annotates them with the helpers below.

import { DartSnapshot } from "../lib/dart-snapshot.js";
Method What it does
DartSnapshot.parse(arrayBuffer) Parses a libapp.so or App binary into a model (a DartSnapshot): container (format, arch, segments, vaToOff(address)), symbols, vmHeader / isoHeader (hash, kind, features), version, arch, os, buildId, errors, warnings and, when the version is supported, libraries ({ url, name, classes }), classes, functions, ranges and vmRanges (code ranges { start, end, owner | label }), pool (entries: [{ kind, value }]), strings ({ text }) and stats. Throws when the file is not a Dart snapshot; later problems go to errors.
model.findRange(address) The code range (a function's code or a stub) containing an address, or null.
model.describePoolEntry(index) A short text for object-pool entry index ("a string", Class Foo, Function Foo.bar, #42, …), or null.
model.describeObject(object) The same short text for any deserialized object.
model.typeName(type) A type as Dart source would write it: List<String>?, dynamic, (int, bool), T0 for type parameters.
model.functionTypeStr(functionType, depth, name) A function type as a declaration: int name(String, {bool flag}) (Function when no name is given).
model.signatureParts(functionType) { ret, params } texts for a function's signature, or null when the precompiler dropped it.
DartSnapshot.qualifiedName(function) Class.method (top-level functions without the class).
DartSnapshot.demangle(name) A private name without its library key: _foo@123456 → _foo.
DartSnapshot.strOf(object) The text of a string object, or null for anything else.
DartSnapshot.THREAD_OFFSETS Thread field names by offset, for [THR, #offset] accesses.
DartSnapshot.CID, DartSnapshot.CID_NAME Class ids by name and names by id (the table under Class IDs).
DartSnapshot.DART_VERSIONS The supported snapshot hashes: { hash: { version, layout } }.

The tables that depend on the SDK version (THREAD_OFFSETS, CID, CID_NAME) switch to the layout of the snapshot parsed last, so parse one snapshot at a time and use the helpers with that model.

import { DartSnapshot } from "../lib/dart-snapshot.js";

const model = DartSnapshot.parse(arrayBuffer);
if (model.errors.length) {
	console.log(model.isoHeader.hash, model.errors);
} else {
	for (const library of model.libraries) {
		for (const classObject of library.classes) {
			for (const functionObject of classObject.fnList || []) {
				const signature = model.signatureParts(functionObject.signature);
				const range = functionObject.range;
				console.log(DartSnapshot.qualifiedName(functionObject), signature, range ? range.start.toString(16) : "no code");
			}
		}
	}
	console.log(model.describePoolEntry(51));
}