1# FIDL: Wire Format Specification
2
3This document is a specification of the Fuchsia Interface Definition Language
4(FIDL) data structure encoding.
5
6See [FIDL: Overview](../index.md) for more information about FIDL's overall
7purpose, goals, and requirements, as well as links to related documents.
8
9[TOC]
10
11## Design
12
13### Goals
14
15*   Efficiently transfer messages between processes.
16*   General purpose, for use with device drivers, high-level services, and
17    applications.
18*   Optimized for Zircon IPC only; portability is not a goal.
19*   Optimized for direct memory access; inter-machine transport is not a goal.
20*   Optimized for 64-bit only; no accommodation for 32-bit environments.
21*   Uses uncompressed native data types with host-endianness and correct
22    alignment to support in-place access of message contents.
23*   Compatible with C structure in-memory layout (with suitable field ordering
24    and packing annotations).
25*   Structures are fixed size and inlined; variable-sized data is stored
26    out-of-line.
27*   Structures are not self-described; FIDL files describe their contents.
28*   No versioning of structures, but interfaces can be extended with new methods
29    for protocol evolution.
30*   No offset calculations required, very little arithmetic which may overflow.
31*   Support fast single-pass encoding and validation (as a combined operation).
32*   Support fast single-pass decoding and validation (as a combined operation).
33
34### Messages
35
36A **message** is a contiguous data structure represented using the FIDL Wire
37Format, consisting of a single **in-line primary object** followed by a sequence
38of **out-of-line secondary objects** stored in **traversal order**.
39
40#### Objects
41
42Messages are aggregates of **objects**.
43
44The **primary object** of a message is simply the first object it contains. It
45is always a **struct** of fixed size whose type (and size) is known from the
46context (such as by examining the **method ordinal** in the **interface call
47header**).
48
49To store variable-size or optional data, the primary object may refer to
50**secondary objects**, such as string content, vector content, structs, and
51unions. Secondary objects are stored **out-of-line** sequentially in traversal
52order following the object which reference them. In encoded messages, the
53presence of secondary objects is marked by a flag. In decoded messages, the
54flags are substituted with pointers to their location in memory (or null
55pointers when absent).
56
57Primary and secondary objects are 8-byte aligned and stored sequentially in
58traversal order without gaps other than the minimum required padding to maintain
59object alignment.
60
61Objects may also contain **in-line objects** which are aggregated within the
62body of the containing object, such as embedded structs and fixed-size arrays of
63structs. The alignment factor of in-line objects is determined by the alignment
64factor of their most restrictive member.
65
66In the following example, each Rect structure contains two Point objects which
67are stored in-line whereas each Region structure contains a vector with a
68variable number of Rect objects which are stored sequentially out-of-line. In
69this case, the secondary object is the vector's content (as a unit).
70
71```
72struct Region {
73    vector<Rect> rects;
74};
75struct Rect {
76    Point top_left;
77    Point bottom_right;
78};
79struct Point { uint32 x, y; };
80```
81
82![drawing](objects.png)
83
84#### Traversal Order
85
86The **traversal order** of a message is a determined by a recursive depth-first
87walk of all of the **objects** it contains, as obtained by following the chain
88of references.
89
90Given the following structure:
91
92```
93struct Cart {
94    vector<Item> items;
95};
96struct Item {
97    Product product;
98    uint32 quantity;
99};
100struct Product {
101    string sku;
102    string name;
103    string? description;
104    uint32 price;
105};
106```
107
108The depth-first traversal order for a Cart message is defined by the following
109pseudo-code:
110
111```
112visit Cart:
113    for each Item in Cart.items vector data:
114        visit Item.product:
115                visit Product.sku
116                visit Product.name
117                visit Product.description
118                visit Product.price
119            visit Item.quantity
120```
121
122#### Dual Forms
123
124The same message content can be expressed in two forms -- **encoded** and
125**decoded** -- which have the same size and overall layout but differ in terms
126of their representation of pointers (memory addresses) or handles
127(capabilities).
128
129FIDL is designed such that **encoding** and **decoding** of messages can occur
130in place in memory assuming that objects have been stored in traversal order.
131
132The representation of encoded messages is unambiguous. There is exactly one
133possible encoding for all messages of the same type with the same content.
134
135![drawing](dual-forms.png)
136
137#### Encoded Messages
138
139An **encoded message** has been prepared for transfer to another process: it
140does not contain pointers (memory addresses) or handles (capabilities).
141
142During **encoding**���
143
144*   all pointers to sub-objects within the message are replaced with flags which
145    indicate whether their referent is present or not-present in traversal order
146*   all handles within the message are extracted to an associated **handle
147    vector** and replaced with flags which indicate whether their referent is
148    present or not-present in traversal order
149
150The resulting **encoding message** and **handle vector** can then be sent to
151another process using **zx_channel_call()** or a similar IPC mechanism.
152
153#### Decoded Messages
154
155A **decoded message** has been prepared for use within a process's address
156space: it may contain pointers (memory addresses) or handles (capabilities).
157
158During **decoding**...
159
160*   all pointers to sub-objects within the message are reconstructed using the
161    encoded present / not-present flags in traversal order
162*   all handles within the message are restored from the associated **handle
163    vector** using the encoded present / not-present flags in traversal order
164
165The resulting **decoded message** is ready to be consumed directly from memory.
166
167## Data Types
168
169### Primitives
170
171*   Value stored in native machine format.
172*   Packed with natural alignment.
173    *   Each _m_-byte primitive is stored on an _m_-byte boundary.
174*   Not nullable.
175
176The following primitive types are supported:
177
178Category                | Types
179----------------------- | ----------------------------
180Boolean                 | `bool`
181Signed integer          | `int8 int16 int32 int64`
182Unsigned integer        | `uint8 uint16 uint32 uint64`
183IEEE 754 Floating-point | `float32 float64`
184
185Number types are suffixed with their size in bits, `bool` is 1 byte.
186
187### Enums
188
189*   Primitive value representing a proper enumerated type; bit fields are not
190    valid enums.
191*   Stored directly using their underlying primitive type.
192*   Not nullable.
193
194From the perspective of the wire format, enums are just fancy names for
195primitive types.
196
197For example, an enum whose underlying type is
198`int32` is stored in exactly the same way as any
199ordinary C `int32_t` would be.
200
201### Arrays
202
203*   Fixed length sequence of homogeneous elements.
204*   Packed with natural alignment of their elements.
205    *   Alignment of array is the same as the alignment of its elements.
206    *   Each subsequent element is aligned on element's alignment boundary.
207*   The stride of the array is exactly equal to the size of the element (which
208    includes the padding required to satisfy element alignment constraints).
209*   Not nullable.
210*   There is no special case for arrays of bools. Each bool element takes one
211    byte as usual.
212
213Arrays are denoted:
214
215*   `T[n]`: where *T* can be any FIDL type
216    (including an array) and *n* is the number of elements in the array.
217
218![drawing](arrays.png)
219
220### Strings
221
222*   Variable-length sequence of UTF-8 encoded characters representing text.
223*   Nullable; null strings and empty strings are distinct.
224*   Can specify a maximum size, e.g. `string:40` for
225    a maximum 40 byte string.
226*   String content does not have a null-terminator.[^1]
227
228*   Stored as a 16 byte record consisting of:
229
230    *   `size` : 64-bit unsigned number of code
231        units (bytes)
232    *   `data` : 64-bit presence indication or
233        pointer to out-of-line string data
234
235*   When encoded for transfer, `data` indicates
236    presence of content:
237
238    *   `0` : string is null
239    *   `UINTPTR_MAX` : string is non-null, data is
240        the next out-of-line object
241
242*   When decoded for consumption, `data` is a
243    pointer to content.
244
245    *   `0` : string is null
246    *   `<valid pointer>` : string is non-null, data
247        is at indicated memory address
248
249Strings are denoted as follows:
250
251*   `string` : non-nullable string (validation error
252    occurs if null `data` is encountered)
253*   `string?` : nullable string
254*   `string:N, string:N?` : string with maximum
255    length of <em>N</em> bytes
256
257![drawing](strings.png)
258
259### Vectors
260
261*   Variable-length sequence of homogeneous elements.
262*   Nullable; null vectors and empty vectors are distinct.
263*   Can specify a maximum size, e.g. `vector<T>:40`
264    for a maximum 40 element vector.
265*   Stored as a 16 byte record consisting of:
266    *   `size` : 64-bit unsigned number of elements
267    *   `data` : 64-bit presence indication or
268        pointer to out-of-line element data
269*   When encoded for transfer, `data` indicates
270    presence of content:
271    *   `0` : vector is null
272    *   `UINTPTR_MAX` : vector is non-null, data is
273        the next out-of-line object
274*   When decoded for consumption, `data` is a
275    pointer to content.
276    *   `0` : vector is null
277    *   `<valid pointer>` : vector is non-null, data
278        is at indicated memory address
279*   There is no special case for vectors of bools. Each bool element takes one
280    byte as usual.
281
282Vectors are denoted as follows:
283
284*   `vector<T>` : non-nullable vector of element
285    type <em>T</em> (validation error occurs if null
286    `data` is encountered)
287*   `vector<T>?` : nullable vector of element type
288    <em>T</em>
289*   `vector<T>:N, vector<T>:N?` : vector with
290    maximum length of <em>N</em> elements
291
292<em>T</em> can be any FIDL type.
293
294![drawing](vectors.png)
295
296### Handles
297
298*   Transfers a Zircon capability by handle value.
299*   Stored as a 32-bit unsigned integer.
300*   Nullable by encoding as a zero-valued[^2] handle (equivalent to
301    `ZX_HANDLE_INVALID`).
302
303*   When encoded for transfer, the stored integer indicates presence of handle:
304
305    *   `0` : handle is null
306    *   `UINT32_MAX` : handle is non-null, handle
307        value is the next entry in handle table
308
309*   When decoded for consumption, the stored integer is handle value itself.
310
311    *   `0` : handle is null
312    *   `<valid handle>` : handle is non-null,
313        handle value is provided in-line
314
315Handles are denoted:
316
317*   `handle` : non-nullable Zircon handle of
318    unspecified type
319*   `handle?` : nullable Zircon handle of
320    unspecified type
321*   `handle<H>` : non-nullable Zircon handle of type
322    <em>H</em>
323*   `handle<H>?` : nullable Zircon handle of type
324    <em>H</em>
325*   `Interface` : non-nullable FIDL interface
326    (client endpoint of channel)
327*   `Interface?` : nullable FIDL interface (client
328    endpoint of channel)
329*   `request<Interface>` : non-nullable FIDL interface
330    request (server endpoint of channel)
331*   `request<Interface>?` : nullable FIDL interface request
332    (server endpoint of channel)
333
334<em>H</em> can be one of[^3]: `channel, event, eventpair, fifo,
335job, process, port, resource, socket, thread, vmo`
336
337### Structs
338
339*   Record type consisting of a sequence of typed fields.
340
341*   Alignment factor of structure is defined by maximal alignment factor of any
342    of its fields.
343
344*   Structure is padded with zeroes so that its size is a multiple of its
345    alignment factor.
346
347    *   e.g. 1. a struct with an **int32** and an **int8** field has an
348        alignment of 4 bytes (due to **int32**) and a size of 8 bytes (3 bytes
349        of padding)
350    *   e.g. 2. a struct with a **bool** and a **string** field has an alignment
351        of 8 bytes (due to **string**) and a size of 24 bytes (7 bytes of
352        padding)
353    *   e.g. 3. a struct with a **bool** and a **uint8[2]** field has an
354        alignment of 1 byte and a size of 3 bytes (no padding!)
355
356*   In general, changing the definition of a struct will break binary
357    compatibility; instead prefer to extend interfaces by adding new methods
358    which use new structs.
359
360Storage of a structure depends on whether it is nullable at point of reference.
361
362*   Non-nullable structures:
363    *   Contents are stored in-line within their containing type, enabling very
364        efficient aggregate structures to be constructed.
365    *   The structure layout does not change when inlined; its fields are not
366        repacked to fill gaps in its container.
367*   Nullable structures:
368    *   Contents are stored out-of-line and accessed through an indirect
369        reference.
370    *   When encoded for transfer, stored reference indicates presence of
371        structure:
372        *   `0` : reference is null
373        *   `UINTPTR_MAX` : reference is non-null,
374            structure content is the next out-of-line object
375    *   When decoded for consumption, stored reference is a pointer.
376        *   `0` : reference is null
377        *   `<valid pointer>` : reference is
378            non-null, structure content is at indicated memory address
379
380Structs are denoted by their declared name (e.g. <strong>Circle</strong>) and
381nullability:
382
383*   `Circle` : non-nullable Circle
384*   `Circle?` : nullable Circle
385
386The following example shows how structs are laid out according to their fields.
387
388```
389struct Circle {
390    bool filled;
391    Point center;    // Point will be stored in-line
392    float32 radius;
393    Color? color;    // Color will be stored out-of-line
394    bool dashed;
395};
396struct Point { float32 x, y; };
397struct Color { float32 r, g, b; };
398```
399
400The Color content is padded to the 8 byte secondary object alignment
401boundary.
402
403![drawing](structs.png)
404
405### Unions
406
407*   Tagged option type consisting of tag field and variadic contents.
408*   Tag field is represented with a **uint32 enum**.
409*   Size of union is the size of the tag field plus the size of the largest
410    option including padding necessary to satisfy its alignment requirements.
411*   Alignment factor of union is defined by the maximal alignment factor of the
412    tag field and any of its options.
413*   Union is padded so that its size is a multiple of its alignment factor.
414    *   e.g. 1. a union with an **int32** and an **int8** option has an
415        alignment of 4 bytes (due to **int32**) and a size of 8 bytes including
416        the 4 byte tag (0 to 3 bytes of padding).
417    *   e.g. 2. a union with a **bool** and a **string** option has an alignment
418        of 8 bytes (due to **string**) and a size of 24 bytes (4 to 19 bytes of
419        padding).
420*   In general, changing the definition of a union will break binary
421    compatibility; instead prefer to extend interfaces by adding new methods
422    which use new unions.
423
424Storage of a union depends on whether it is nullable at point of reference.
425
426*   Non-nullable unions:
427    *   Contents are stored in-line within their containing type, enabling very
428        efficient aggregate structures to be constructed.
429    *   The union layout does not change when inlined; its options are not
430        repacked to fill gaps in its container.
431*   Nullable unions:
432    *   Contents are stored out-of-line and accessed through an indirect
433        reference.
434    *   When encoded for transfer, stored reference indicates presence of union:
435        *   `0` : reference is null
436        *   `UINTPTR_MAX` : reference is non-null,
437            union content is the next out-of-line object
438    *   When decoded for consumption, stored reference is a pointer.
439        *   `0` : reference is null
440        *   `<valid pointer>` : reference is
441            non-null, union content is at indicated memory address
442
443Union are denoted by their declared name (e.g. <strong>Pattern</strong>) and
444nullability:
445
446*   `Pattern` : non-nullable Shape
447*   `Pattern?` : nullable Shape
448
449The following example shows how unions are laid out according to their options.
450
451```
452struct Paint {
453    Pattern fg;
454    Pattern? bg;
455};
456union Pattern {
457    Color color;
458    Texture texture;
459};
460struct Color { float32 r, g, b; };
461struct Texture { string name; };
462```
463
464When laying out **Pattern**, space is first allotted to the tag (4 bytes) then
465to the selected option.
466
467![drawing](unions.png)
468
469### Transactional Messages
470
471*   Transactions consist of sequences of correlated messages sent between the
472    client and implementation of an interface over a Zircon channel.
473*   Each message is prefixed with a simple 16 byte header, the body immediately
474    follows header.
475    *   `zx_txid_t txid`, transaction ID (32 bits)
476        * txids with the high bit set are reserved for use by zx_channel_call
477        * txids with the high bit unset are reserved for use by userspace
478        * See the [channel call] manpage for more details on txid allocation
479    *   `uint32 reserved0`, reserved for future use.
480    *   `uint32 flags`, all unused bits must be set to zero
481    *   `uint32 ordinal`
482        *   The zero ordinal is invalid.
483        *   Ordinals with the most significant bit set are reserved.
484            *   Ordinals 0x80001xxx are "control" messages
485            *   Ordinals 0x80002xxx are "fileio" messages
486*   A non-zero transaction ID is used to correlate sequences of messages which
487    involve a request and a response, e.g. in a two-way method call. The
488    initiator of the request is responsible for assigning a unique transaction
489    ID to the request. The handler of the request is responsible for echoing the
490    transaction ID it received back into the response which it sends. The
491    initiator can reuse transaction IDs once it receives their corresponding
492    responses.
493*   A zero transaction ID is reserved for messages which do not require a
494    response from the other side, e.g. one-way calls or system messages.
495*   There are three kinds of messages: method calls, method results, and control
496    messages.
497*   Ordinals indicate the purpose of the message.
498    *   Ordinals with the most significant bit set are reserved for control
499        messages and future expansion.
500    *   Ordinals without the most significant bit set indicate method calls and
501        responses.
502*   Flags control the interpretation of the message. All unused bits must be set
503    to zero.
504    *   Currently there are no flags, so all bits must be zero.
505
506Messages which are sent directly through Zircon channels have a maximum total
507size (header + body) which is defined by the kernel <em>(currently 64 KB,
508eventual intent may be 16 KB).</em>
509
510It is possible to extend interfaces by declaring additional methods with unique
511ordinals. The language also supports creating derived interfaces provided the
512method ordinals remain unique down the hierarchy. Interface derivation is purely
513syntactic; it does not affect the wire format).
514
515We'll use the following interface for the next few examples.
516
517```
518    interface Calculator {
519        1: Add(int32 a, int32 b) -> (int32 sum);
520        2: Divide(int32 dividend, int32 divisor)
521        -> (int32 quotient, int32 remainder);
522        3: Clear();
523    };
524```
525
526_FIDL does not provide a mechanism to determine the "version" of an interface;
527interface capabilities must be determined out-of-band such as by querying a
528**ServiceProvider** for an interface "version" by name or by other means._
529
530#### Method Call Messages
531
532The client of an interface sends method call messages to the implementor of the
533interface to invoke methods of that interface.
534
535If a server receives an unknown, unsupported, or unexpected method call message,
536it must close the channel.
537
538The message indicates the method to invoke by means of its ordinal index. The
539body of the message contains the method arguments as if they were packed in a
540**struct**.
541
542![drawing](method-call-messages.png)
543
544#### Method Result Messages
545
546The implementor of an interface sends method result messages to the client of
547the interface to indicate completion of a method invocation and to provide a
548(possibly empty) result.
549
550If a client receives an unknown, unsupported, or unexpected method call message,
551it must close the channel.
552
553Only two-way method calls which are defined to provide a (possibly empty) result
554in the FIDL interface declaration will elicit a method result message. One-way
555method calls must not produce a method result message.
556
557A method result message provides the result associated with a prior method call.
558The body of the message contains the method results as if they were packed in a
559**struct**.
560
561The message result header consists of `uint32 txid, uint32_t reserved, uint32
562flags, uint32_t ordinal`.  The `txid` must be equal to the `txid` of the method
563call to which this message is a response. The flags must be zero. The `ordinal`
564must be equal to the `ordinal` of the method call to which this message is a
565response.
566
567![drawing](method-result-messages.png)
568
569#### Event Messages
570
571These support sending unsolicited messages from the server back to the client.
572
573```
574interface Calculator {
575    1: Add(int32 a, int32 b) -> (int32 sum);
576    2: Divide(int32 dividend, int32 divisor) -> (int32 quotient, int32 remainder);
577    3: Clear();
578    4: -> Error(uint32 status_code);
579};
580```
581
582The implementor of an interface sends unsolicited event messages to the client
583of the interface to indicate that an asynchronous event occurred as specified by
584the interface declaration.
585
586Events may be used to let the client observe significant state changes without
587having to create an additional channel to receive the response.
588
589In the **Calculator** example, we can imagine that an attempt to divide by zero
590would cause the **Error()** event to be sent with a "divide by zero" status code
591prior to the connection being closed. This allows the client to distinguish
592between the connection being closed due to an error as opposed to for other
593reasons (such as the calculator process terminating abnormally).
594
595The body of the message contains the event arguments as if they were packed in a
596**struct**, just as with method result messages.
597
598![drawing](events.png)
599
600#### Control Messages
601
602Control messages support in-band signaling of events other than method calls and
603responses.
604
605If a client or server receives an unknown, unsupported, or unexpected control
606message, it must _discard it_. This allows for future expansion of control
607messages in the protocol.
608
609The maximum size of a valid control message is **512 bytes**, including the
610header.
611
612##### Epitaph (Control Message Ordinal 0x80000001)
613
614An epitaph is a message with ordinal **0x80000001** which a client or server
615sends just prior to closing the connection to provide an indication of why the
616connection is being closed. No further messages must be sent through the channel
617after the epitaph.
618
619When a client or server receives an epitaph message, it can assume that it has
620received the last message and the channel is about to be closed. The contents of
621the epitaph message explains the disposition of the channel.
622
623The body of an epitaph is described by the following structure:
624
625```
626struct Epitaph {
627    // Generic protocol status, represented as a zx_status_t.
628    uint32 status;
629
630    // Protocol-specific data, interpretation depends on the interface
631    // associated with the channel.
632    uint32 code;
633
634    // Human-readable message.
635    string:480 message;
636};
637```
638
639TODO: Should we allow custom epitaph structures as in the original proposal? On
640the other hand, making them system-defined greatly simplifies the bindings and
641is probably sufficient for the most common usage of simply indicating why a
642connection is being closed.
643
644![drawing](epitaph.png)
645
646## Details
647
648#### Size and Alignment
649
650`sizeof(T)` denotes the size in bytes for an object
651of type T.
652
653`alignof(T)` denotes the alignment factor in bytes
654to store an object of type T.
655
656FIDL primitive types are stored at offsets in the message which are a multiple
657of their size in bytes. Thus for primitives T_,_ `alignof(T) ==
658sizeof(T)`. This is called <em>natural alignment</em>. It has the
659nice property of satisfying typical alignment requirements of modern CPU
660architectures.
661
662FIDL complex types, such as structs and arrays, are stored at offsets in the
663message which are a multiple of the maximum alignment factor of any of their
664fields. Thus for complex types T, `alignof(T) ==
665max(alignof(F:T))` over all fields F in T. It has the nice
666property of satisfying typical C structure packing requirements (which can be
667enforced using packing attributes in the generated code). The size of a complex
668type is the total number of bytes needed to store its members properly aligned
669plus padding up to the type's alignment factor.
670
671FIDL primary and secondary objects are aligned at 8-byte offsets within the
672message, regardless of their contents. The primary object of a FIDL message
673starts at offset 0. Secondary objects, which are the only possible referent of
674pointers within the message, always start at offsets which are a multiple of 8.
675(So all pointers within the message point at offsets which are a multiple of 8.)
676
677FIDL in-line objects (complex types embedded within primary or secondary
678objects) are aligned according to their type. They are not forced to 8 byte
679alignment.
680
681<table>
682  <tr>
683   <td><strong>types</strong>
684   </td>
685   <td><strong>sizeof(T)</strong>
686   </td>
687   <td><strong>alignof(T)</strong>
688   </td>
689  </tr>
690  <tr>
691   <td>bool
692   </td>
693   <td>1
694   </td>
695   <td>1
696   </td>
697  </tr>
698  <tr>
699   <td>int8, uint8
700   </td>
701   <td>1
702   </td>
703   <td>1
704   </td>
705  </tr>
706  <tr>
707   <td>int16, uint16
708   </td>
709   <td>2
710   </td>
711   <td>2
712   </td>
713  </tr>
714  <tr>
715   <td>int32, uint32
716   </td>
717   <td>4
718   </td>
719   <td>4
720   </td>
721  </tr>
722  <tr>
723   <td>float32
724   </td>
725   <td>4
726   </td>
727   <td>4
728   </td>
729  </tr>
730  <tr>
731   <td>int64, uint64
732   </td>
733   <td>8
734   </td>
735   <td>8
736   </td>
737  </tr>
738  <tr>
739   <td>float64
740   </td>
741   <td>8
742   </td>
743   <td>8
744   </td>
745  </tr>
746  <tr>
747   <td>enum
748   </td>
749   <td>sizeof(underlying type)
750   </td>
751   <td>alignof(underlying type)
752   </td>
753  </tr>
754  <tr>
755   <td>T[n]
756   </td>
757   <td>sizeof(T) * n
758   </td>
759   <td>alignof(T)
760   </td>
761  </tr>
762  <tr>
763   <td>string, string?, string:N, string:N?
764   </td>
765   <td>16
766   </td>
767   <td>8
768   </td>
769  </tr>
770  <tr>
771   <td>vector<T>, vector<T>?,
772<p>
773vector<T>:N,
774<p>
775vector<T>:N?
776   </td>
777   <td>16
778   </td>
779   <td>8
780   </td>
781  </tr>
782  <tr>
783   <td>handle, handle?, handle<H>, handle<H>?,
784<p>
785Interface, Interface?, request<Interface>, request<Interface>?
786   </td>
787   <td>4
788   </td>
789   <td>4
790   </td>
791  </tr>
792  <tr>
793   <td>struct T
794   </td>
795   <td>sum of field sizes and padding for alignment
796   </td>
797   <td>maximum alignment factor among all fields
798   </td>
799  </tr>
800  <tr>
801   <td>struct T?
802   </td>
803   <td>8
804   </td>
805   <td>8
806   </td>
807  </tr>
808  <tr>
809   <td>union T
810   </td>
811   <td>maximum of field sizes and padding for alignment
812   </td>
813   <td>maximum alignment factor among all fields
814   </td>
815  </tr>
816  <tr>
817   <td>union T?
818   </td>
819   <td>8
820   </td>
821   <td>8
822   </td>
823  </tr>
824  <tr>
825   <td>message header
826   </td>
827   <td>16
828   </td>
829   <td>16
830   </td>
831  </tr>
832</table>
833
834#### Padding
835
836The creator of a message must fill all alignment padding gaps with zeros.
837
838The consumer of a message may verify that padding contains zeroes (and generate
839an error if not) but it is not required to check as long as it does not actually
840read the padding bytes.
841
842#### Maximum Recursion Depth
843
844FIDL arrays, vectors, structures, and unions enable the construction of
845recursive messages. Left unchecked, processing excessively deep messages could
846lead to resource exhaustion of the consumer.
847
848For safety, the maximum recursion depth for all FIDL messages is limited to
849**32** levels of nested complex objects. The FIDL validator **must** enforce
850this by keeping track of the current nesting level during message validation.
851
852Complex objects are arrays, vectors, structures, or unions which contain
853pointers or handles which require fix-up. These are precisely the kinds of
854objects for which **encoding tables** must be generated. See [FIDL: C
855Language Bindings](https://fuchsia.googlesource.com/docs/+/master/development/languages/fidl/c.md)
856for information about encoding
857tables. Therefore limiting the nesting depth of complex objects has the effect
858of limiting the recursion depth for traversal of encoding tables.
859
860Formal definition:
861
862*   The message body is defined to be at nesting level **0**.
863*   Each time the validator encounters a complex object, it increments the
864    nesting level, recursively validates the object, then decrements the nesting
865    level.
866*   If at any time the nesting level exceeds **31**, a validation error is
867    raised and validation terminates.
868
869#### Validation
870
871The purpose of message validation is to discover wire format errors early before
872they have a chance to induce security or stability problems.
873
874Message validation is **required** when decoding messages received from a peer
875to prevent bad data from propagating beyond the service entry point.
876
877Message validation is **optional but recommended** when encoding messages to
878send to a peer to help localize violated integrity constraints.
879
880To minimize runtime overhead, validation should generally be performed as part
881of a single pass message encoding or decoding process such that only a single
882traversal is needed. Since messages are encoded in depth-first traversal order,
883traversal exhibits good memory locality and should therefore be quite efficient.
884
885For simple messages, validation may be very trivial, amounting to no more than a
886few size checks. While programmers are encouraged to rely on their FIDL bindings
887library to validate messages on their behalf, validation can also be done
888manually if needed.
889
890Conformant FIDL bindings must check all of the following integrity constraints:
891
892*   The total size of the message including all of its out-of-line sub-objects
893    exactly equals the total size of the buffer that contains it. All
894    sub-objects are accounted for.
895*   The total number of handles referenced by the message exactly equals the
896    total size of the handle table. All handles are accounted for.
897*   The maximum recursion depth for complex objects is not exceeded.
898*   All enum values fall within their defined range.
899*   All union tag values fall within their defined range.
900*   Encoding only:
901    *   All pointers to sub-objects encountered during traversal refer precisely
902        to the next buffer position where a sub-object is expected to appear. As
903        a corollary, pointers never refer to locations outside of the buffer.
904*   Decoding only:
905    *   All present / not-present flags for referenced sub-objects hold the
906        value **0** or **UINTPTR_MAX**.
907    *   All present / not-present flags for referenced handles hold the value
908        **0** or **UINT32_MAX.**
909
910Stricter FIDL bindings may perform some or all of the following additional
911safety checks:
912
913*   All padding is filled with zeroes.
914*   All floating point values represent valid IEEE 754 bit patterns.
915*   All bools have the value **0** or **1**.
916
917<!-- Footnotes themselves at the bottom. -->
918
919## Notes
920
921[channel call]: ../../syscalls/channel_call.md
922
923[^1]: Justification for unterminated strings. Since strings can contain embedded
924    null characters, it is safer to encode the size explicitly and to make no
925    guarantees about null-termination, thereby defeating incorrect assumptions
926    that clients might make. Modern APIs generally use sized strings as a
927    security precaution. It's important that data always have one unambiguous
928    interpretation.
929[^2]: Defining the zero handle to mean "there is no handle" makes it is safe to
930    default-initialize wire format structures to all zeroes. Zero is also the
931    value of the `ZX_HANDLE_INVALID` constant.
932[^3]: New handle types can easily be added to the language without affecting the
933    wire format since all handles are transferred the same way.
934