conflict merge
[nestedvm.git] / doc / nestedvm.ivme04.tex
1 \documentclass{acmconf}
2 \usepackage{graphicx}
3 \usepackage{multicol}
4 \usepackage{amssymb,amsmath,epsfig,alltt}
5 \sloppy
6 \usepackage{palatino}
7 \usepackage{pdftricks}
8 \begin{psinputs}
9   \usepackage{pstricks}
10   \usepackage{pst-node}
11 \end{psinputs}
12 \usepackage{parskip}
13 \usepackage{tabularx}
14 \usepackage{alltt}
15 \bibliographystyle{amsplain}
16
17 \title{\textbf{\textsf{
18 Complete Translation of Unsafe Native Code to Safe Bytecode
19 }}}
20 \date{}
21 \author{\begin{tabular}{@{}c@{}}
22         {\em {Brian Alliet}} \\
23         {Rochester Institute of Technology}\\
24         {\tt bja8464@cs.rit.edu}
25    \end{tabular}\hskip 1in\begin{tabular}{@{}c@{}}
26         {\em {Adam Megacz}} \\
27         {University of California, Berkeley} \\
28         {\tt megacz@cs.berkeley.edu}
29 \end{tabular}}
30 \begin{document}
31
32 \maketitle
33
34 \begin{abstract}
35
36 Most existing techniques for using code written in an unsafe language
37 within a safe virtual machine involve transformations from one source
38 code language (such as C) to another (such as Java) and then to
39 virtual machine bytecodes.  We present an alternative approach which
40 uses a standard compiler to turn unsafe source code into unsafe MIPS
41 binaries, which are then translated into safe virtual machine
42 bytecodes.  This approach offers four key advantages over existing
43 techniques:
44
45 \begin{itemize}
46 \item Total coverage of all language features
47 \item No post-translation human intervention
48 \item No build process modifications
49 \item Bug-for-bug compiler compatability
50 \end{itemize}
51
52 We have implemented this technique in NestedVM, a binary-to-source and
53 binary-to-binary translator targeting the Java Virtual Machine.
54 NestedVM-translated versions of the {\tt libfreetype}, {\tt libjpeg},
55 and {\tt libmspack} libraries are currently in production use.
56 Performance measurements indicate a best case performance within 3x of
57 native code and worst case typically within 10x, making it an
58 attractive solution for code which is not performance-critical.
59
60 \end{abstract}
61
62 \section{Introduction}
63
64 Unsafe languages such as C \cite{KR} and C++ \cite{soustroup} have
65 been in use much longer than any of today's widely accepted safe
66 languages such as Java \cite{java} and C\# \cite{csharp}.  Consequently, there is
67 a huge library of software written in these languages.  Although safe
68 languages offer substantial benefits, their comparatively young age
69 often puts them at a disadvantage when breadth of existing support
70 code is an important criterion.
71
72 The typical solution to this dilemma is to use a native interface such
73 as JNI \cite{jni} or CNI \cite{cni} to invoke unsafe code from within a
74 virtual machine or otherwise safe environment.  Unfortunately, there
75 are a number of situations in which this is not an acceptable
76 solution.  These situations can be broadly classified into two
77 categories: {\it security concerns} and {\it portability concerns}.
78
79 Using Java as an example, JNI and CNI are prohibited in a number of
80 contexts, including applets environments and servlet containers with a
81 {\tt SecurityManager}.  Additionally, even in the context of trusted
82 code, {\tt native} methods invoked via JNI are susceptible to buffer
83 overflow and heap corruption attacks which are not a concern for
84 verified bytecode.
85
86 The second class of disadvantages revolves around portability
87 concerns; native interfaces require the native library to be compiled
88 ahead of time, for every architecture on which they will be
89 deployed.  This is unworkable for situations in which the full set of
90 target architectures is not known at deployment time.  Additionally,
91 some JVM platform variants such as J2ME \cite{j2me} simply do not offer
92 support for native code.
93
94 The technique we present here uses typical compiler to compile unsafe
95 code into a MIPS binary, which is then translated on an
96 instruction-by-instruction basis into Java bytecode.  The technique
97 presented here is general; we anticipate that it can be applied to
98 other secure virtual machines such as Microsoft's .NET \cite{msil}, Perl
99 Parrot \cite{parrot}, or Python bytecode \cite{python}.
100
101 \section{Approaches to Translation}
102
103 The four program representations of interest in this context, along
104 with their specific types in the C-to-JVM instantiation of the
105 problem are shown in the following diagram:
106
107 \begin{pdfpic}
108 \newlength{\MyLength}
109 \settowidth{\MyLength}{machine code}
110 \newcommand{\MyBox}[1]{\makebox[\MyLength][c]{#1}}
111 \begin{psmatrix}[colsep=2,rowsep=0]
112   & \\[0pt]
113   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
114   [name=s00]\MyBox{\tt (.c)} & [name=s11]\MyBox{\tt (.java)}   \\[0pt]
115   & \\[0pt]
116   & \\[0pt]
117   & \\[0pt]
118   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
119   [name=b00]\MyBox{\tt (.o)}  & [name=b11]\MyBox{\tt (.class)} \\
120   & \\[0pt]
121   \psset{nodesep=5pt,arrows=->}
122 \end{psmatrix}
123 \end{pdfpic}
124
125 To illustrate the context of this diagram, the following arcs show the
126 translations performed by a few familiar tools:
127
128 \begin{pdfpic}
129 \newlength{\MyLength}
130 \settowidth{\MyLength}{xmachine codex}
131 \newcommand{\MyBox}[1]{\makebox[\MyLength]{#1}}
132 \psmatrix[colsep=2,rowsep=0,nrot=:D]
133   & \\[0pt]
134   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
135   & \\[0pt]
136   & \\[0pt]
137   & \\[0pt]
138   & \\[0pt]
139   & \\[0pt]
140   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
141   & \\[0pt]
142   \psset{nodesep=5pt,arrows=->}
143   \ncline{s0}{b0}\bput{:U}{\tt gcc}
144   \ncline{s1}{b0}\bput{:D}{\tt gcj}
145   \ncline{s1}{b1}\aput{:U}{\tt javac}
146   \ncline{b1}{b0}\aput{:D}{\tt gcj}\bput{:D}{JITs}
147 \endpsmatrix
148 \end{pdfpic}
149
150 Techniques for translating unsafe code into VM bytecode generally fall
151 into four categories, which we expand upon in the next two sections:
152
153 \begin{itemize}
154 \item source-to-source translation
155 \item source-to-binary translation
156 \item binary-to-source translation
157 \item binary-to-binary translation
158 \end{itemize}
159
160 \section{Existing Work}
161
162 \subsection{Source-to-Source Translation}
163
164 The most common technique employed is partial translation from unsafe
165 source code to safe source code:
166
167 \begin{pdfpic}
168 \newlength{\MyLength}
169 \settowidth{\MyLength}{xmachine codex}
170 \newcommand{\MyBox}[1]{\makebox[\MyLength]{#1}}
171 \psmatrix[colsep=2,rowsep=0,nrot=:U]
172   & \\[0pt]
173   & \\[0pt]
174   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
175   & \\[0pt]
176   & \\[0pt]
177   & \\[0pt]
178   & \\[0pt]
179   & \\[0pt]
180   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
181   & \\[0pt]
182   \psset{nodesep=5pt,arrows=->}
183   \ncline{s0}{s1}\aput{:U}{source-to}\bput{:U}{source}
184   \ncline{s1}{b1}\aput{:U}{\tt javac}
185 \endpsmatrix
186 \end{pdfpic}
187
188 A number of existing systems employ this technique; they can
189 be divided into two categories: those which perform a partial
190 translation which is completed by a human, and those which perform a
191 total translation but fail (yield an error) on a large class of input
192 programs.
193
194
195 \subsubsection{Incomplete Translation}
196
197 Jazillian \cite{jazillian} is a commercial solution which produces
198 extremely readable Java source code from C source code, but ony
199 translates a small portion of the C language.  Jazillian is unique in
200 that in addition to {\it language migration}, it also performs {\it
201 API migration}; for example, Jazillian is intelligent enough
202 to translate {\tt char*~s1~=~strcpy(s2)} into {\tt String~s1~=~s2}.
203
204 Unfortunately such deep analysis is intractible for most of the C
205 language and standard library; Jazillian's documentation notes that
206 {\it ``This is not your father's language translator.  It's not
207 generating ugly code that's guaranteed to work out of the
208 box... Jazillian does not always produce code that works correctly.''}
209
210 MoHCA-Java \cite{mohca} is the other major tool in this category, and steps
211 beyond Jazillian by providing tools for analysis of the source C++
212 abstract syntax tree.  Additionally, MoHCA-Java's analysis engine is
213 extensible, making it a platform for constructing application-specific
214 translators rather than a single translation tool.  However,
215 MoHCA-Java does not always generate complete Java code for all of the C++
216 programs which it accepts.
217
218
219 \subsubsection{Partial Domain Translation}
220
221 The c2j \cite{c2j}, c2j++ \cite{c2jpp}, Cappucinno \cite{capp},
222 and Ephedra \cite{ephedra} systems each provide support for complete
223 translation of a {\it subset} of the source language (C or C++).  Each
224 of the four tools supports a progressively greater subset than the one
225 preceding it; however none covers the entire input language.
226
227 Ephedra, the most advanced of the four, supports most of the C++
228 language, and claims to produce ``human readable'' Java code as
229 output.  Notable omissions from the input domain include support for
230 fully general pointer arithmetic, casting between unrelated types, and
231 reading from a {\tt union} via a different member than the one most
232 recently written.
233
234 Unfortunately, when the program being translated is large and complex,
235 it is quite likely that it will use an unsupported feature in at least
236 one place.  In the absence of a programmer who understands the source
237 program, a single anomoly is often enough to render the entire
238 translation process useless.  As a result, these tools are mainly
239 useful as an {\it aid} to programmers who could normally perform the
240 conversion themselves, but want to save time by automating most of the
241 process.
242
243
244 \subsection{Source-to-Binary Translation}
245
246 Source-to-binary translation involves a compiler for the unsafe
247 language which has been modified to emit safe bytecode.
248
249 \begin{pdfpic}
250 \newlength{\MyLength}
251 \settowidth{\MyLength}{xmachine codex}
252 \newcommand{\MyBox}[1]{\makebox[\MyLength]{#1}}
253 \psmatrix[colsep=2,rowsep=0,nrot=:U]
254   & \\[0pt]
255   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
256   & \\[0pt]
257   & \\[0pt]
258   & \\[0pt]
259   & \\[0pt]
260   & \\[0pt]
261   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
262   & \\[0pt]
263   \psset{nodesep=5pt,arrows=->}
264   \ncline{s0}{b1}\bput{:U}{source-to-binary}
265 \endpsmatrix
266 \end{pdfpic}
267
268 The primary occupant of this category is {\tt egcs-jvm}
269 \cite{egcsjvm}, an experimental ``JVM backend'' for the GNU Compiler
270 Collection ( {\tt gcc} ) \cite{gcc}.  Since {\tt gcc} employs a highlym
271 odular architecture, it {\it is} possible to add RTL code generators
272 for nonstandard processors.  However, {\tt gcc}'s parsing, RTL
273 generation, and optimization layers make fundamental assumptions (such
274 as the availability of pointer math) which cannot be directly
275 supported; thus the compiler still fails for a substantial class of
276 input programs.
277
278
279
280 \section{NestedVM}
281
282 The principal difference between NestedVM and other approaches is that
283 NestedVM {\it does not} attempt to deal with source code as an input.
284 This leads immediately to three advantages:
285
286 \begin{itemize}
287 \item {\bf Total coverage of all language features}
288
289       Because NestedVM does not attempt to implement the parsing and
290       code generation steps of compilation, it is freed from the
291       extremely complex task of faithfully implementing languages
292       which are often not fully or formally specified (such as C and
293       C++).
294
295 \item {\bf No build process modifications}
296
297       NestedVM does not modify existing build processes, which can be
298       extremely complex and dependent on strange preprocessor usage as
299       well as the complex interplay between compiler switches and
300       header file locations.
301
302 \item {\bf Bug-for-bug compiler compatability}
303
304       Since NestedVM uses the compiler's {\it output} as its own {\it
305       input}, it ensures that programs which are inadvertently
306       dependent on the vagaries of a particular compiler can still be
307       used.
308
309 \end{itemize}
310
311 NestedVM's approach carries a fourth benefit as well, arising from its
312 totality:
313
314 \begin{itemize}
315 \item {\bf No post-translation human intervention}
316
317       NestedVM offers total support for all non-privileged
318       instructions, registers, and resources found on a MIPS {\tt
319       R2000} CPU, including the add/multiply unit and floating point
320       coprocessor.  As such, it constitutes a total function mapping
321       from the entire domain of (non-kernel-mode) programs onto (a
322       subset of) the semantics of the Java Virtual Machine.  This
323       ensures that the translation process is fully automated and
324       always succeeds for valid input binaries.
325 \end{itemize}
326
327 This is a much more important factor than is obvious at first glance.
328 If post-translation human intervention is required, then the {\it
329 human becomes part of the build process}.  This means that if a third
330 party library used in the project needs to be upgraded, {\it a human
331 must intervene} in the rebuild process.  In addition to slowing the
332 process and introducing opportunities for error, this task often
333 requires specialized knowledge which becomes tied to the particular
334 individual performing this task, rather than being encoded in build
335 scripts which persist throughout the lifetime of the project.
336
337 \subsection{Why MIPS?}
338
339 We chose MIPS as a source format for three reasons: the availability
340 of tools to compile legacy code into MIPS binaries, the close
341 similarity between the MIPS ISA and the Java Virtual Machine, and the
342 relatively high degree of program structure that can be inferred from
343 ABI-adherent binaries.
344
345 The MIPS architecture has been around for quite some time, and is well
346 supported by the GNU Compiler Collection, which is capable of
347 compiling C, C++, Java, Fortran, Pascal, and Objective C
348 into MIPS binaries.
349
350 The MIPS R2000 ISA bears a striking similarity to the Java Virtual
351 Machine:
352
353 \begin{itemize}
354
355 \item Most of the instructions in the original MIPS ISA operate only
356       on 32-bit aligned memory locations. This allows NestedVM to
357       represent memory as a Java {\tt int[]} array without introducing
358       additional overhead.  The remaining non-aligned memory load
359       instructions are only rarely emitted by most compilers since
360       they carry a performance penalty on physical MIPS
361       implementations.
362
363 \item Unlike its predecessor, the R2000 supports 32-bit by 32-bit
364       multiply and divide instructions as well as a single and double
365       precision floating point unit.  These capabilities map nicely
366       onto Java's arithmetic instructions.
367
368 \end{itemize}
369
370 Finally, the MIPS ISA and ABI convey quite a bit of information about
371 program structure.  This information can be used for optimization
372 purposes:
373
374 \begin{itemize}
375
376 \item The structure of MIPS branching and jump instructions make it
377       easy to infer the set of likely target instructions.
378
379 \item The MIPS ABI specifies particular registers as caller-save and
380       callee-save, as well as designating a register for the return
381       address after a function call.  This allows NestedVM to optimize
382       many operations for the common case of ABI-adherent binaries.
383
384 \item All MIPS instructions are exactly 32 bits long.
385
386 \end{itemize}
387
388
389
390 \subsection{Binary-to-Source}
391
392 The simplest operational mode for NestedVM is binary-to-source
393 translation.  In this mode, NestedVM translates MIPS binaries into
394 Java source code, which is then fed to a Java compiler in order to
395 produce bytecode files:
396
397 \begin{pdfpic}
398 \newlength{\MyLength}
399 \settowidth{\MyLength}{xmachine codex}
400 \newcommand{\MyBox}[1]{\makebox[\MyLength]{#1}}
401 \psmatrix[colsep=2,rowsep=0,nrot=:U]
402   & \\[0pt]
403   & \\[0pt]
404   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
405   & \\[0pt]
406   & \\[0pt]
407   & \\[0pt]
408   & \\[0pt]
409   & \\[0pt]
410   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
411   \psset{nodesep=5pt,arrows=->}
412   \ncline{s0}{b0}\bput{:U}{\tt gcc}
413   \ncline{s1}{b1}\aput{:U}{\tt javac}
414   \ncline{b0}{s1}\naput{\tt NestedVM}
415 \endpsmatrix
416 \end{pdfpic}
417
418 \begin{figure*}[t]
419 \begin{minipage}[c]{7in}%
420 \begin{multicols}{2}
421 {\footnotesize\begin{verbatim}
422 private final static int r0 = 0;
423 private int r1, r2, r3,...,r30;
424 private int r31 = 0xdeadbeef;
425 private int pc = ENTRY_POINT;
426
427 public void run() {
428     for(;;) {
429         switch(pc) {
430             case 0x10000:
431                 r29 = r29 - 32;
432             case 0x10004:
433                 r1 = r4 + r5;
434             case 0x10008:
435                 if(r1 == r6) {
436                     /* delay slot */
437                     r1 = r1 + 1;
438                     pc = 0x10018:
439                     continue;
440                 }
441             case 0x1000C:
442                 r1 = r1 + 1;
443             case 0x10010:
444                 r31 = 0x10018;
445                 pc = 0x10210;
446                 continue;
447             case 0x10014:
448                 /* nop */
449             case 0x10018:
450                 pc = r31;
451                 continue;
452             ...
453             case 0xdeadbeef:
454                 System.err.println(``Exited.'');
455                 System.exit(1);
456         }
457     }
458 }
459 \end{verbatim}}
460 \vspace{1in}
461 {\footnotesize\begin{verbatim}
462 public void run_0x10000() {
463     for(;;) {
464     switch(pc) {
465         case 0x10000:
466             ...
467         case 0x10004:
468             ...
469         ...
470         case 0x10010:
471             r31 = 0x10018;
472             pc = 0x10210;
473             return;
474         ...
475     }
476     }
477 }
478
479 pubic void run_0x10200() {
480     for(;;) {
481     switch(pc) {
482         case 0x10200:
483             ...
484         case 0x10204:
485             ...
486     }
487     }
488 }
489
490 public void trampoline() {
491     for(;;) {
492     switch(pc&0xfffffe00) {
493             case 0x10000: run_0x10000(); break;
494             case 0x10200: run_0x10200(); break;
495             case 0xdeadbe00:
496                 ...
497         }
498     }
499 }
500 \end{verbatim}}
501 \end{multicols}
502 \end{minipage}
503 \caption{\label{code1} Trampoline transformation necessitated by Java's 64kb method size limit}
504 \end{figure*}
505
506 Translating unsafe code for use within a JVM proceeds as follows:
507
508 \begin{enumerate}
509
510 \item Compile the source code to a statically linked binary, targeting
511       the MIPS R2000 ISA.  Typically this will involve linking against
512       {\tt libc}, which translates system requests (such as {\tt
513       open()}, {\tt read()}, or {\tt write()}) into appropriate
514       invocations of the MIPS {\tt SYSCALL} instruction.
515
516 \item Invoke {\tt NestedVM} on the statically linked binary.
517
518 \item Compile the resulting {\tt .java} code using {\tt jikes}
519       \cite{jikes} or {\tt javac}.
520
521 \item From java code, invoke the {\tt run()} method on the generated
522       class.  This is equivalent to the {\tt main()} entry point.
523
524 \end{enumerate}
525
526 \subsubsection{Optimizations}
527
528 Generating Java source code instead of bytecode frees NestedVM from
529 having to perform simple constant propagation optimizations, as most
530 Java compilers already do this.  A recurring example is the treatment
531 of the {\tt r0} register, which is fixed as {\tt 0} in the MIPS ISA.
532
533 Lacking the ability to generate specially optimized bytecode
534 sequences, a straightforward mapping of the general purpose hardware
535 registers to 32 {\tt int} fields turned out to be optimal.
536
537
538 \epsfig{file=chart1,width=3in}
539
540 Unfortunately, Java imposes a 64kb limit on the size of the bytecode
541 for a single method.  This presents a problem for NestedVM, and
542 necessitates a {\it trampoline transformation}, as shown in
543 Figure~\ref{code1}.  With this trampoline in place, large binaries can
544 be handled without much difficulty -- fortunately, there is no
545 corresponding limit on the size of a classfile as a whole.
546
547 One difficulty that arose as a result of using the trampoline
548 transformation was the fact that {\tt javac} and {\tt jikes} are
549 unable to properly optimize its switch statements.  For example, the
550 following code is compiled into a comparatively inefficient {\tt
551 LOOKUPSWITCH}:
552
553 {\footnotesize
554 \begin{verbatim}
555     switch(pc&0xffffff00) {
556         case 0x00000100: run_100(); break;
557         case 0x00000200: run_200(); break;
558         case 0x00000300: run_300(); break;
559     }
560 \end{verbatim}}
561
562 Whereas the next block of code code optimized into a {\tt
563 TABLESWITCH}:
564
565 {\footnotesize
566 \begin{verbatim}
567     switch(pc>>>8) {
568         case 0x1: run_100();
569         case 0x2: run_200();
570         case 0x3: run_300();
571     }
572 \end{verbatim}}
573
574 This problem was surmounted by switching on a denser set of {\tt case}
575 values, which is more amenable to the {\tt TABLESWITCH} structure.
576 This change alone nearly doubled the speed of the compiled binary.
577
578 The next performance improvement came from tuning the size of the
579 methods invoked from the trampoline.  Trial and error led to the
580 onclusion that HotSpot \cite{hotspot} -- the most widely deployed JVM
581 -- performs best when 128 MIPS instructions are mapped to each method.
582
583 \epsfig{file=chart5,width=3in}
584
585 \epsfig{file=chart6,width=3in}
586
587 This phenomenon is due to two factors:
588
589 \begin{itemize}
590
591 \item While the trampoline method's {\tt switch} statement can be
592       coded as a {\tt TABLESWITCH}, the {\tt switch} statement
593       within the individual methods is to sparse to encode this way.
594
595 \item Hybrid Interpretive-JIT compilers such as HotSpot generally
596       favor smaller methods since they are easier to compile and are
597       better candidates for compilation in ``normal'' programs (unlike
598       NestedVM programs).
599
600 \end{itemize}
601
602 After tuning method sizes, our next performance boost came from
603 eliminating exraneous case branches.  Having case statements before
604 each instruction prevents JIT compilers from being able to optimize
605 across instruction boundaries, since control flow can enter the body
606 of a {\tt switch} statement at any of the {\tt case}s.  In order to
607 eliminate unnecessary case statements we needed to identify all
608 possible jump targets.  Jump targets can come from three sources:
609
610 \begin{itemize}
611
612 \item {\bf The {\tt .text} segment}
613
614       Every instruction in the text segment is scanned, and every
615       branch instruction's destination is added to the list of
616       possible branch targets.  In addition, any function that sets
617       the link register is added to the list \footnote{actually {\tt addr+8}}.
618       Finally, combinations of {\tt LUI} (Load Upper Immediate) and
619       {\tt ADDIU} (Add Immediate Unsigned) are scanned for possible
620       addresses in the {\tt .text} segment since this combination of
621       instructions is often used to load a 32-bit word into a
622       register.
623
624 \item {\bf The {\tt .data} segment}
625
626       When compiling {\tt switch} statements, compilers often use a
627       jump table stored in the {\tt .data} segment.  Unfortunately
628       they typically do not identify these jump tables in any way.
629       Therefore, the entire {\tt .data} segment is conservatively
630       scanned for possible addresses in the {\tt .text} segment.
631       
632 \item {\bf The symbol table}
633
634       This is mainly used as a backup.  Scanning the {\tt .text} and
635       {\tt .data} segments should identify any possible jump targets;
636       however, adding all function symbols in the ELF symbol table
637       also catches functions that are never called directly from the
638       MIPS binary, such as those invoked only via the NestedVM
639       runtime's {\tt call()} method.
640
641 \end{itemize}
642
643 Eliminating unnecessary {\tt case} statements provided a 10-25\% speed
644 increase.
645
646 Despite all the above optimizations, one insurmountable obstacle
647 remained: the Java {\tt .class} file format limits the constant pool
648 to 65535 entries.  Every integer literal greater than {\tt 32767}
649 requires an entry in this pool, and each branch instruction generates
650 one of these.
651
652 One suboptimal solution was to express constants as offsets from a few
653 central values; for example ``{\tt pc~=~N\_0x00010000~+~0x10}'' (where
654 {\tt N\_0x000100000} is a non-final field to prevent {\tt javac} from
655 inlining it).  This was sufficient to get reasonably large binaries to
656 compile, and caused only a small (approximately 5\%) performance
657 degredation and a similarly small increase in the size of the {\tt
658 .class} file.  However, as we will see in the next section, compiling
659 directly to {\tt .class} files (without the intermediate {\tt .java}
660 file) eliminates this problem entirely.
661
662
663 \subsection{Binary-to-Binary}
664
665 After implementing the binary-to-source compiler, a binary-to-binary
666 translation mode was added.
667
668 \begin{pdfpic}
669 \newlength{\MyLength}
670 \settowidth{\MyLength}{xmachine codex}
671 \newcommand{\MyBox}[1]{\makebox[\MyLength]{#1}}
672 \psmatrix[colsep=2,rowsep=0,nrot=:U]
673   & \\[0pt]
674   [name=s0]\MyBox{unsafe source} & [name=s1]\MyBox{safe source}   \\[0pt]
675   & \\[0pt]
676   & \\[0pt]
677   & \\[0pt]
678   & \\[0pt]
679   & \\[0pt]
680   [name=b0]\MyBox{machine code}  & [name=b1]\MyBox{safe bytecode} \\[0pt]
681   & \\[0pt]
682   \psset{nodesep=5pt,arrows=->}
683   \ncline{s0}{b0}\bput{:U}{\tt gcc}
684   \ncline{b0}{b1}\naput{\tt NestedVM}
685 \endpsmatrix
686 \end{pdfpic}
687
688 This mode has several advantages:
689
690 \begin{itemize}
691       
692 \item There are quite a few interesting bytecode sequences that cannot
693       be generated as a result of compiling Java source code.
694
695 \item Directly generating {\tt .class} files Eliminates the
696       time-consuming {\tt javac} step.
697
698 \item Direct compilation to {\tt .class} files opens up the
699       interesting possibility of dynamically translating MIPS binaries
700       and loading them via {\tt ClassLoader.fromBytes()} {\it at
701       deployment time}, eliminating the need to compile binaries ahead
702       of time.
703
704 \end{itemize}
705
706 Most of the performance improvemen where made where in the handling of
707 branch instructions and in taking advantage of the JVM stack to
708 eliminate unnecessary {\tt LOAD}s and {\tt STORE}s to local variables.
709
710 \epsfig{file=chart7,width=3in}
711
712 The first optimization gained by direct bytecode generation came from
713 the use of the JVM {\tt GOTO} instruction.  Despite the fact that the
714 Java {\it language} does not have a {\tt goto} keyword, the VM does in
715 fact have a corresponding instruction which is used quite heavily by
716 {\tt javac}.  NestedVM's binary-to-binary mode exploits this
717 instruction to avoid emitting inefficient {\tt switch..case}
718 structures.
719
720 Related to the {\tt GOTO} instruction is branch statement
721 optimization.  When emitting source code, NestedVM translates branches
722 into Java source code like this:
723
724 {\footnotesize\begin{verbatim}
725     if (condition) {
726         pc = TARGET;
727         continue;
728     }
729 \end{verbatim}}
730
731 This requires a branch in the JVM {\it regardless} of whether the MIPS
732 branch is actually taken.  If {\tt condition} is false the JVM has to
733 jump over the code to set {\tt pc} and go back to the {\tt switch}
734 statemenmt; if {\tt condition} is true the JVM has to jump to the {\tt
735 switch} block.  By generating bytecode directly, NestedVM is able to
736 emit a JVM bytecode branching directly to the address corresponding to
737 the target of the MIPS branch.  In the case where the branch is not
738 taken the JVM doesn't branch at all.
739
740 A side effect of the previous two optimizations is a solution to the
741 excess constant pool entries problem.  When jumps are implemented as
742 {\tt GOTO}s and branches are taken directly, the {\tt pc} field does
743 not need to be set.  This eliminates a huge number of constant pool
744 entries.  The {\tt .class} file constant pool size limit is still
745 present, but it is less likely to be encountered.
746
747 Implementation of the MIPS delay slot offers another opportunity for
748 bytecode-level optimization.  In order to take advantage of
749 instructions already in the pipeline, the MIPS ISA specifies that the
750 instruction after a jump or branch is always executed, even if the
751 jump/branch is taken.  This instruction is referred to as the ``delay
752 slot\footnote{Newer MIPS CPUs have pipelines that are much larger than
753 early MIPS CPUs, so they have to discard instructions anyways}.''  The
754 instruction in the delay slot is actually executed {\it before} the
755 branch is taken.  To further complicate matters, values from the
756 register file are loaded {\it before} the delay slot is executed.
757
758 Fortunately there is a very elegent solution to this problem which can
759 be expressed in JVM bytecode.  When a branch instruction is
760 encountered, the registers needed for the comparison are pushed onto
761 the stack to prepare for the JVM branch instruction.  Then, {\it
762 after} the values are on the stack the delay slot instruction is
763 emitted, followed by the actual JVM branch instruction.  Because the
764 values were pushed to the stack before the delay slot was executed, any
765 changes the delay slot made to the registers are not visible to the
766 branch bytecode.
767
768 One final advantage that generating bytecode directly allows is a
769 reduction in the size of the ultimate {\tt .class} file.  All the
770 optimizations above lead to more compact bytecode as a beneficial side
771 effect; in addition, NestedVM performs a few additional optimizations.
772
773 When encountering the following {\tt switch} block, both {\tt javac}
774 and {\tt jikes} generate redundant bytecode.
775
776 {\footnotesize\begin{verbatim}
777     switch(pc>>>8) {
778         case 0x1: run_1(); break;
779         case 0x2: run_2(); break
780         ...
781         case 0x100: run_100(); break;
782     }
783 \end{verbatim}}
784
785 The first bytecode in each case arm in the switch statement is {\tt
786 ALOAD\_0} to prepare for a {\tt INVOKESPECIAL} call.  By simply
787 lifting this bytecode outside of the {\tt switch} statement, each {\tt
788 case} arm shrinks by one instruction.
789
790 \subsubsection{Compiler Flags}
791
792 Although NestedVM perfectly emulates a MIPS R2000 CPU, its performance
793 profile is nothing like that of actual silicon.  In particular, {\tt
794 gcc} makes several optimizations that increase performance on an
795 actually MIPS CPU but actually decrease the performance of
796 NestedVM-generated bytecode.  We found the following compiler options
797 could be used to improve performance:
798
799 \begin{itemize}
800
801 \item {\tt -falign-functions}
802
803       Normally a function's location in memory has no effect on its
804       execution speed.  However, in the NestedVM binary translator,
805       the {\tt .text} segment is split on power-of-two boundaries.  If
806       a function starts near the end of one of these boundaries, a
807       performance critical part of the function winds up spanning two
808       Java methods.  Telling {\tt gcc} to align all functions along
809       these boundaries decreases the chance of this sort of splitting.
810
811 \item {\tt -fno-rename-registers}
812
813       On an actual silicon chip, using additional registers carries no
814       performance penalty (as long as none are spilled to the stack).
815       However, when generating bytecode, using {\it fewer}
816       ``registers'' helps the JVM optimize the machine code it
817       generates by simplifying the constraints it needs to deal with.
818       Disabling register renaming has this effect.
819
820 \item {\tt -fno-schedule-insns}
821
822       Results of MIPS load operations are not available until {\it
823       two} instructions after the load.  Without the {\tt
824       -fno-schedule-insns} instruction, {\tt gcc} will attempt to
825       reorder instructions to do other useful work during this period
826       of unavailability.  NestedVM is under no such constraint, so
827       removing this reordering typically generates simpler machine
828       code.
829
830 \item {\tt -mmemcpy}
831
832       Enabling this instruction causes {\tt gcc} to use the system
833       {\tt memcpy()} routine instead of generating loads and stores.
834       As explained in the next section, the NestedVM runtime
835       implements {\tt memcpy()} using {\tt System.arraycopy()}, which
836       is substantially more efficient.
837
838 \item {\tt -ffunction-sections -fdata-sections}
839
840       These two options are used in conjunction with the {\tt
841       --gc-section} linker option, prompting the linker to more
842       aggressively prune dead code.
843
844 \end{itemize}
845
846 The effects of the various optimizations presented in this chapter are
847 summarized in the table below.
848
849 \epsfig{file=chart4,width=3in}
850
851 \epsfig{file=chart3,width=3in}
852
853 \section{The NestedVM Runtime}
854
855 In addition to binary-to-source and binary-to-binary translation,
856 NestedVM also includes a MIPS binary interpreter.  All three
857 translation approaches expose the same API to both the translated
858 binary and the surrounding VM (including peer Java code).
859
860 \subsection{The Runtime Class}
861
862 The runtime fulfills four roles:
863
864 \begin{itemize}
865       
866 \item It provides a simple, consistent external interface.  The method
867       of actually executing the code (currently only translated
868       binaries and the interpreter) can be changed without any code
869       changes to the caller because only runtime exposes a public
870       interface.  This includes methods to pass arguments to the
871       binary's {\tt main()} function, read and write from memory, and
872       call individual functions in the binary.
873       
874 \item It manages the process's memory.  The runtime class contains
875       large {\tt int[]} arrays that represent the process`s entire
876       memory space.  Subclasses read and write to these arrays as
877       required by the instructions they are executing, and can expand
878       their memory space using the {\tt sbrk} system call.
879       
880 \item The runtime provides access to the host file system and standard
881       I/O streams.  Subclasses of {\tt runtime} can access the file
882       system through standard UNIX syscalls ({\tt read()}, {\tt
883       write()}, {\tt open()}, etc).  The runtime manages the file
884       descriptor table that maps UNIX file descriptors to Java {\tt
885       RandomAccessFile}s, {\tt InputStream}s, {\tt OutputStream}s, and
886       {\tt Socket}s.
887       
888 \item It provides general OS services, including {\tt sleep()}, {\tt
889       gettimeofday()}, {\tt getpagesize()}, {\tt sysconf()}, {\tt
890       fcntl()}, and so on.
891       
892 \end{itemize}
893
894 \section{Future Directions}
895
896 Although we have only implemented it for the Java Virtual Machine, our
897 technique generalizes to other safe bytecode architectures.  In
898 particular we would like to demonstrate this generality by retargeting
899 the translator to the Microsoft Intermediate Language \cite{msil}.
900
901 Additionally, we would like to explore other uses for dynamic loading
902 of translated MIPS binaries by combining NestedVM (which itself is
903 written in Java) and the {\tt ClassLoader.fromBytes()} mechanism.
904
905
906 \section{Conclusion}
907
908 We have presented a novel technique for using libraries written in
909 unsafe languages within a safe virtual machine without resorting to
910 native interfaces.  We have implemented this technique in NestedVM,
911 which is currently used by the Ibex project\footnote{{\tt
912 http://www.ibex.org}} to perform font rasterization (via {\tt
913 libfreetype}), JPEG decoding (via {\tt libjpeg}), and CAB archive
914 extraction (via {\tt libmspack}), three libraries for which no
915 equivalent Java classes exist.
916
917 NestedVM is available under an open source license, and can be
918 obtained from
919 \begin{verbatim}
920     http://nestedvm.ibex.org
921 \end{verbatim}
922
923
924 \section{Appendix: Testing Methodology}
925
926 All times are measured in seconds. These were all run on a dual 1Ghz
927 Macintosh G4 running Apple's latest JVM (Sun HotSpot JDK 1.4.1). Each
928 test was run 8 times within a single VM. The highest and lowest times
929 were removed and the remaining 6 were averaged.  In each case only the
930 first run differed significantly from the rest.
931
932 The {\tt libjpeg} test consisted of decoding a 1280x1024 jpeg and
933 writing a tga.  The {\tt mspack} test consisted of extracting all
934 members from {\tt arial32.exe}, {\tt comic32.exe}, {\tt times32.exe},
935 and {\tt verdan32.exe}. The {\tt libfreetype} test consisted of
936 rendering ASCII characters 32-127 of {\tt Comic.TTF} at sizes from 8
937 to 48 incrementing by 4 for a total of 950 glyphs.
938
939 \bibliography{nestedvm}
940
941 \end{document}
942