






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Abstract
Certifying compilation allows a compiler to produce annota- tions that prove that target code abides by a specified safety policy. An independent verifier can check the code without needing to trust the compiler. For such a system to be gen- erally useful, the safety policy should be expressive enough to allow different compilers to effectively produce certifiable code. In this work, we use our experience in writing a certify- ing compiler to suggest general design principles that should allow concise yet expressive certificates. As an extended ex- ample, we present our compiler’s translation of the control flow of Popcorn, a high-level language with function point- ers and exception handlers, to TALx86, a typed assembly language with registers, a stack, memory, and code blocks. This example motivates techniques for controlling certificate size and verification time. We quantify the effectiveness of techniques for reducing the overhead of certifying compilation by measuring the ef- fects their use has on a real Popcorn application, the com- piler itself. The selective use of these techniques, which in- clude common-subexpression elimination of types, higher- order type abbreviations, and selective re-verification, can change certificate size and verification time by well over an order of magnitude. We consider this report to be the first quantitative study on the practicality of certifying a real program using a type system not specifically designed for the compiler or source language.
1 Background
A certifying compiler takes high-level source code and pro- duces target code with a certificate that ensures that the target code respects a desired safety or security policy. To date, certifying compilers have primarily concentrated on producing certificates of type safety. For example, Sun’s javac compiler maps Java source code to statically typed Java Virtual Machine Language (JVML) code. The JVML code includes typing annotations that a dataflow analysis- based verifier can use to ensure that the code is type safe. However, both the instructions and the type system of JVML are relatively high-level and are specifically tailored
∗This material is based on work supported in part by the AFOSR grant F49620-97-1-0013, ARPA/RADC grant F30602-1-0317, and a National Science Foundation Graduate Fellowship. Any opinions, findings, and conclusions or recommendations expressed in this pub- lication are those of the authors and do not reflect the views of these agencies.
to Java. Consequently, JVML is ill-suited for compiling a variety of source-level programming languages to high- performance code. For example, JVML provides only high- level method-call and method-return operations. Also, it provides no provision for performing general tail-calls on methods. Therefore, JVML cannot be used as a target for certifying compilers of functional programming languages such as Scheme that require tail-call elimination. In addition, current platforms for JVML either interpret programs or compile them further to native code. Achieving acceptable performance seems to demand compilation with a good deal of optimization. To avoid security or safety holes, the translation from JVML to native code should also be certifying. That way we can verify the safety of the resulting code instead of trusting a large optimizing compiler. Another example of a certifying compiler is Necula and Lee’s Touchstone compiler [18]. Touchstone compiles a small, type-safe subset of C to high-performance DEC Al- pha assembly language. The key novelty of Touchstone is that the certificate it produces is a formal “proof” that the code is type-correct. Checking the proof for type-correctness is relatively easy, especially when compared to the ad hoc verification process of the JVML. As such, the Touchstone certificates provide a higher degree of trustworthiness. The proofs of the Touchstone system are represented us- ing the general-purpose logical framework LF [8]. The ad- vantage of using LF to encode the proofs is that, from an im- plementation perspective, it is easy to change the type sys- tem of the target language. In particular, the proof checker is parameterized by a set of primitive axioms and inference rules that effectively define the type system. The checker itself does not need to change if these rules are changed. Consequently, the use of LF makes it easy to change type systems to adapt to different source languages or different compilation strategies. Although changing the type system is easy for the imple- mentor, doing so obligates one to an enormous proof burden: Every change requires a proof of the soundness of the type system with respect to the underlying machine’s semantics. Constructing such proofs is an extremely difficult task.
1.1 An Alternative Approach
Our goal is to make it easy for certifying compilers to pro- duce provably type-correct code without having to change the type system of the target language. That way, it suffices to write and trust one verifier for one type system. Toward this end, we have been studying the design and implementa-
tion of general-purpose type systems suitable for assembly language [15, 16, 14]. Ultimately, we hope to discover typ- ing constructs that support certifying compilation of many orthogonal programming language features. Our current work focuses on the design of an extremely expressive type system for the Intel IA32 assembly language and a verifier that we call TALx86 [13]. Where possible, we have avoided baking in high-level language abstractions like procedures, exception handlers, or objects. In fact, the only high-level operation that is a TALx86 primitive is mem- ory allocation. We also have not baked in compiler-specific abstractions such as activation records or calling conven- tions. Rather, the type system of TALx86 provides a num- ber of primitive type constructors, such as parametric poly- morphism, label types, existential types, products, recursive types, etc., that we can use to encode language features and compiler invariants. These type constructors have either been well studied in other contexts or modeled and proven sound by our group. In addition, we and others have shown how to encode a number of important language and compiler features using our type constructors. For example, our encoding of pro- cedures easily supports tail-call optimizations because the control-flow transfers are achieved through simple machine- level jumps. In other words, we did not have to change the type system of TALx86 to support these optimizations. In this respect, TALx86 provides an attractive target for certi- fying compilers.
1.2 The Problem
Unfortunately, there is a particularly difficult engineering tradeoff that arises when a certifying compiler targets a general-purpose type system like TALx86: Encoding high- level language features, compiler invariants, and optimiza- tions into primitive type constructors results in extremely large types and typing annotations — often orders of mag- nitude larger than the code itself. Thus, there is a very real danger that our noble goal of using one general-purpose type system will be defeated by practical considerations of space and time. Some researchers, such as Appel and Felty [1], suggest going even further than we do with respect to minimizing potential soundness errors. In particular, they have recently proposed formally specifying the type system in terms that relate directly to the underlying machine semantics. By em- bedding the policy in a higher-order logical framework, they hope that compilers may define their own type systems and formally prove them sound with respect to the underlying semantics. This work is a promising direction for developing an infrastructure that is truly independent of the source lan- guage and compiler. However, it is clear that an even more primitive approach than ours will only exacerbate the prob- lems with respect to certificate size and verification time. The work presented here is essentially a case study in writing a certifying compiler that targets the general- purpose typed assembly language TALx86. The source lan- guage for our compiler, called Popcorn, shares much of its syntax with C, but it has a number of advanced language features including first-class parametric polymorphism, non- regular algebraic datatypes with limited pattern matching, function pointers, exceptions, first-class abstract data types, modules, etc. Indeed, the language is suitably high-level that we have easily ported various ML libraries to Popcorn
and constructed the certifying compiler for Popcorn in Pop- corn itself. Although the TALx86 type system is very expressive, it is far from a universal typed assembly language. However, we have found that it is expressive enough to allow a rea- sonable translation of Popcorn’s linguistic features. Because the compiler’s invariants are encoded in the primitive typ- ing constructs of TALx86, the most difficult aspect of effi- cient, scalable verification is handling the potentially enor- mous size of the target-level types. We use our experience to suggest general techniques for controlling this overhead that we believe transcend the specifics of our system. The efficacy of these techniques is demonstrated quantitatively for the libraries and compiler itself. In particular, the size of the type annotations and the time needed to verify the code are essentially linear in the size of the object code. In the next section, we give a taxonomy for general ap- proaches to reducing typing annotation overhead and fur- ther discuss other projects related to certifying compilation. Then in Section 3 we summarize relevant aspects of the TALx86 type system, annotations, and verification process. We then show how these features are used to encode the provably safe compilation of the control-flow aspects of Pop- corn, including procedures and exceptions. This extended example demonstrates that an expressive type system can permit reasonable compilation of a language for which it is not specifically designed. It also shows qualitatively that if handled naively, type annotation size becomes unwieldy. In Section 4, we use the example to analyze several approaches that we have examined for reducing type annotation over- head. Section 5 presents the quantitative results of our in- vestigation, where we conclude that the TALx86 approach scales to a medium-size application and that almost all of the techniques contribute significantly to reducing the over- heads of certifying compilation. Finally, we summarize our conclusions as a collection of guidelines for designers of low- level safety policies.
2 Approaches to Efficient Certification
Keeping annotation size small and verification time short in the presence of optimizations and advanced source lan- guages is an important requirement for a practical system that relies on certified code. In this section, we classify some approaches to managing the overhead of certifying compi- lation and discuss their relative merits. None of the ap- proaches are mutually exclusive; any system will probably have elements of all of them.
The “Bake it in” Approach If the type system only sup- ports one way of compiling something, then compilers do not need to write down that they are using that way. For exam- ple, the type system could fix a calling convention and re- quire compilers to group code blocks into procedures. Both the javac and Touchstone compilers use this approach. Baking in assumptions about procedures eliminates the need for any annotations describing the interactions between procedures. However, it inhibits some inter-procedural opti- mizations, such as inter-procedural register allocation, and makes it difficult to compile languages with other control features, such as exception handlers. In general, the “bake it in” approach reflects particular source features into the target language rather than providing low-level constructors suitable for encoding a variety of source constructs.
(although extensions support run-time code generation[9]). In order to investigate the practicality of expressive low-level safety policies, we have relied on a rigorous, informal proof of type soundness and a procedural implementation of the verifier. This approach has allowed us to examine the feasibility of compiler-independent safety policies on a far larger scale than has been previously possible. At the time of this writ- ing, no compiler has targeted the independent safety policies of Appel and Felty. The published results of the Touch- stone project, which does not have a compiler-independent safety policy, do not include object files larger than four kilobytes [18]. More recent work on a Java-specific safety policy has so far compiled only very small programs [11]. In contrast, the data we present in Section 5 is the result of compiling all 39 modules of a real program. The result of compilation is hundreds of kilobytes of object code that link together to form an executable program.
3 Compiling to TALx86: An Extended Example
In this section, we briefly review the structure of the TALx type system, its annotations, and the process of verification. More thorough discussions of the underlying formalism may be found elsewhere [16, 14]. Here, we concentrate on the details relevant to our study. A TALx86 object file consists of Intel IA32 assembly lan- guage instructions and data. As in a conventional assembly language, the instructions and data are organized into la- beled sequences. Unlike conventional assembly language, some labels are equipped with a typing annotation. The typing annotations on the labels of instruction sequences, called code types, specify a typing pre-condition that must be satisfied before control may be transferred to the label. The pre-condition specifies, among other things, the types of reg- isters and stack slots. For example, if the code type annotat- ing a label L is {eax:int4, ebx:S(3), ecx:^[int4,int4] }, then control may only be transferred to the address de- noted by L when the register eax contains a 4-byte integer, the register ebx contains the integer value 3, and the register ecx contains a pointer (ˆ) to a record ([...]) of two 4-byte integers. Verification of code proceeds by taking each labeled in- struction sequence and building a typing context that as- sumes registers have values with types as specified by the pre-condition. Each instruction is then type-checked, in se- quence, under the current set of context assumptions, pos- sibly producing a new context. For most instructions, the verifier automatically infers a suitable typing post condi- tion in a style similar to data-flow analysis or strongest post-conditions. Some instructions require additional an- notations to help the verifier. For example, it is sometimes necessary to explicitly coerce values to an isomorphic type or to explicitly instantiate polymorphic type variables. Not all labels require a typing annotation. However, code blocks without annotations may be checked multiple times under different contexts, depending on the control- flow paths of the program. To ensure termination of verifi- cation, the type-checker requires annotations on labels that are moved into a register, the stack,^1 or data structure (e.g. exception handlers); on labels that are the targets of back- wards branches (e.g. loop headers); and on labels that are
(^1) Return addresses are an important exception; they do not need explicit types.
exported from the object file module (e.g. function entry points.) These restrictions ensure that verification termi- nates. As in a conventional compiler, our certifying compiler translates the high-level control flow constructs of Popcorn into suitable collections of labeled instruction sequences with appropriate low-level control transfers. For present pur- poses, control flow in Popcorn takes one of three forms:
Currently, our compiler only performs intra-procedural optimizations, so the code types for function entry labels are quite uniform and can be derived systematically from the source-level function’s type. For simplicity, we discuss these code types first. We then discuss the code types for labels internal to functions, focusing on why they are more complicated than function entries. We emphasize that the distinction between the different flavors of code labels (func- tion entries, internal labels, exception handlers) is a Popcorn convention encoded in the pre-conditions and is in no way specific to TALx86. (Indeed, we have constructed other toy compilers that use radically different conventions.) In what follows, we present relevant TALx86 constructs as necessary, but for the purposes of this paper, it is sufficient to treat the types as low-level syntax for describing pre- conditions. Our purpose is not to dwell on the artifacts of TALx86 or its relative expressiveness. Rather, we want to give an intuitive feeling for the following claims which we believe transcend TALx86:
Because of this focus, we purposely do not explain some of the aspects of the annotations other than to mention the general things they are encoding. The reader interested in such details should consult the literature[16, 14, 7, 13, 6, 22].
3.1 Function Entry Labels
As a running example, we consider a Popcorn function foo which takes one parameter, an int, and returns an int. The Popcorn type int is compiled to the TALx86 type int4. Arithmetic operations are allowed on values of this type, but treating them as pointers is not. Our compiler uses the standard C calling convention for the IA32. Under this con- vention, the parameters are passed on the stack, the caller pops the parameters, the return address is shallowest on the stack, and the return value is passed in register EAX. All of these specifics are encoded in TALx86 by giving foo this pre-condition:
foo: ∀s:Ts. {esp: {eax:int4 esp: int4::s}::int4::s}
The pre-condition for foo concerns only ESP (the stack pointer) and requires that this register point to a stack that contains a return address (which itself has a pre-condition), then an int4 (i.e. the parameter), and then some stack, s. The return address expects an int4 in register EAX and the stack to have shape int4::s. (The int4 is there because the caller pops the parameters.) The pre-condition is polymor- phic over the “rest” of the stack as indicated by the forall- quantification over the stack-type variable s. This technique allows a caller to abstract the current type of the stack upon entry, and it ensures that the type is preserved upon return. Types in TALx86 are classified into kinds (types of types), so that we do not confuse “standard” types such as int4 with “non-standard” types such as stack types. To maintain the distinction, we must label the bound type variable s with its kind (Ts). Notice that our annotation already includes much more information than it would need to if the safety policy dic- tated a calling convention. In that case, we would presum- ably just give the parameter types and return type of the function. Our annotation does not quite describe the standard C calling convention. In particular, the standard requires EBX, ESI, and EDI to be callee-save. (It also requires EBP, traditionally the frame pointer, to be callee-save. Our com- piler uses EBP for the exception handler.) We encode callee- save registers using polymorphism:^2
foo: ∀s:Ts a1:T4 a2:T4 a3:T4. {esp: {eax:int4 esp: int4::s ebx:a1 esi:a2 edi:a3} ::int4::s ebx:a1 esi:a2 edi:a3}
This pre-condition indicates that for any standard types a1, a2, a3,^3 the appropriate registers must have those types before foo is called and again when the return address is invoked. This annotation restricts the behavior of foo to preserve these registers since it does not know of any other values with these types. Notice that if we wish to use differ- ent conventions about which registers should be callee-saves, then we need only change the pre-condition on foo. In par- ticular, we do not need to change the underlying type system of TALx86. Much more detail is required to encode our compiler’s translation of exception handling, so we just sketch the main ideas. We reserve register EBP to point into the middle of the stack where a pointer to the current exception handler resides. This handler expects an exception packet in register EAX. Since foo might need to raise an exception, its pre- condition must encode this strategy. Also, it must encode that if foo returns normally, the exception handler is still in EBP. We express all these details below, where we use @ an infix operator for appending two stack types.
foo: ∀s1:Ts s2:Ts a1:T4 a2:T4 a3:T4. {esp: {eax:int esp: int4::s1@{esp:s2 eax:exn}::s ebp: {esp:s2 eax:exn}::s ebx:a1 esi:a2 edi:a3} ::int4::s1@{esp:s2 eax:exn}::s2} ebp: {esp:s2 eax:exn}::s ebx:a1 esi:a2 edi:a3} (^2) Here and below, underlining is for emphasis; it is not part of TALx86. (^3) The kind T4 includes all types whose values fit in a register.
We urge the reader not to focus on the details other than to notice that none of the additions are particular to foo, nor would it be appropriate for a safety policy to bake in this specific treatment of exception handlers. Also, we have assumed there is a type exn for exception packets. TALx does not provide this type directly, so our compiler must encode its own representation using an extensible sum[6]. Each of the four occurrences of exn above should in fact be replaced by the typing expression
∃c:Tm ^[(^T^rw(c)[int4^rw])^rw,c]
but in the interest of type-setting, we spare the reader the result. For the sake of completeness, we offer a final amendment to make this pre-condition correct. Our compiler schedules function calls while some heap records may be partially ini- tialized. This strategy is better than the “don’t optimize” approach of always initializing records within a basic block, but it requires that we convince the verifier that no aliases to partially initialized records escape. In particular, the pre- condition for foo uses two capability variables[22], as shown below, to indicate that it does not create any aliases to par- tially initialized records held by the caller and exception handler.
foo:∀s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: {eax:int esp: int4::s1@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::int4::s1@{esp:s2 eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]}
In short, because our compiler has complicated inter- procedural invariants, the naive encoding into TALx86 is anything but concise. (The unconvinced reader is invited to encode a function which takes a function pointer as a pa- rameter.) However, the only parts particular to our example function foo are the return type, which is written once, and the parameter types, which are written twice. Moreover, even these parts are the same for all functions that take and return integer values.
3.2 Internal Labels In this section, we present the pre-conditions for labels that are only targets of intra-procedural jumps. For simplicity, we only discuss labels in functions that do not declare any local exception handlers. This special case is by far the most common, so it is worth considering explicitly. Because our compiler does perform intra-procedural optimizations, most relevantly register allocation, the pre-conditions for internal labels are less uniform than those for function entry labels. Specifically, they must encode several properties about the program point that the label designates:
object types. Here we show how to use higher-order type constructors to define parameterized abbreviations. Such abbreviations can be used to share common patterns that hash-consing of subterms cannot, but for our verifier, it is difficult to exploit abbreviations during verification. Since every function entry pre-condition created by Pop- corn is the same except for its parameter types and return types, we can create a parameterized abbreviation that de- scribes the generic situation. Then at each function entry label, we apply the abbreviation to the appropriate types.
type F = fn params:Ts ret:T4. ∀s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: {eax: ret esp: params@s1@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::params@s1@{esp:s eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]}
foo: F int4::se int
The only new feature other than the abbreviation is the type se which describes empty stacks. We use it here to terminate a list of parameter types. The use of abbreviations greatly simplifies the structure of the compiler because it centralizes invariants such as calling conventions. It is not clear how a compiler-independent verifier could exploit an abbreviation like F during verification. Sup- pose the first instruction in block foo increments the in- put parameter. The verifier must check that given the pre- condition F int4::se int4, it is safe to perform an incre- ment of the value on top of the stack. This verification re- quires inspecting the result of the abbreviation application since the verifier does not know that the argument int4::se describes the top of the stack. As we show in the section on experimental results, using abbreviations sometimes slows down verification because of this phenomenon. The abbreviation F can be used often because all func- tion entry pre-conditions are similar. To use abbreviations for internal labels, we must capture the additional proper- ties that distinguish these pre-conditions. In addition to F’s parameters, we also need parameters for the spill slots, the live registers, and something to do with partial initializa- tion issues. We also use a primitive type constructor (&) for combining two pre-conditions. That way we can pass in the live registers as one pre-condition and merge it with a pre-condition that describes the reserved registers.
type L = fn params:Ts ret:T4 spills:Ts part:Tcap regs:Tpre. ∀s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: spills@a3::a2::a ::{eax: ret esp: params@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::params@{esp:s2 eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s
cap: &[part,e1,e2]} & regs
l: L int4::se int top4::int4::top4::se ce {esi:int4}
L is correct, but it is only useful for labels in functions where all three callee-save values are stored on the stack. With a “don’t optimize” approach, we could make all func- tions meet this description, but we lose most of the advan- tages of callee-save registers as a result. A better approach is to provide 2^3 = 8 different abbreviations, one for each combination of callee-save values being stored on the stack. In fact, we only need four such abbreviations since our reg- ister allocator uses the callee-save registers in a fixed order. Since the compiler is the creator of the abbreviations, this specialization is possible and appropriate.
4.3 Eliding Pre-conditions
Recall that the verifier checks a code block by assuming its pre-condition is true and then processing each instruction in turn, checking it for safety and computing a pre-condition for the remainder of the block. At a control transfer to another block, it suffices to ensure that the current pre- condition implies the pre-condition on the destination label. TALx86 takes a “reconstruction” approach by allowing many label pre-conditions to be elided. Clearly, the result of eliding a pre-condition is a direct decrease in annotation size. To check a control transfer to a block with an elided pre- condition, the verifier simply uses the current pre-condition at the source of the transfer to check the target block. Hence if a block with elided pre-condition has multiple control flow predecessors, it is verified multiple times under (possibly) different pre-conditions. To ensure termination of verification, we must prohibit annotation-free loops in the control flow graph. For this reason, TALx86 allows a pre-condition to be elided only if the block is only the target of forward jumps. Even with this restriction, the number of times a block is checked is the number of paths through the control-flow graph to the block such that no block on the path has an explicit pre- condition. This number can be exponential in the number of code blocks, so it is unwise to elide explicit pre-conditions indiscriminantly. As the next section demonstrates, an ex- ponential number of paths is rare, but it does occur and it can have disastrous effects on verification time. The approach taken by our compiler is to set an elision threshold, T , and insist that no code block is verified more than T times. Notice T = 1 means all merge points have explicit pre-conditions. We interpret T = 0 to mean that all code labels, even those with a single predecessor, have explicit pre-conditions. For higher values of T , we expect space requirements to decrease, but verification time to in- crease. Given a value for T , we might like to minimize the number of labels that have explicit pre-conditions. Unfortu- nately, this problem is NP-Complete for T ≥ 3. Currently, the compiler does a simple greedy depth-first traversal of the control-flow graph, leaving off pre-conditions until the threshold demands otherwise.
5 Experimental Results
In this section, we present our quantitative study of cer- tifying a real program in TALx86. We conclude that tar-
geting compiler-independent safety policies is practical and scalable, but that careful use of appropriate techniques can significantly reduce verification space and time. Our example is the Popcorn compiler itself. This choice saves us the effort of writing a compiler and an application. It also suggests that our application is useful and our source language is realistic. Of course, studying a new applica- tion written by ourselves in our own language makes many comparisons impossible. Since we are more interested in studying the overheads of compiling to expressive low-level safety policies than in producing excellent code, we find this approach attractive. The compiler consists of 39 Popcorn source files compiled separately. The more interesting optimizations performed are Chaitin-style intra-procedural register allocation[4] (us- ing optimistic spilling[3] and conservative coalescing[5]) and the elimination of fully redundant null-checks for object dereferences. The entire compiler is roughly 18,000 lines of source code and compiles to 816 kilobytes of object code (335 kilobytes after running strip). The sizes we report include the sum across files of all annotations, not just those for code labels. They do not include interface information used for type-safe linking. All execution times were measured on a 266MHz Pentium II with 64MB of RAM running Windows NT 4.0. The ver- ifier and assembler are written in Objective Caml[12] and compiled to native code. We first show that naive choices in the annotation lan- guage and compiler can produce a system with unacceptable space and/or time overhead. Then we show that our actual implementation avoids these pitfalls. Next we adjust var- ious parameters and disable various techniques to discover the usefulness of individual approaches and how they inter- act. Finally, we discuss how we could extend our techniques to further lower the TALx86 overhead.
5.1 Two Bad Approaches
A simple encoding of the TALx86 annotations is insufficient. First, consider a system where we do not use the abbrevi- ations developed in Section 4, our type annotations repeat types rather than sharing them, and we put types on all code labels. Then the total annotation size for our program is over 4.5 megabytes, several times the size of the object code. As for verification time, if we make no attempt to share common subterms created during verification, then it takes 59 seconds to verify all of the files. A second possibility is to remove as many pre-conditions as possible. That is, we only put an explicit pre-condition on a code label if the label is used as a call destination, a backwards branch destination, or a first-class value. Indeed, the total size of our annotations drops to 1.85 megabytes. However, the verifier now checks some code blocks a very large number of times. Total verification time rises to 18 minutes and 30 seconds. These two coarse experiments yield some immediate con- clusions. First, the actual amount of safety information de- scribing a compiled program is large. Second, the number of loop-free paths through our application code is, in places, much larger than the size of the code. Therefore, it is un- wise to make verification time proportional to the number of loop-free paths as the second approach does. The latter conclusion is important for certified code frameworks (such as proof-carrying code) that construct ver- ification conditions at verification time via a form of weakest
1
10
1.E+02 1.E+03 1.E+04 1.E+05 1.E+ Total File Size (bytes)
Verification Time (sec)
Figure 1: Verification Time vs. File Size
pre-condition computation [11]. If done naively, the con- structed condition can have exponential size by creating a different logical clause for every loop-free path. For a com- piler to exploit the weakness of such a pre-condition, it would need to have optimized based on an exponential amount of path-sensitive information. We conclude that constructing weakest pre-conditions in this way is impractical and waste- ful.
5.2 A Usable System Having shown how bad matters can get, we now present the actual overhead that our system achieves. First we iden- tify the main techniques used and the overhead that results. Then we show that verification time is roughly proportional to file size; this fact suggests that our approach should scale to larger applications. Finally, we partition the source code into several styles, show that the overhead is reasonable for all of them, and discuss salient differences. Unlike the “straw man” systems constructed above, the real encoding of TALx86 annotations uses several tables to share common occurrences. Specifically, uses of identifiers, types, kinds, and coercions are actually indices into a table that contains the annotation. The code producer can avoid duplicates when constructing the table. The benefit of this approach is proportional to the amount of repetition; there is a small penalty for annotations that occur only once. We call this technique “sharing”; more specifically it is full common subexpression elimination on types at the file level. Since this sharing does not create parameterized abbrevi- ations, we also use the abbreviations developed in Section 3. We set the elision threshold to four. At this value, many forward control flow points will not need explicit pre- conditions, but no block is verified more than four times. Finally, the verifier uses “hash consing” to share types that are created during verification. That is, when creat- ing a new type, the verifier consults a table to see if it has encountered the type previously. If so, it uses the type in the table. Moreover, reductions on higher-order type con- structors are performed in a lazy manner. In particular, we use a weak-head normalization strategy with memoiza- tion to avoid both unnecessary reductions and duplicated reductions. As such, other uses of the type will not have to re-compute the reduction. Because of complications with
Annotation Size (kB) Verification Time (sec) Sharing Abbreviations Uncompressed Compressed No hash consing Hash consing no no 2041 155 50 38 no yes 793 132 42 36 yes no 503 205 37.5 34. yes yes 419 163 40.5 34.
Figure 3: Effect of Abbreviations, Sharing Subterms, and Hash Consing
5.3 Effectiveness of Individual Techniques
We have shown that our system achieves reasonable per- formance and uses a number of techniques for controlling annotation overhead, but we have not yet discussed which of the techniques are effective. In this section, we examine what happens if we selectively disable some of these tech- niques. Figure 3 summarizes the total annotation size when the elision threshold is four and the other techniques are used selectively. We discuss this data in detail below. When “Sharing” is no, we do not use tables for sharing types and coercions. Instead, we repeat the types directly in the an- notations. We still share identifiers so that the lengths of strings is insignificant. If “Abbreviations” is no, then all abbreviations are fully expanded before the annotations are written. “Uncompressed” is the total size of all the anno- tations. “Compressed” is the sum of the result of running gzip on each file’s annotations separately. The final two columns give total execution time with and without hash consing enabled. We first discuss the effect of sharing and abbreviations on the explicit annotation size. Both techniques appear very effective if we ignore the effect of gzip. Abbreviations alone reduce size by a factor of three whereas sharing alone reduces size by a factor of four. Using abbreviations and sharing re- duces size by about another fifteen percent as compared to a system with just sharing. Hence neither technique subsumes the other, but they do recover much of the same repetition. However, if what we really care about is the size of anno- tations that must be sent to a code consumer, then we should consider running gzip. It is clear that gzip is extremely effective; our worst result for compressed annotations is a factor of two better than our best result for uncompressed annotations. More subtle is the fact that gzip achieves a smaller result when sharing is not used in our binary encod- ing. This surprising result is a product of how our tables are implemented and how gzip performs compression. In short, gzip constructs its own tables and uses a much more compact format than our encoding. Worse, our tables hide repetition from gzip which looks for common strings. We conclude that if annotation size is the primary concern, then the binary encoding should remain “gzip-friendly”. Abbreviations are actually much more effective than the data in the figure indicates. The compiler’s abbreviations are only used for code pre-conditions, so optimization on this one aspect of annotation size must eventually demonstrate Amdahl’s Law. We considered what the total annotation size would be if we removed all explicit code pre-conditions. Of course, the result of this drastic measure is unverifiable, but it provides a rough lower bound for the effectiveness of the abbreviations.^6 The total size is still 377 kilobytes,
(^6) Actually, there are a few other places where the abbreviations are used, such as when a polymorphic function is instantiated at a
so abbreviations reduced the size of code pre-conditions by about a factor of three. We now discuss the effect of the techniques on verifi- cation time. Here gzip is useless since our verifier works on uncompressed annotations. Without hash consing, shar- ing significantly reduces verification time. While the verifier under these conditions does not share types that it creates during verification, it does share types that originally oc- cur in the annotations. The result suggests that these types cover many of those used during verification.^7 Without shar- ing, abbreviations are a great help since they recover the most common occurrences. However, with sharing, abbrevi- ations actually hurt verification time. Essentially, the time to expand the abbreviations during verification outweighs the time that the additional sharing gains. With hash consing, the different verification times are much closer to each other. Using a hash-cons table redis- covers any sharing, so without sharing initially we only have to pay the cost to achieve this rediscovery. More interest- ingly, the penalty for using abbreviations goes away. We believe this result is due to the fact that with hash consing, any abbreviation applied to the same argument only needs to be expanded once and then the result can be used in multiple places. Using hash consing reduces verification time significantly, but only with a careful implementation of the hashing. For example, if we give our hash cons table a size near a power of two (as number theory warns against), verification time takes longer than without hash consing at all. The good news is that optimizing the verifier can sometimes be re- duced to fundamental properties of data structures. The bad news is this fact means the difference between verifica- tion times under different parameters is more brittle than we would like. As explained in the previous section, TALx86 code blocks that are only targets of forward branches do not need an- notations, but they will be re-verified along every unanno- tated control-flow path. Given an elision threshold T , our compiler ensures that no block will be verified more than T times. Subject to this constraint, it uses a simple greedy al- gorithm to leave annotations off labels. Figure 4 shows the effect of changing the value of T. Sharing and abbreviations are both used. The left chart in Figure 4 shows that total annotation size drops by over fifteen percent as T is 1 instead of 0. We conclude that low-level systems should not require pre- conditions on all blocks. However, the additional space sav- ings as T is given values larger than 8 are quite small. This fact justifies the use of T = 4 for the other experiments. The other charts in Figure 4 show the verification time for different values of T. Verification time initially drops as
function type, but such situations are exceedingly rare in our code. (^7) Parsing time is a small but noticeable fraction of the difference.
0
100
200
300
400
500
600
(^0124816100) (^100010000) infinity Elision Threshold
Annotation Size (kB)
UncompressedCompressed
0
5
10
15
20
25
30
35
40
45
0 1 2 4 8 16 Elision Threshold
Verification Time (sec) 0
100
200
300
400
500
600
700
800
100 1000 10000 infinity Elision Threshold
Verification Time (sec)
Figure 4: Effect of Elision Threshold
T gets the value 1 instead of 0. This phenomenon indicates that it takes a lot of time to process an explicit annotation and compare it to a pre-condition. As T takes values 2, 4, 8, and 16, verification time rises noticeably but only by a few seconds. We conclude that this range of values allow for different reasonable time-space trade-offs. As T takes larger values, verification time rises sharply. Although very few additional blocks have their pre-conditions elided, these blocks are then checked a very large number of times. In fact, for large T , the time spent verifying different files varies drastically since most files do not have any such blocks.
5.4 Useful Extensions
We have presented a system where uncompressed safety an- notations consume roughly half the space of the object code they describe, and we have given techniques (sharing, ab- breviations, and elision) that help in this regard. Now we investigate whether the current system is the best we can hope to achieve or if the techniques could contribute more to reducing the TALx86 overhead. By moving beyond what the current system supports, we demonstrate the latter con- clusion. First, we notice that sharing common subterms was so effective because it shares type annotations across an entire file. The file level is currently the best we can do because we compile each file separately. In a scenario where all of the object files are packaged together, it may be reasonable to share annotations in a single table for the entire package. Although our current tools cannot process such a package, we are able to generate it by hand and measure its size. The total size drops from 419 kilobytes to 338 kilobytes. We conclude that different files in our project have many similar annotations; we should be able to exploit this property to further reduce overhead. In fact, since this improvement does not rely on understanding the compiler’s conventions, a generic TALx86 tool could put separately compiled object files into a package. Second, the annotations that describe what coercions ap- ply at each instruction are not currently shared. While there are common occurrences in the annotations, some of the most common only take one byte to represent, so sharing these annotations must carefully avoid increasing space re- quirements. Third, verification time suffers significantly from mem- ory allocation and garbage collection. Although we have
implemented hash consing to address this bottleneck, Shao and associates [21] use their experience with type-directed compilers to suggest that suspension-based lambda encod- ing [17] can further improve performance. Unfortunately, modifying our verifier to use these techniques is non-trivial, so we relegate such an investigation to future work. Fourth, some well-chosen uses of type reconstruction could eliminate many of the explicit annotations. For exam- ple, if the verifier performed unification of (first-order) type variables, then the compiler could eliminate all of the type applications at control transfer points. This elision would improve our annotation size to 330 kilobytes. (We com- puted this figure by eliding the instantiations even though the verifier cannot process the result.) More importantly, re- construction approaches improve the size even in the pres- ence of gzip; the compressed annotations drop from 163 kilobytes to 141 kilobytes in this case. In summary, the TALx86 system shows that techniques such as sharing and elision make certified code scalable and practical, but even TALx86 could use these techniques more aggressively to achieve lower overhead.
6 Conclusions
Our Popcorn compiler encodes the safety of its output in TALx86. As a Popcorn application itself, it also serves as the largest application we know of that has been compiled to a safe machine language. Because we believe safety policies should not be tailored to a particular compiler, we encode the aspects of Popcorn compilation relevant to safety in the more primitive constructs of TALx86. We have found that the most important factor in the scalability of certifying compilation is the size of code pre-conditions. Based on our experience, we present the following conclu- sions for compiler-independent low-level code certification systems.