Gillian, Part II: Real-World Veriﬁcation for JavaScript and C

. We introduce veriﬁcation based on separation logic to Gillian, a multi-language platform for the development of symbolic analysis tools which is parametric on the memory model of the target language. Our work develops a methodology for constructing compositional memory models for Gillian, leading to a uniﬁed presentation of the JavaScript and C memory models. We verify the JavaScript and C implementations of the AWS Encryption SDK message header deserialisation module, speciﬁcally designing common abstractions used for both veriﬁcation tasks, and ﬁnd two bugs in the JavaScript and three bugs in the C implementation.


Introduction
Separation logic (SL) [?,44] introduced compositional program verification using Hoare reasoning. Current analysis tools based on ideas from SL include: the automatic tool Infer [10,11] used inside Facebook to find lightweight bugs in Java/C/C++/Obj-C programs; the semi-automatic tool Verifast [28], which provides full verification for fragments of C and Java; the semi-automatic tool JaVerT [24], which provides bug-finding and verification for JavaScript (JS) programs; and the Viper architecture [39,38], which provides a verification backend for multiple programming languages, including Java, Rust, and Python. Our goal is to introduce verification based on SL to Gillian [22], a multi-language platform for symbolic analysis, integrating bug-finding and verification in the spirit of JaVerT and targeting many languages in the spirit of Viper.
Gillian currently supports three types of program analysis: symbolic testing, verification and bi-abduction. In [22], the focus was on symbolic testing, parametrised on complete concrete and symbolic memory models of the target language (TL), and underpinned by a core symbolic execution engine with strong mathematical foundations. Gillian analysis is done on GIL, an intermediate goto language parametric on a set of memory actions, which describe the fundamental ways in which TL programs interact with their memories. To instantiate Gillian to a new TL, a tool developer must: (1) identify the set of the TL memory actions and implement the TL memory models using these actions; and (2) provide a trusted compiler from the TL to GIL, which preserves the TL memory models and the semantics. In [22], Gillian was instantiated to JS and C, and used to find bugs in two real-world data-structure libraries, Buckets.js [?] and Collections-C [?]. Here, we introduce compositional memory models for Gillian, extend Gillian analysis with verification based on separation logic, adapt Gillian-JS and Gillian-C to this compositional setting, and provide verified specifications of the JS and C implementations of the deserialisation module of the AWS Encryption SDK.
The compositional Gillian memory models ( §2) are given by the tool developer for each TL instantiation. They are based on partial memories, and formulated using core predicates and the associated consumer and producer actions. Core predicates describe fundamental units of TL memories: e.g., a property of a JS object and a C block cell. Consumers and producers, respectively, frame off and frame on the TL memory resource described by the core predicates. Partiality and frame are familiar concepts from SL [?, 44,13]. What is perhaps less familiar is our emphasis on negative resource: i.e., the resource known to be absent from the partial memory. For example, in JS, a new extensible object is known not to contain any property; and, in C, a freed block is known not to be in memory and a cell is known not to exist beyond the block bound. We introduce a methodology for designing Gillian compositional memory models, and apply it to JS and C ( §3), resulting in a unexpected similarity between the two models. Our compositional JS memory models follow those given in work on a JS program logic [27] and the JaVerT tool [24], where negative resource was essential for frame preservation, inspired by the use of negative resource to capture stability properties in the CAP concurrent separation logic [17], now used in Iris [29]. Our compositional C memory models are based on the complete CompCert memory model [34]. Despite a large body of work on separation logic for C, we were unable to find a partial C memory model that captures the negative resource in its entirety. The nearest is probably the CH20 formalism [31], which handles freed locations but not block bounds. Negative resource for freed locations has also been used in incorrectness logic [43], and for block bounds in a program logic for WebAssembly [48].
We build Gillian verification on top of our compositional memory models. In particular, using the core predicates, we design an assertion language for writing function specifications in separation logic and, using the consumers and producers, we build a fully parametric spatial entailment engine which enables the use of function specifications in symbolic execution. Gillian also supports user-defined predicates, which allow tool developers to identify the TL language interface familiar to code developers, and code developers to describe and prove properties about the particular data structures in their programs.
We extend Gillian-JS and Gillian-C to enable verification, introducing the JS and C compositional memory models, and using the same trusted compilers as in [22]. With these instantiations, we provide functionally-correct, verified specifications of the message header deserialisation module of the AWS Encryption SDK JS and C implementations ( §4, §5). This is stable, critical, industry-grade code (~200loc for JS,~950loc for C), which uses advanced language features to manipulate complex data structures. To verify this code, we create language-independent predicates to capture the message header, which we then connect without modification to both JS and C memories, giving specifications for the module functions. We also build a library of associated lemmas, used for the verification of both implementations. The verification itself required a substantial improvement of the reasoning capabilities of Gillian, especially when it came to handling arrays of symbolic size. We discovered two bugs in the JS implementation: one a form of prototype poisoning, predicted theoretically in our paper on JaVerT [24]; and another that allowed third parties to potentially alter authenticated, non-secret data. We have also discovered three bugs in the C implementation: one which allowed some malformed headers to be parsed as correct; one over-allocation; and one undefined behaviour. All of these bugs have been fixed.

Gillian Verification
We introduce Gillian verification based on separation logic ( §2.2), extending the GIL execution engine presented in [22] with compositional memory models ( §2.1).

Compositional Memory Models
GIL is a simple goto intermediate language whose syntax is given below. It is parametric on a set of TL memory actions, A α, given per instantiation by the tool developer. GIL values, v ∈ Val , contain numbers, strings, booleans, uninterpreted symbols (used, e.g., to represent memory locations), simple types (e.g., numbers, strings), function identifiers and lists of values. GIL expressions, e ∈ Expr , contain values, program variables, and unary and binary operators (e.g. addition, list concatenation); GIL symbolic expressions,ê ∈Êxpr , are analogous except that symbolic variables,x ∈X , are used instead of program variables.
GIL commands, c ∈ Cmd , contain variable assignment, conditional goto, function call, memory actions, allocation of uninterpreted/interpreted symbols, function return, error termination and path cutting. A GIL function, f (x){c}, comprises an identifier f ∈ F, a formal parameter x 3 , and a body given by a list of commands c. A GIL program is a set of GIL functions with unique identifiers.
GIL execution is defined in terms of state models, which are parametric on a value set, V ⊇ Val , and a set of memory actions, A. We distinguish the Boolean value set, Π ⊂ V, and refer to π ∈ Π as a context. State models expose an interface consisting of state actions, A A S , where the actions
Definition 1 (State Model). A state model, S(V, A) |S|, ea , comprises: a set of states σ = µ, ρ, π ∈ |S|, containing a memory µ, a variable store ρ, and a (satisfiable) context π 4 ; and an action execution function, ea : , with the result r ∈ R = {S, E, M} denoting success, non-correctible error, or missing information error, pretty-printed σ.α(v) → {(σ i , v i ) ri | i∈I } for all outcomes and σ.α(v) (µ i , σ i ) ri for a specific outcome, with countable I. The value set of concrete state models is the set of GIL values, Val 5 ; the value set of symbolic state models is the set of symbolic expressions,Êxpr .
Definition 2 (GIL Execution Semantics). Given a state model S, the GIL execution semantics has judgements of the form: The GIL execution semantics is standard for a goto language, except that it is parametrised by the memory actions. Call stacks capture function-related control flow, with cmd(p, cs, i) denoting the i-th command of the currently executing function (cf. [36] for details).
how the execution is to proceed: S states that it can continue; N(v) states that it terminated normally with return value v; and E(v) and M(v) state that it failed with either a non-correctible or missing information error described by v. We denote configurations, σ, cs, i , by ω and give the rules for memory action execution in Figure 1; all can be found in [36].
Compositional Memory Models. We move from whole-program memory models [22] to compositional memory models by introducing memory core predicates, γ ∈ Γ , which represent the fundamental units of the TL memory model (e.g., a memory cell). Core predicates take two lists of parameters, in-parameters (or ins), denoted v i , and out-parameters (or outs), denoted v o , such that from the ins we can learn the outs. This concept is similar to predicate parameter modes of [40] and we use it to implement a parametric spatial entailment engine. An example of a core predicate is the cell assertion, x → v, which captures a cell in memory at address x having value v. Its in-parameter is x, and its out-parameter is v, because, if we know x, we can find v by looking it up in the memory.
With each core predicate γ ∈ Γ , we associate a consumer and a producer memory action, denoted by cons γ and prod γ respectively, to obtain the set of predicate actions A Γ = γ∈Γ {cons γ , prod γ }, whose meaning is discussed shortly. (2) a well-formedness relation, Wf ⊆ |M | × Π, with Wf π (µ) denoting that memory µ is well-formed in (satisfiable) context π; and (3) a predicate action execution function, ea Γ : πi | i∈I for all outcomes and µ.α(v) π (µ i , v i ) ri πi for a specific outcome, with countable I. The value set of concrete memory models is the set of GIL values, Val ; the value set of symbolic memory models is the set of symbolic expressions,Êxpr .
We discuss the most important properties that the components of compositional memory models must satisfy; a full list is available in [36]. The PCM requirement is well-known from separation logic [44,13]. Well-formedness holds only for satisfiable contexts, and describes the separation of symbolic resource and any further TL-specific well-formedness criteria (cf. §3). It must be monotonic with respect to context strengthening, compatible with the PCM composition, and the empty memory must be well-formed in any satisfiable context. The action execution function, µ.α(v) π → (µ i , v i ) ri πi | i∈I , denotes that, in a memory µ that is well-formed in the context π, executing action α with parameter v yields a countable number of branches characterised by the non-overlapping 7 , satisfiable contexts π i , each of which implies π and makes the corresponding memory µ i wellformed, and all of which together cover π (i.e., π ⇒ i∈I π i ). This last property means that memory actions do not drop paths, which is essential for verification.
The intuition behind consumers and producers is that consumers frame off the core predicate resource (CPR), uniquely determined by the core predicate ins, and the producers frame it on. The following properties capture this intuition. First, we define the CPR of a core predicate γ v i · v o as the memory resulting from its production in 0, which must succeed in any satisfiable context: overloading notation for the core predicate and its resource. Moreover, we require that any successful production frames on the CPR: and also that producers cannot return missing information errors, as they are meant to succeed precisely when the CPR is missing. The consumers, on the other hand, must succeed if and only if the CPR is present in memory: with the resulting context π having enough information to isolate the CPR 8 . Interestingly, erroneous executions cannot be fully characterised in terms of CPR presence or absence, because of TL-specific error cases: for example, in C, attempting to either get or set the value of a block cell that is beyond the block bound raises an out-of-bounds error (cf. §3). What we require instead is that consumed CPR can always be re-produced, that producers fail in a memory in which consumers succeed, and that producers succeed in a memory in which consumers return a missing information error (and vice versa for the latter): The properties given so far allow us, for example, to prove that well-formed memories cannot contain duplicated CPR. The final property below requires that non-missing executions of consumers and erroneous executions of producers must be frame-preserving, with the former formulated as follows: where π effectively maintains well-formedness constraints for µ, adds on further ones required for µ • µ f to be defined and also isolates the consumed CPR. Note that neither missing executions of consumers nor successful executions of producers can be frame preserving, as framing on the appropriate CPR could result in success for the former, and a duplicated resource error for the latter.
Using the consumers and producers, we are able to derive getter and setter actions, A {get γ , set γ : γ ∈ Γ }, which perform frame-preserving CPR lookup and mutation, as given below. We discuss getters and setters further in §3, in the context of our JS and C instantiations.
Compositional State Models. Compositional memory models lift to compositional state models, in a similar way to the lifting of the complete memory models illustrated in [22]; see [36] for details. Here, we focus on memory action execution, which is lifted as follows to state action execution, given a memory model M (V, Γ ) and α ∈ A Γ A: Observe how the context of the state is passed to the memory execution function, which may then strengthen it before passing it back to the resulting state. We can show that the PCM and well-formedness relation on memories lift to a PCM and well-formedness relation on states, and that state action execution maintains properties analogous to those given for memory models.

GIL Verification
We give an overview of Gillian verification based on separation logic (SL); see [36] for details. We describe GIL assertions, parameterised by the core predicates of the TL, define assertion satisfiability in a novel, parametric way using the core predicate producers, and provide a mechanism for using verified function specifications in GIL execution.

GIL Assertion Syntax
A compositional memory model with core predicates Γ induces an SL-assertion language given on the right. GIL memory assertions, p, q ∈ A, are formed using the empty assertion, the separating conjunction, the core predicates, and user-defined predicates, whose names come from a dedicated set, ∆ δ. The empty assertion and the separating conjunction are standard. Core predicate assertions are lifted from memory core predicates. User-defined predicates, introduced by example in §3 and §4, are used by tool developers to characterise the interface of the TL, and by code developers to describe the data structures in their programs. They have in-and out-parameters like core predicates, and can have multiple definitions, separated by a semi-colon. Assertions, P, Q ∈ Asrt , extend memory assertions with pure first-order assertions, π, conflated with Boolean symbolic expressions.
Satisfiability. To define assertion satisfiability, we lift memory consumers and producers from core predicates to memory assertions, denoted by µ.cons θ (p) and µ.prod θ (p), and then to states and arbitrary assertions, denoted by σ.cons θ (P ) and σ.prod θ (P ), using substitutions θ :X → V (extended to symbolic expressions inductively, in the standard way) to map core predicate assertions, with parameters given by symbolic expressions, to the core predicates of the memory model, with parameters given by values. We highlight the successful base case of the memory assertion consumers, where the returned context requires the out-parameters of the assertion to match the ones found in memory: π and the successful consumption of an arbitrary assertion P = p ∧ π: µ , ρ, π .cons θ (p ∧ π) ( µ , ρ, π , true) S Definition 4 (Satisfiability). The satisfiability relation, stating that memory µ and context π satisfy assertion p ∧ π under substitution θ, is defined by: and is lifted to states as: µ , ρ, π , θ |= p ∧ π if and only if µ , π , θ |= p ∧ π.
In Definition 4, the production, when successful, creates the (unique) memory µ p that corresponds to the resource of the assertion p, with its (unique) wellformedness constraints, π p . In the concrete case, as the only allowed context is true, the formulation simplifies to the more intuitive 0.prod θ (p) → (µ , true) S ∧ θ(π).
Specifications. Gillian function specifications have the form {x, P }f (x){Q}ê, where f is the function identifier, x is the function parameter,x is the symbolic variable holding the value of x, P is the pre-condition, Q is the post-condition, and e is the return value of the function, with the following, well-known, constraints: 1. program variables do not appear in the pre-or the post-condition, and the function parameter x is accessed using the symbolic variablex; 2. symbolic variables that appear in a pre-condition are implicitly universally quantified, and can be re-used in the corresponding post-condition; and 3. symbolic variables that appear only in a post-condition are implicitly existentially quantified.
We extend GIL programs with function specifications, accessible via p.specs, and the GIL execution semantics with rules for folding and unfolding user-defined predicates, as well as with a rule for calling function specifications, the success case of which is given below. Gillian verifies a specification {x, P }f (x){Q}ê if, given the identity substitutionθ and a symbolic stateσ with store {x →θ(x)} such thatσ,θ |= P , the symbolic execution of f starting fromσ always terminates, for all final symbolic statesσ i there exists someθ i ≥θ such thatσ i ,θ i |= Q, and the corresponding return value equalsθ i (ê) under the context ofσ i . We can prove that if Gillian verifies a specification, then its standard SL interpretation holds.
Note that for this rule to succeed, the consumption of P must succeed. The rule is slightly simplified for presentation. First, it assumes to have the substitution upfront; in the implementation, we have a unification algorithm that, starting from the function parameter and using the consumers, learns the substitution. Second, it assumes that the post-condition does not introduce fresh symbolic variables; these are handled using allocators and added to the substitution.
Remark. Due to space constraints, we have not been able to give the full technical details of Gillian verification. These are available in the Gillian technical report [36], where we demonstrate that the overall GIL execution using compositional memory models is frame-preserving (up to the usual renaming of allocated memory locations) and prove a soundness result that states that the GIL symbolic execution over-approximates the GIL concrete execution: 9

Compositional Memory Models: JavaScript and C
We present the compositional memory models of JS and C, giving the basic actions and core predicates, and some of the user-defined predicates that capture the intuitive interfaces of these languages. The key ideas behind compositional JS memory models were introduced in the JaVerT project [24,23,25]; we transfer them to Gillian. We introduce the compositional C memory models, building on the concrete block-offset memory model of CompCert [34], simplifying the presentation. 10 In doing so, we highlight a striking similarity between the JS and C models that is the result of our emphasis on negative resource.
The JS and C concrete compositional memory models are made up of building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks building blocks that are assigned a unique location (or identifier) from a set of uninterpreted symbols, L ⊂ U: for JS, the building blocks are the extensible objects; for C, they are the blocks of linear memory of a given size. Compositional memory models must keep track of negative resource, which can come from two sources: allocation and deallocation. For JS and C, the negative information originating from allocation has infinite representation: in JS, a freshly created object is known to not have any properties; in C, a freshly allocated block of a given size in C is known not to have offsets beyond that size. This infinite information is captured, for JS, by the object domain whose meaning is that any property not in the domain is absent, and, for C, by the block bound whose meaning is that any accesses beyond that bound result in a buffer overrun error. The negative information originating from deallocation is easier to handle, tracked by a dedicated uninterpreted symbol, ∅ ∈ U. In JS, deallocation is at the unit level: only object properties are deleted. This is captured by extending the co-domain of property tables with ∅: that is, h : S Val ∅ . In C, deallocation is at the building-block level: only entire blocks can be deleted. This is captured by extending the co-domain of blocks with ∅, indicating that a block has been freed.
Due to compositionality, any building block, component or unit can be missing missing missing missing missing missing missing missing missing missing missing missing missing missing missing missing missing. In the theory, we capture this either implicitly, via absence from the domain of a mapping (e.g., a missing object property for JS or a missing block cell for C), or explicitly, using the symbol ⊥ (e.g. a missing domain, metadata, or bound).
Definition 5 (Compositional JS and C Memories). The PCMs of compositional concrete JS and C memories, |M JS | and |M C |, are given by the sets composition defined as disjoint union, and empty memory ∅. The PCMs of compositional symbolic JS and C memories, |M JS | and |M C |, are given by the setŝ µ ∈ |M JS | :Êxpr ((Êxpr Ê xpr ) ×Êxpr ⊥ ×Êxpr ⊥ ), with composition defined as (syntactic) disjoint union, and empty memory ∅.
In the above definition, symbolic memory models are simple liftings of the concrete ones. In the implementation, we employ heavy optimisation: for example, in Gillian-C, we have developed a complex tree representation of symbolic blocks inspired by [31], enabling tractable reasoning about arrays of symbolic size.
Well-formedness of concrete memories addresses the relationship between positive and negative information, given for JS and C below: Well-formedness of symbolic memories additionally has to address separation of locations and separation in any other mappings with symbolic expressions in its domain (e.g. object properties for JS and offsets for C). We give the well-formedness criterion for the symbolic C memory: Fig. 2: Selected rules for the consCell consumer.
For our JS and C instantiations, the core predicates follow straightforwardly from the units of their memory models.
Definition 6 (JS Core Predicates). JS has three core predicates, γ JS ∈ Γ JS : the object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property object-property predicate, (l,p) →v, which states that propertyp of object at locationl contains valuev ( ), which states that object at locationl has no properties outside the finite setd; the metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata metadata predicate, metadata(l,m), which states that object at locationl has metadatam.
Definition 7 (C Core Predicates). C has three core predicates, γ C ∈ Γ C 11 : - We illustrate the C predicate action execution functions, ea C andêa C , respectively, with a selection of rules for the C cell-predicate consumer, consCell, given in Figure 2. The remaining rules, as well as the rules for their JS counterparts, ea JS andêa JS , can be found in the Gillian technical report [36]. With this information, we can define the compositional concrete and symbolic JS and C memory models. Definition 9 (C Memory Models). The compositional concrete and symbolic C memory models are defined, respectively, as M C (Val , Γ JS ) = |M C |, Wf C , ea C andM C (Êxpr , Γ JS ) = |M C |,Ŵf C ,êa C .
The getters and setters for JS and C are defined using the methodology described in §2. In particular, the JS getters and setters are given by A JS = {getProp, setProp, getDomain, setDomain, getMetadata, setMetadata}, and the summary of the execution of the symbolic getProp(l,p) getter is illustrated below: Similarly, the C getters and setters are given by A C = {getCell, setCell, getBound, setBound, getFreed, setFreed} and the summary of the execution of the symbolic getCell(l,ô) getter is illustrated below: The similarities in the two diagrams are evident, with the main difference being that JS getters do not throw errors, whereas C getters do.
User-defined JS and C Predicates. Core predicates describe fundamental units of the TL memory model. On top, user-defined predicates build layers of abstraction to describe memory components and building blocks, standard library interfaces, all the way to complex data structures for particular code such as the AWS message header. Using Gillian notation, we present some of the JS and C user-defined predicates; in this notation: * and ∧ are conflated to * , with automatic differentiation between spatial and pure assertions 12 ; predicate definitions are separated with a semi-colon; and logical variables are prefixed with the # symbol and are implicitly existentially quantified in predicate definitions.
Gillian-JS inherits many user-defined predicates from JaVerT [24], including simple ones for describing JS objects and their properties, as well as advanced ones for specifying scoping, function closures and prototype chains. We focus here on the new FrozenObject(o, proto, pvs) predicate, which describes a frozen object 13 o with prototype proto and property-value pairs pvs. We first define the predicate FrozenObjectProps(o, pvs) to grab the resource of the object properties: where DataPropConst(o, #p, #v) states that the object o has a non-writable property #p with value #v. We then add information about the object prototype and its non-extensibility using the JSObject(o, proto, ext) predicate, and also state that the object has no properties other than pvs using the domain core predicate: where FirstProj(pvs, #ps) means that the list #ps is the first projection of the list of pairs pvs, and ListToSet(#ps, #pss) means that the elements of the list #ps form the set #pss. Gillian-C, on the other hand, comes with user-defined predicates capturing, for example, arrays and blocks in memory, as well as automatically-generated predicates describing C structs, with support for nested structs. In particular, the array(b, off, c) predicate describes a contiguous fragment of a block b, starting from offset off, with contents described by the mathematical list c: In the implementation, arrays also exist as core predicates. This allows us to reason about arrays automatically in the symbolic memory (e.g., to split an array into sub-arrays), supported by our tree representation of symbolic blocks, instead of requiring manual application of lemmas. Finally, we illustrate automatically generated struct-related predicates using the aws_byte_cursor structure given below, which contains two fields: an unsigned integer len; and a nullable pointer to an array of 8-bit unsigned integers buf. This struct is used for traversing the AWS message header (cf. §4), and is intended to capture an array in memory that starts at buf and has length len. The generated predicate describes the struct's layout in memory and gives basic typing information: it states that an aws_byte_cursor, starting from the position given by the pointer cur, occupies 16 bytes in memory (8 + 8, given by the type annotation int64), with the first 8 bytes taken by len, and the second 8 bytes (note the pointer addition +p) taken by buf, which is either a pointer or null.

AWS Encryption SDK Message Header Specification
The encrypted data handled by the AWS Encryption SDK is stored within a structure called a message [3]. The message format has two versions of similar complexity: we verify version 1; version 2 was introduced very recently. Messages consist of a header, a body, and a footer. Here, we describe only the structure of the header, as we are verifying header deserialisation. The AWS Encryption SDK message header is a sequence of bytes (buffer) divided into sections, as illustrated below; above each section is its length in bytes.
Our approach is to abstract the header contents into a list and formulate pure predicates that describe its structure in a language-independent way. This allows us to then use the same abstractions as part of further, language-dependent, abstractions for both JS and C. Our design of the abstractions was informed by existing code annotations found in the implementations, which describe simple first-order properties of the code and, in the case of C, can also link to the CBMC [32] bounded model checker. However, these annotations are limited by the expressivity of JS and C, particularly when it comes to reflecting on the memory contents. Our predicates have no such limitations.
We narrow down our exposition to the encryption context, as it illustrates well the language-independent and language-dependent aspects of our specification, and is also the section in which we discovered bugs in both implementations.
Pure Specification of the Encryption Context. The encryption context (EC) is a sequence of bytes that describes a set of key-value pairs. Its structure is given in the diagram below.
The first two bytes represent the number of key-value pairs, denoted by KC, and the rest describe the KC key-value pairs themselves. Keys and values are represented by sequences of bytes and, as they are of variable length, are serialised by first having two bytes that represent the length, followed by that many bytes of the actual key or value; we refer to this pattern as a field, and to a sequence of n fields as an n-element. Then, a key-value pair is serialised as a 2-field element, and all of the key-value pairs form a sequence of KC 2-field elements.
We specify the EC by building layers of abstraction, from fields to elements to element sequences to the EC, each of which can either be complete, incomplete (partial, but with correct structure), or malformed (with incorrect structure). In the implementation, these are specified separately and are joined together in appropriate over-arching abstractions. Here, we focus on complete variants only.
The Field(buf, pos, fld, len) predicate states that the buffer (list of bytes) buf, at index pos, holds a field with contents fld (list of bytes) and total length len: pred Field(buf, pos, fld, len) : (0 <= pos) * (#rFL = sub(buf, pos, 2)) * UInt16(#rFL, #fL) * (fld = sub(buf, pos+2, #fL)) * (len = 2+#fL) * (pos+len <= |buf|) This predicate uses the GIL operator sub(l, s, n), which returns the sublist of list l starting from index s and of length n, and also the UInt16(rn, n) predicate, which states that n is a 16-bit big-endian interpretation of the raw 2-byte list rn. The Element(buf, pos, fC, elem, len) predicate states that buffer buf at index pos holds a sequence of fC fields, with contents elem (a list of the appropriate field contents) and total length len. It is defined similarly to a standard linked-list predicate, with the 'link' being the fact that the list members are contiguous in memory: Next, analogously to Element, we define the Elements(buf, pos, eC, fC, elems, len) predicate, which states that the buffer buf, at index pos, holds a sequence of eC elements, each with fC fields, with contents elems (a list of the appropriate element contents) and of total length len. Finally, the EncryptionContext(buf, KVs) predicate states that the entire buffer buf is an EC with key-value pairs KVs, with all keys being unique: Next, we show how this pure specification of the EC contents can be connected without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification without modification to both the JS and C memories.
Encryption Context in JS. In JS, the EC is serialised as an ArrayBuffer, which is a raw binary data buffer in memory, and accessed using a Uint8Array, which is a view on top of that ArrayBuffer starting from a given offset and of a given length, treating the raw data underneath as 8-bit unsigned integers. This Uint8Array view is similar in function to the aws_byte_cursor C structure (cf. §3). Abstracting ArrayBuffer contents to lists, we connect these data structures in JS memory to our pure EC specification (cf. Figure 3, top and centre): pred JSSerEC(o, EC, KVs) : Uint8Array(o, #aBuf, #off, #len) * ArrayBuffer(#aBuf, #data) * (EC = sub(#data, #off, #len)) * EncryptionContext(EC, KVs) Fig. 3: Serialised Encryption Context: language-independent pure part (red; middle) and language-specific resource (green; JS above, C below) In JS, the EC is deserialised into a frozen JS object with prototype null, whose properties represent the keys and hold the values. This is done by converting the keys and the values to UTF-8 strings, and is specified as follows: Finally, the specification of the decodeEncryptionContext function states that the EC deserialisation is performed correctly.
Encryption Context in C. In C, the EC is serialised as a block in memory, and is traversed using an AWS byte cursor. Using the auto-generated predicate given in §3, we define the aws_byte_cursor(cur, buf, c) predicate, stating that cur points to a byte cursor which has access to an array starting from buf, and holding contents c, making the length implicit: A serialised EC can then be described as a valid byte cursor whose contents represent the EC key-value pairs (cf. Figure 3, centre and bottom): In C, the EC is deserialised into an AWS hash table, whose keys and values directly correspond to the key/value pairs of the EC, specified as follows, eliding the internal structure of the hash tables due to space constraints: The specification of the EC deserialisation function is more complex than for JS. In particular, the byte cursor that originally pointed to the EC ends up shifted to the end of the byte buffer, exposing the array underneath the CSerEC predicate.

AWS Encryption SDK Message Header Verification
Using Gillian-JS and Gillian-C, together with the specifications given in §4, we verify full functional correctness of the header deserialisation module of the AWS Encryption SDK JS [2] (~200loc) and C [1] (~950loc) implementations. In particular, we verify that the deserialisation of a complete header is correct, and the deserialisation of an incomplete or a malformed header raises an appropriate error.
Verification Effort and Performance. The JS verification took 3 personmonths and the C verification took 2 person-months, with the latter taking less time because a large part of the infrastructure developed for JS could be re-used. We substantially improved the first-order solver of Gillian to reason automatically about complex operations on lists of symbolic length, first used in the modelling of JS ArrayBuffers and then for C dynamic arrays. We created a collection of language-independent predicates and lemmas about their inductive properties (~1.2kloc) that cover the project-specific AWS header, but also reusable first-order concepts such as list element uniqueness, projections of lists of pairs, conversion from bytes to numbers, and conversion from raw bytes to strings. Similarly, we also had to create language-dependent abstractions and associated lemmas for the JS and C manipulation of the AWS message header (~1.2kloc). Finally, we had to: annotate the code with specifications and loop invariants, with the latter often having more than twenty components; manually apply lemmas to prove numerous complex entailments; and manually unfold user-defined predicates at times (the folding is automated) (~1.1kloc). On a machine with an Intel Core i7-4980HQ CPU 2.80 GHz, DDR3 RAM 16GB, and a 256GB solid-state hard-drive running macOS, the JS verification takes approximately 45 seconds and the C verification takes approximately six minutes. The C time is longer, in part due to the larger codebase, but mainly due to the complexity of the implementation of the full C memory model, which is able to reason about arrays of symbolic size. This requires frequent satisfiability checks and (for the moment) branching on non-zero array size. These times could both be improved with the implementation of basic merging techniques.
JS Verification: Bugs/Improvements. We discovered two bugs and improved one function implementation to link better with the underlying data structure.
-In the decodeEncryptionContext function, the object representing the deserialised EC originally had prototype Object.prototype which, in this case, due to the prototype inheritance of JavaScript, meant that if an EC key coincided with a property of Object.prototype, an error would be thrown incorrectly. This bug was predicted theoretically in [24], and has since been found in several real-world libraries [45], including cash and jQuery. -In the same function, in one of the branches the deserialised EC was returned non-frozen, which constituted a potential vulnerability in that third parties could alter non-secret, but authenticated data. -The readElements(eC, fC, buf, pos) function, which reads eC elements with fC fields from buffer buf at index pos into a JS array of arrays, was misaligned with the underlying data structures. Its parameters were non-intuitive (it received eC · fC, buf, and pos), and used complex array operations to re-form the final return value. We re-implemented this function to construct the returned array of arrays efficiently, simplifying specification and verification, and our implementation was integrated into the codebase.
JS Verification: Caveats. Our JS verification is correct up to the following caveats. First, as the AWS SDK JS implementation is written in TypeScript, we elide types to obtain JS; this could be automated, potentially generating predicates from the types. Next, some ES6 features, such as patterns in function parameters, are not yet supported by Gillian-JS; these we rewrite to ES5 Strict, preserving their meaning. Next, we use axiomatic specifications of the ArrayBuffer, DataView, and UInt8Array ES6 built-in libraries, as well as of the Object.freeze and Array.prototype.map built-in functions. These would ideally be accompanied with implementations, tested against the official Test262 test suite [19] and verified against their specifications. Finally, as Gillian does not support higher-order reasoning, we axiomatise the toUtf8 function, passed into the deserialisation module as a parameter, as an injective function from raw bytes to JS strings.
C Verification: Bugs. We discovered three bugs: one logical error; one undefined behaviour; and one over-allocation.
-The deserialisation of the EC mishandled the case when there is not enough data to read it entirely, continuing to read the EDK instead of reporting an error. This allows some malformed headers to be parsed as well-formed. -The function aws_byte_cursor_advance called with a NULL cursor and a length of 0 resulted in NULL + 0 being computed, which is undefined behaviour, although it is not problematic for most compilers. -The deserialised EC was stored using aws_string, which extends C strings with certain metadata. It is implemented using a structure that includes a flexible array member. We discovered that string creation over-allocated this array by 8 bytes, because our (correct) predicate describing aws_strings was not allowing verification to go through.
C Verification: Caveats. Our C verification is correct up to the following caveats. First, we do not use the aws_byte_cursor_advance_nospec function, which advances the byte cursor, but also uses complex computation to protect against the Spectre bug. We instead use aws_byte_cursor_advance, which has equivalent behaviour. In any case, our specifications are not expressive enough to capture this distinction. Next, we axiomatise the functions of the AWS hash tables and array list libraries, as their verification is of comparable complexity to the entire deserialisation module. Finally, the AWS allocators of the C implementation, which are passed into some of the functions, contain pointers to memory management functions; this is higher-order in nature. In the verification, we assume those functions are malloc, calloc, and realloc.

Related Work
The literature explores many techniques and tools for verifying JS [46,21,25,24] and C [26,28,30,16,9]. We describe: multi-language verification architectures; JS and C verification tools based on separation logic; C memory models related to our models; and other analyses applied to the AWS Encryption SDK.
Multi-Language Verification Architectures. The multi-language verification architectures closest to Gillian are coreStar [8] and Viper [39,38]. Both of these architectures were designed to serve as verification back-ends for TLs and both have at their core a simple intermediate representation with a dedicated symbolic execution engine 14 . However, they work with the TL in different ways.
In coreStar, TL core assertions are modelled as abstract predicates and memory actions as function calls. The function specifications play the role of our consumer and producer actions. The user also has to provide logical axioms, describing properties of the abstract predicates. The Gillian equivalent of these axioms are the implementations of the memory actions using consumers and producers, which can be optimised, but require understanding of the inner workings of Gillian. Like Gillian, coreStar's symbolic execution engine is parametric on the underlying logical theory and can thus be used to reason about any memory model representable using abstract predicates. It is, however, unclear how efficiently this can be done. coreStar has been used inside the tool jStar [18], which has verified implementations of several Java design patterns but was not pushed to more complex Java code. In [24], the authors observed that coreStar was not able to handle tractably even simple JS programs.
Unlike Gillian and coreStar, Viper [39,38] comes with a fixed, intermediate language, also called Viper. The user encodes their memory model and corresponding core assertions into the memory model and assertion language of Viper. A key advantage of Viper lies in its expressive permission model, which includes fractional, recursive, and abstract read permissions, as well as in its support for custom mathematical domains enabling users to extend Viper with their own first-order theories, tailored to the data structures at hand. Viper has mechanisms similar to our consumer and producer actions, called inhale and exhale. Viper can reason about both sequential and concurrent programs, and has been used to verify programs written in Java, Go, Rust, and Python, but not JS and C. In fact, it is not clear to us how difficult it would be to use Viper to reason about JS objects and the linear memory of C, as neither can be simply expressed using the static objects natively provided by Viper.
Semi-automatic Verification Tools for JS and C. There are few verification tools for JS based on separation logic. For example, JaVerT [24] has been used to verify simple data-structure algorithms. Its successor, JaVerT 2.0 [25], provides whole-program symbolic testing, verification and bi-abductive reasoning [12], unified by a core symbolic execution engine. JaVerT 2.0 verification is more efficient than JaVerT verification, but was still only applied to simple data-structure algorithms. Gillian [22] builds on JaVerT 2.0, taking the highly non-trivial step of designing the intermediate language, correctness results, and implementation to be parametric on the TL memory models. Despite this generalisation, Gillian substantially outperforms JaVerT 2.0, both for symbolic testing [22] and for verification.
Verifast [28] and the tool in [9] are prominent examples of semi-automatic tools that provide functionally-correct verification of C programs using separationlogic specifications. These tools work with C fragments and simplified memory models. While the tool in [9] has not been applied to real-world code, Verifast has been used to verify, e.g., an implementation of a Policy Enforcement Point (PEP) for Network Admission Control scenarios [42]. One difference between these tools and Gillian is that Gillian specifications can express negative resource, allowing us to differentiate missing resource errors from use-after-free errors. On the other hand, Verifast, unlike Gillian, supports reasoning about concurrent programs. There is also much work on using theorem provers to verify both sequential and concurrent C code using separation logic: see, for example, the DeepSpec project [?] and the Iris project [?], which we do not describe here.
Related Formal C Memory Models. Our compositional C memory models arose from several sources. Our concrete C model is adapted from the complete model of CompCert [35], which supports reasoning about programs that access in-memory data representations. This feature is used by the AWS deserialisation algorithm, which reads the buffer contents at the byte-granularity.
We present our compositional symbolic C memory model in this paper as a simple lifting of the concrete one. Our implementation is more complex, representing blocks as trees holding symbolic values, combining the concepts of memory trees and abstract values from the concrete memory model of the CH2O formalisation [31], which is one of the most detailed formal memory models for C. Although not mentioned in [31], the CH2O formalisation does keep track of some negative resource in that it maintains freed locations, but not block bounds.
Analysis of the AWS Encryption SDK. Amazon has recently directed considerable effort towards the formal analyses of their codebase, with a number of tools incorporated into their CI pipeline. For example, the main cryptographic algorithms of the AWS Encryption SDK have certified implementations in the specification language Cryptol [20], underpinned by SAW [15]. These implemen-tations, however, have not yet been proven equivalent to the corresponding C implementation. In addition, the C implementation of the AWS Encryption SDK includes a symbolic test suite run using CBMC [32]. This implementation makes heavy use of the aws-c-common data-structure library, which is annotated with first-order assertions checked by CBMC. CBMC is a mature, industrial-strength tool, likely to outperform and have broader coverage than the symbolic testing of Gillian-C, with substantially fewer annotations than Gillian verification. However, as CBMC is a bounded model checker, it provides weaker correctness guarantees and is not compositional. Its expressivity is also somewhat constrained by the expressivity of the C runtime. For example, it does not allow reasoning about the size of allocated memory. Gillian specifications have this expressivity, as highlighted by the discovered over-allocation bug. The subtle logical bug found by Gillian also demonstrates the importance of being able to express full, functionally-correct specifications. We believe there has been no previous analysis of the JS implementation of AWS Encryption SDK.

Conclusions
We have introduced compositional verification to the Gillian platform. Our work includes a methodology for designing compositional TL memory models, distinguishing negative resource from missing resource and using the JS and C memory models as demonstrator examples. It also includes a novel, parametric approach to assertion interpretation, independent of the TL, enabling compositional use of function specifications in verification. We have been able to push the Gillian verification to self-contained, critical, real-world AWS JS and C code. The bugs and suggestions for code improvements that arose during this verification process have all been accepted by the developers and incorporated into the codebase. To our knowledge, this is the first time that industry-grade JS code has been fully verified and the first time that, in one verification platform, the same abstractions were used to verify industry code from languages as different as JS and C. The artifact accompanying this paper can be found at [37], and the entire Gillian development at [47]. In future, we will publish correctness results for Gillian verification [36], as part of a broader study of program correctness and incorrectness for the symbolic execution, specification, and bi-abduction modules of Gillian.