# Changeset 2087 for src/ASM

Ignore:
Timestamp:
Jun 15, 2012, 11:40:25 AM (9 years ago)
Message:

Tidied up the paper, added a few more things, tidied and expanded bibliography.

Location:
src/ASM/CPP2012-asm
Files:
2 edited

### Legend:

Unmodified
 r2083 \title{On the correctness of an optimising assembler for the Intel MCS-51 microprocessor\thanks{The project CerCo acknowledges the financial support of the Future and Emerging Technologies (FET) programme within the Seventh Framework Programme for Research of the European Commission, under FET-Open grant number: 243881}} \author{Dominic P. Mulligan \and Claudio Sacerdoti Coen} \institute{Dipartimento di Scienze dell'Informazione, Universit\'a di Bologna} \institute{Dipartimento di Scienze dell'Informazione,\\ Universit\'a di Bologna} \bibliographystyle{splncs03} Assembly language programs can manipulate concrete addresses in arbitrary ways. Our proof strategy contains a tracking facility for good addresses' and only programs that use good addresses have their semantics preserved under assembly. Our strategy offers increased flexibility over the traditional approach of keeping addresses in assembly opaque. Our strategy offers increased flexibility over the traditional approach to proving the correctness of assemblers, wherein addresses in assembly are kept opaque and immutable. In particular, we may experiment with allowing the benign manipulation of addresses. \end{abstract} As a result our C compiler, to have any sort of hope of successfully compiling realistic programs for embedded devices, ought to produce tight' machine code. In order to do this, we must solve the branch displacement' problem---deciding how best to expand jumps to labels in assembly language to machine code jumps. Clearly a correct but efficient strategy would be to expand all unconditional jumps to the MCS-51's \texttt{LJMP} instruction, and all conditional jumps to a set configuration of jumps using \texttt{LJMP} instructions; this is inefficient. Finding an efficient solution with this expansion process is not trivial, and is a well-known problem for those writing assemblers targetting RISC architectures. Branch displacement is not a simple problem to solve and requires the implementation of an optimising assembler. In order to do this, we must solve the branch displacement' problem---deciding how best to expand pseudojumps to labels in assembly language to machine code jumps. Clearly a correct but efficient strategy would be to expand all unconditional pseudojumps to the MCS-51's \texttt{LJMP} instruction, and all conditional pseudojumps to a set configuration of jumps using \texttt{LJMP} instructions; this is inefficient and a waste of valuable code memory space. Finding an efficient solution with this expansion process is not trivial, and is a well-known problem for those writing assemblers targetting RISC architectures (for instance, see~\cite{holmes:branch:2006}). To free the CerCo C compiler from having to consider complications relating to branch displacement, we have chosen to implement an optimising assembler, whose input language the compiler will target. Labels, conditional jumps to labels, a program preamble containing global data and a \texttt{MOV} instruction for moving this global data into the MCS-51's one 16-bit register all feature in our assembly language. We simplify the proof by assuming that all our assembly programs are pre-linked (i.e. we do not formalise a linker). We simplify the proof by assuming that all our assembly programs are pre-linked (i.e. we do not formalise a linker---this is left for future work). Further, we must make sure that the assembly process does not change the timing characteristics of an assembly program for two reasons. This is achieved by means of dependent types: the assembly function is total over a program, a policy and the proof that the policy is correct for that program. Policies do not exist in only a limited number of circumstances: namely, if a pseudoinstruction attempts to jump to a label that does not exist, or the program is too large to fit in code memory, even after shrinking jumps according to the best policy. Policies do not exist in only a limited number of circumstances: namely, if a pseudoinstruction attempts to jump to a label that does not exist, or the program is too large to fit in code memory, even after shrinking jumps according to the policy. The first circumstance is an example of a serious compiler error, as an ill-formed assembly program was generated, and does not (and should not) count as a mark against the completeness of the assembler. Our emulator centres around a \texttt{Status} record, describing the microprocessor's state. This record contains fields corresponding to the microprocessor's program counter, registers, and so on. At the machine code level, code memory is implemented as a compact trie of bytes, addressed by the program counter. At the machine code level, code memory is implemented as a compact trie of bytes addressed by the program counter. We parameterise \texttt{Status} records by this representation as a few technical tasks manipulating statuses are made simpler using this approach, as well as permitting a modicum of abstraction. \end{lstlisting} %The function \texttt{execute} allows one to execute an arbitrary, but fixed (due to Matita's normalisation requirement) number of steps of a program. The function \texttt{execute\_1} closely matches the operation of the MCS-51 hardware, as described by a Siemen's manufacturer's data sheet. The function \texttt{execute\_1} closely matches the operation of the MCS-51 hardware, as described by a Siemen's manufacturer's data sheet (specifically, this one~\cite{siemens:2011}). We first fetch, using the program counter, from code memory the first byte of the instruction to be executed, decoding the resulting opcode, fetching more bytes as is necessary. Decoded instructions are represented as an inductive type, where $\llbracket - \rrbracket$ denotes a vector: Decoded instructions are represented as an inductive type, where $\llbracket - \rrbracket$ denotes a fixed-length vector: \begin{lstlisting} inductive preinstruction (A: Type[0]): Type[0] := Once decoded, execution proceeds by a case analysis on the decoded instruction, following the operation of the hardware. For example: For example, the \texttt{DEC} instruction (decrement') is implemented as follows: \begin{lstlisting} \label{subsect.assembly.code.semantics} An assembly program is a list of potentially labelled pseudoinstructions, bundled with a preamble consisting of a list of symbolic names for locations in data memory. An assembly program is a list of potentially labelled pseudoinstructions, bundled with a preamble consisting of a list of symbolic names for locations in data memory (i.e. global variables). Pseudoinstructions are implemented as an inductive type: \begin{lstlisting} Execution of pseudoinstructions is a function from \texttt{PseudoStatus} to \texttt{PseudoStatus}. Both \texttt{Status} and \texttt{PseudoStatus} are instances of a more general type parameterised over the representation of code memory. The more general type will be crucial to share most of the semantics of the two languages. The more general type is crucial for sharing the majority of the semantics of the two languages. Emulation for pseudoinstructions is handled by \texttt{execute\_1\_pseudo\_instruction}: The costing returns \emph{pairs} of natural numbers because, in the case of expanding conditional jumps to labels, the expansion of the true branch' and false branch' may differ in execution time. The \texttt{ticks1} function we already seen used to increment the machine clock is determined, for the assembly language, from the costing function. It is instead fixed and precomputed for machine code. The \texttt{add\_ticks1} function, which we have already seen used to increment the machine clock above, is determined for the assembly language from the costing function. Execution proceeds by first fetching from pseudo-code memory using the program counter---treated as an index into the pseudoinstruction list. Each of these three instructions expects arguments in different sizes and behaves in markedly different ways: \texttt{SJMP} may only perform a local jump'; \texttt{LJMP} may jump to any address in the MCS-51's memory space and \texttt{AJMP} may jump to any address in the current memory page. Consequently, the size of each opcode is different, and to squeeze as much code as possible into the MCS-51's limited code memory, the smallest possible opcode that will suffice should be selected. This is a well known problem to assembler writers who target RISC architectures. Similarly, a conditional pseudojump must be translated potentially into a configuration of machine code instructions, depending on the distance to the jump's target. The input \texttt{pi} is the pseudoinstruction to be expanded and is found at address \texttt{ppc} in the assembly program. The policy is defined using the two functions \texttt{sigma} and \texttt{policy}, of which \texttt{sigma} is the most interesting. The function $\sigma$ maps pseudo program counters to program counters: the encoding of the expansion of the pseudoinstruction found at address \texttt{a} in the assembly code should be placed into code memory at address \texttt{sigma(a)}. The function \texttt{sigma} maps pseudo program counters to program counters: the encoding of the expansion of the pseudoinstruction found at address \texttt{a} in the assembly code should be placed into code memory at address \texttt{sigma(a)}. Of course this is possible only if the policy is correct, which means that the encoding of consecutive assembly instructions must be consecutive in code memory. \begin{displaymath} Note that the entanglement we hinted at is only partially solved in this way: the assembler code can ignore the implementation details of the algorithm that finds a policy; however, the algorithm that finds a policy must know the exact behaviour of the assembly program because it needs to predict the way the assembly will expand and encode pseudoinstructions, once fed with a policy. A companion paper to this one~\cite{boender:correctness:2012} certifies an algorithm that finds branch displacement policies for the assembler described in this paper. A companion submission to this one~\cite{boender:correctness:2012} certifies an algorithm that finds branch displacement policies for the assembler described in this paper. The \texttt{expand\_pseudo\_instruction} function uses the \texttt{sigma} map to determine the size of jump required when expanding pseudojumps, computing the jump size by examining the size of the differences between program counters. By total correctness', we mean that the assembly process never fails when provided with a correct policy and that the process does not change the semantics of a certain class of well behaved assembly programs. The aim of this section is to prove the following informal statement: when we fetch an assembly pseudoinstruction \texttt{I} at address \texttt{ppc}, then we can fetch the expanded pseudoinstruction(s) \texttt{[J1, \ldots, Jn] = fetch\_pseudo\_instruction \ldots\ I\ ppc} from \texttt{sigma(ppc)} in the code memory obtained loading the assembled object code. The aim of this section is to prove the following informal statement: when we fetch an assembly pseudoinstruction \texttt{I} at address \texttt{ppc}, then we can fetch the expanded pseudoinstruction(s) \texttt{[J1, \ldots, Jn] = fetch\_pseudo\_instruction \ldots\ I\ ppc} from \texttt{sigma(ppc)} in the code memory obtained by loading the assembled object code. This constitutes the first major step in the proof of correctness of the assembler, the next one being the simulation of \texttt{I} by \texttt{[J1, \ldots, Jn]} (see Subsection~\ref{subsect.total.correctness.for.well.behaved.assembly.programs}). Then, indexing into this list with any natural number \texttt{j} less than the length of \texttt{a} gives the same result as indexing into \texttt{assembled} with \texttt{sigma(ppc)} (the program counter pointing to the start of the expansion in \texttt{assembled}) plus \texttt{j}. Essentially the lemma above states that the \texttt{assembly} function correctly expands pseudoinstructions. Essentially the lemma above states that the \texttt{assembly} function correctly expands pseudoinstructions, and that the expanded instruction reside consecutively in memory. This result is lifted from lists of bytes into a result on tries of bytes (i.e. code memories), using an additional lemma: \texttt{assembly\_ok}. \end{lstlisting} Here, \texttt{l} is the number of machine code instructions the pseudoinstruction at hand has been expanded into. We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{jump\_expansion} and \texttt{expand\_pseudo\_instruction}. We assemble a single pseudoinstruction with \texttt{assembly\_1\_pseudoinstruction}, which internally calls \texttt{expand\_pseudo\_instruction}. The function \texttt{fetch\_many} fetches multiple machine code instructions from code memory and performs some routine checks. We read \texttt{fetch\_assembly\_pseudo2} as follows. Suppose we are able to successfully assemble an assembly program using \texttt{assembly} and produce a code memory, \texttt{cmem}. Then, fetching a pseudoinstruction from the pseudo-code memory at address \texttt{ppc} corresponds to fetching a sequence of instructions from the real code memory using $\sigma$ to expand pseudoinstructions. Then, fetching a pseudoinstruction from the pseudo-code memory at address \texttt{ppc} corresponds to fetching a sequence of instructions from the real code memory using \texttt{sigma} to expand pseudoinstructions. The fetched sequence corresponds to the expansion, according to \texttt{sigma}, of the pseudoinstruction. In contrast, in this paper we take a different approach. We trace memory locations (and, potentially, registers) that contain memory addresses. We then prove that only those assembly programs that use addresses in safe' ways have their semantics preserved by the assembly process---a sort of type system sitting atop memory. We then prove that only those assembly programs that use addresses in safe' ways have their semantics preserved by the assembly process---a sort of dynamic type system sitting atop memory. We believe that this approach is more flexible when compared to the traditional approach, as in principle it allows us to introduce some permitted \emph{benign} manipulations of addresses that the traditional approach, using opaque addresses, cannot handle, therefore expanding the set of input programs that can be assembled correctly. Our analogue of the semantic function above is then merely a wrapper around the function that implements the semantics of machine code, paired with a function that keeps track of addresses. This permits a large amount of code reuse, as the semantics of pseudo- and machine code is essentially shared. The only thing that changes as the assembly level is the presence of the new tracking function. This permits a large amount of code reuse, as the semantics of pseudo- and machine code are essentially shared. The only thing that changes at the assembly level is the presence of the new tracking function. However, with this approach we must detect (at run time) programs that manipulate addresses in well behaved ways, according to some approximation of well-behavedness. The \texttt{low\_internal\_ram\_of\_pseudo\_low\_internal\_ram} function converts the lower internal RAM of a \texttt{PseudoStatus} into the lower internal RAM of a \texttt{Status}. A similar function exists for higher internal RAM. A similar function exists for high internal RAM. Note that both RAM segments are indexed using addresses 7-bits long. The function is currently axiomatised, and an associated set of axioms prescribe the behaviour of the function: internal_pseudo_address_map$\rightarrow$BitVectorTrie Byte 7$\rightarrow$BitVectorTrie Byte 7. \end{lstlisting} Another pair of axioms precisely describes the supposed behaviour of \texttt{low\_internal\_ram\_of\_pseudo\_low\_internal\_ram} and its high internal ram counterpart. Next, we are able to translate \texttt{PseudoStatus} records into \texttt{Status} records using \texttt{status\_of\_pseudo\_status}. \end{lstlisting} The statement is standard for forward simulation, but restricted to \texttt{PseudoStatuses} \texttt{ps} whose next instruction to be executed is well-behaved with respect to the \texttt{internal\_pseudo\_address\_map} \texttt{M}. Further, we explicitly requires proof that our policy is correct and the pseudo program counter lies within the bounds of the program. Further, we explicitly require proof that our policy is correct and the pseudo program counter lies within the bounds of the program. Theorem \texttt{main\_thm} establishes the total correctness of the assembly process and can simply be lifted to the forward simulation of an arbitrary number of well behaved steps on the assembly program. We are proving the total correctness of an assembler for MCS-51 assembly language. In particular, our assembly language featured labels, arbitrary conditional and unconditional jumps to labels, global data and instructions for moving this data into the MCS-51's single 16-bit register. In particular, our assembly language features labels, arbitrary conditional and unconditional jumps to labels, global data and instructions for moving this data into the MCS-51's single 16-bit register. Expanding these pseudoinstructions into machine code instructions is not trivial, and the proof that the assembly process is correct', in that the semantics of a subset of assembly programs are not changed is complex. The formalisation is a key component of the CerCo project, which aims to produce a verified concrete complexity preserving compiler for a large subset of the C programming language. The verified assembler, complete with the underlying formalisation of the semantics of MCS-51 machine code (described fully in~\cite{mulligan:executable:2011}), will form the bedrock layer upon which the rest of the CerCo project will build its verified compiler platform. The verified assembler, complete with the underlying formalisation of the semantics of MCS-51 machine code, will form the bedrock layer upon which the rest of the CerCo project will build its verified compiler platform. It is interesting to compare our work to an industrial grade' assembler for the MCS-51: SDCC~\cite{sdcc:2011}. However, this comes at the expense of assembler completeness: the generated program may be too large to fit into code memory. In this respect, there is a trade-off between the completeness of the assembler and the efficiency of the assembled program. The definition and proof of a terminating, correct jump expansion policy is described in a companion publication to this one. The definition and proof of a terminating, correct jump expansion policy is described in a companion publication to this one~\cite{boender:correctness:2012}. Aside from their application in verified compiler projects such as CerCo and CompCert, verified assemblers such as ours could also be applied to the verification of operating system kernels. The second purpose is to single out the sources of incompleteness. By abstracting our functions over the dependent type of correct policies, we were able to manifest the fact that the compiler never refuses to compile a program where a correct policy exists. This also allowed to simplify the initial proof by dropping lemmas establishing that one function fails if and only if some other one does so. Finally, dependent types, together with Matita's liberal system of coercions, allow to simulate almost entirely in user space the proof methodology Russell'' of Sozeau~\cite{sozeau:subset:2006}. However, not every proof has been done this way: we only used this style to prove that a function satisfies a specification that only involves that function in a significant way. This also allowed to simplify the initial proof by dropping lemmas establishing that one function fails if and only if some previous function does so. Finally, dependent types, together with Matita's liberal system of coercions, allow us to simulate almost entirely---in user space---the proof methodology `Russell'' of Sozeau~\cite{sozeau:subset:2006}. However, not every proof has been carried out in this way: we only used this style to prove that a function satisfies a specification that only involves that function in a significant way. For example, it would be unnatural to see the proof that fetch and assembly commute as the specification of one of the two functions. The low ratio between the number of lines of code and the number of lines of proof is unusual. It is justified by the fact that the pseudo-assembly and the assembly language share most constructs and that large parts of the semantics are also shared. Thus many lines of code are required to describe the complex semantics of the processor, but, for the shared cases, the proof of preservation of the semantics is essentially trivial. Therefore many lines of code are required to describe the complex semantics of the processor, but, for the shared cases, the proof of preservation of the semantics is essentially trivial. \bibliography{cpp-2012-asm.bib}