DexFile.java revision 61eedba1ab4514e7d287a173a204ef35771904f4
1/*
2 * [The "BSD licence"]
3 * Copyright (c) 2009 Ben Gruver
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29package org.jf.dexlib;
30
31import org.jf.dexlib.Util.*;
32import org.jf.dexlib.*;
33import org.jf.dexlib.Item;
34import org.jf.dexlib.StringDataItem;
35
36import java.io.File;
37import java.io.UnsupportedEncodingException;
38import java.security.DigestException;
39import java.security.MessageDigest;
40import java.security.NoSuchAlgorithmException;
41import java.util.HashMap;
42import java.util.Arrays;
43import java.util.Comparator;
44import java.util.Collections;
45import java.util.zip.Adler32;
46
47/**
48 * <h3>Main use cases</h3>
49 *
50 * <p>These are the main use cases that drove the design of this library</p>
51 *
52 * <ol>
53 * <li><p><b>Annotate an existing dex file</b> - In this case, the intent is to document the structure of
54 *    an existing dex file. We want to be able to read in the dex file, and then write out a dex file
55 *    that is exactly the same (while adding annotation information to an AnnotatedOutput object)</p></li>
56 *
57 * <li><p><b>Canonicalize an existing dex file</b> - In this case, the intent is to rewrite an existing dex file
58 *    so that it is in a canonical form. There is a certain amount of leeway in how various types of
59 *    tems in a dex file are ordered or represented. It is sometimes useful to be able to easily
60 *    compare a disassebled and reassembled dex file with the original dex file. If both dex-files are
61 *    written canonically, they "should" match exactly, barring any explicit changes to the reassembled
62 *    file.</p>
63 *
64 *    <p>Currently, there are a couple of pieces of information that probably won't match exactly
65 *    <ul>
66 *    <li>the order of exception handlers in the <code>EncodedCatchHandlerList</code> for a method</li>
67 *    <li>the ordering of some of the debug info in the <code>{@link org.jf.dexlib.DebugInfoItem}</code> for a method</li>
68 *    </ul></p>
69 *
70 *
71 *    <p>Note that the above discrepancies should typically only be "intra-item" differences. They
72 *    shouldn't change the size of the item, or affect how anything else is placed or laid out</p></li>
73 *
74 * <li><p><b>Creating a dex file from scratch</b> - In this case, a blank dex file is created and then classes
75 *    are added to it incrementally by calling the {@link org.jf.dexlib.Section#intern intern} method of
76 *    {@link DexFile#ClassDefsSection}, which will add all the information necessary to represent the given
77 *    class. For example, when assembling a dex file from a set of assembly text files.</p>
78 *
79 *    <p>In this case, we can choose to write  the dex file in a canonical form or not. It is somewhat
80 *    slower to write it in a canonical format, due to the extra sorting and calculations that are
81 *    required.</p></li>
82 *
83 *
84 * <li><p><b>Reading in the dex file</b> - In this case, the intent is to read in a dex file and expose all the
85 *    data to the calling application. For example, when disassembling a dex file into a text based
86 *    assembly format, or doing other misc processing of the dex file.</p></li>
87 *
88 *
89 * <h3>Other use cases</h3>
90 *
91 * <p>These are other use cases that are possible, but did not drive the design of the library.
92 * No effort was made to test these use cases or ensure that they work. Some of these could
93 * probably be better achieved with a disassemble - modify - reassemble type process, using
94 * smali/baksmali or another assembler/disassembler pair that are compatible with each other</p>
95 *
96 * <ul>
97 * <li>deleting classes/methods/etc. from a dex file</li>
98 * <li>merging 2 dex files</li>
99 * <li>splitting a dex file</li>
100 * <li>moving classes from 1 dex file to another</li>
101 * <li>removing the debug information from a dex file</li>
102 * <li>obfustication of a dex file</li>
103 * </ul>
104 */
105public class DexFile
106{
107    /**
108     * A mapping from ItemType to the section that contains items of the given type
109     */
110    private final Section[] sectionsByType;
111
112    /**
113     * Ordered lists of the indexed and offsetted sections. The order of these lists specifies the order
114     * that the sections will be written in
115     */
116    private final IndexedSection[] indexedSections;
117    private final OffsettedSection[] offsettedSections;
118
119    /**
120     * dalvik had a bug where it wrote the registers for certain types of debug info in a signed leb
121     * format, instead of an unsigned leb format. There are no negative registers of course, but
122     * certain positive values have a different encoding depending on whether they are encoded as
123     * an unsigned leb128 or a signed leb128. Specifically, the signed leb128 is 1 byte longer in some cases.
124     *
125     * This determine whether we should keep any signed registers as signed, or force all register to
126     * unsigned. By default we don't keep track of whether they were signed or not, and write them back
127     * out as unsigned. This option only has an effect when reading an existing dex file. It has no
128     * effect when a dex file is created from scratch
129     *
130     * The 2 main use-cases in play are
131     * 1. Annotate an existing dex file - In this case, preserveSignedRegisters should be false, so that we keep
132     * track of any signed registers and write them back out as signed Leb128 values.
133     *
134     * 2. Canonicalize an existing dex file - In this case, fixRegisters should be true, so that all
135     * registers in the debug info are written as unsigned Leb128 values regardless of how they were
136     * originally encoded
137     */
138    private final boolean preserveSignedRegisters;
139
140    /**
141     * When true, this prevents any sorting of the items during placement of the dex file. This
142     * should *only* be set to true when this dex file was read in from an existing (valid) dex file,
143     * and no modifications were made (i.e. no items added or deleted). Otherwise it is likely that
144     * an invalid dex file will be generated.
145     *
146     * This is useful for the first use case (annotating an existing dex file). This ensures the items
147     * retain the same order as in the original dex file.
148     */
149    private boolean inplace = false;
150
151    /**
152     * When true, this imposes an full ordering on all the items, to force them into a (possibly
153     * arbitrary) canonical order. When false, only the items that the dex format specifies
154     * an order for are sorted. The rest of the items are not ordered.
155     *
156     * This is useful for the second use case (canonicalizing an existing dex file) or possibly for
157     * the third use case (creating a dex file from scratch), if there is a need to write the new
158     * dex file in a canonical form.
159     */
160    private boolean sortAllItems = false;
161
162
163    /**
164     * this is used to access the dex file from within inner classes, when they declare fields or
165     * variable that hide fields on this object
166     */
167    private final DexFile dexFile = this;
168
169    /**
170     * Is this file an odex file? This is only set when reading in an odex file
171     */
172    private boolean isOdex = false;
173
174
175    private int dataOffset;
176    private int dataSize;
177    private int fileSize;
178
179    private boolean disableInterning = false;
180
181
182    /**
183     * A private constructor containing common code to initialize the section maps and lists
184     * @param preserveSignedRegisters If true, keep track of any registers in the debug information
185     * that are signed, so they will be written in the same format. See
186     * <code>getPreserveSignedRegisters()</code>
187     */
188    private DexFile(boolean preserveSignedRegisters) {
189        this.preserveSignedRegisters = preserveSignedRegisters;
190
191        sectionsByType = new Section[] {
192                StringIdsSection,
193                TypeIdsSection,
194                ProtoIdsSection,
195                FieldIdsSection,
196                MethodIdsSection,
197                ClassDefsSection,
198                TypeListsSection,
199                AnnotationSetRefListsSection,
200                AnnotationSetsSection,
201                ClassDataSection,
202                CodeItemsSection,
203                AnnotationDirectoriesSection,
204                StringDataSection,
205                DebugInfoItemsSection,
206                AnnotationsSection,
207                EncodedArraysSection,
208                null,
209                null
210        };
211
212        indexedSections = new IndexedSection[] {
213                StringIdsSection,
214                TypeIdsSection,
215                ProtoIdsSection,
216                FieldIdsSection,
217                MethodIdsSection,
218                ClassDefsSection
219        };
220
221        offsettedSections = new OffsettedSection[] {
222                AnnotationSetRefListsSection,
223                AnnotationSetsSection,
224                CodeItemsSection,
225                AnnotationDirectoriesSection,
226                TypeListsSection,
227                StringDataSection,
228                AnnotationsSection,
229                EncodedArraysSection,
230                ClassDataSection,
231                DebugInfoItemsSection
232        };
233    }
234
235
236    /**
237     * Construct a new DexFile instance by reading in the given dex file.
238     * @param file The dex file to read in
239     */
240    public DexFile(String file) {
241        this(new File(file), true);
242    }
243
244    /**
245     * Construct a new DexFile instance by reading in the given dex file,
246     * and optionally keep track of any registers in the debug information that are signed,
247     * so they will be written in the same format.
248     * @param file The dex file to read in
249     * @param preserveSignedRegisters If true, keep track of any registers in the debug information
250     * that are signed, so they will be written in the same format. See
251     * <code>getPreserveSignedRegisters()</code>
252     */
253    public DexFile(String file, boolean preserveSignedRegisters) {
254        this(new File(file), preserveSignedRegisters);
255    }
256
257    /**
258     * Construct a new DexFile instance by reading in the given dex file.
259     * @param file The dex file to read in
260     */
261    public DexFile(File file) {
262        this(file, true);
263    }
264
265    /**
266     * Construct a new DexFile instance by reading in the given dex file,
267     * and optionally keep track of any registers in the debug information that are signed,
268     * so they will be written in the same format.
269     * @param file The dex file to read in
270     * @param preserveSignedRegisters If true, keep track of any registers in the debug information
271     * that are signed, so they will be written in the same format.
272     * @see #getPreserveSignedRegisters
273     */
274    public DexFile(File file, boolean preserveSignedRegisters) {
275        this(preserveSignedRegisters);
276
277        byte[] magic = FileUtils.readFile(file, 0, 8);
278        byte[] dexMagic, odexMagic;
279
280        try {
281            dexMagic = HeaderItem.MAGIC.getBytes("US-ASCII");
282            odexMagic = OdexHeaderItem.MAGIC.getBytes("US-ASCII");
283        } catch (UnsupportedEncodingException ex) {
284            throw new RuntimeException(ex);
285        }
286
287        boolean isDex = true;
288        this.isOdex = true;
289        for (int i=0; i<8; i++) {
290            if (magic[i] != dexMagic[i]) {
291                isDex = false;
292            }
293            if (magic[i] != odexMagic[i]) {
294                isOdex = false;
295            }
296        }
297
298        Input in;
299
300        if (isOdex) {
301            byte[] odexHeaderBytes = FileUtils.readFile(file, 0, 40);
302            Input odexHeaderIn = new ByteArrayInput(odexHeaderBytes);
303            OdexHeaderItem odexHeader = new OdexHeaderItem(odexHeaderIn);
304
305            in = new ByteArrayInput(FileUtils.readFile(file, odexHeader.dexOffset, odexHeader.dexLength));
306        } else if (isDex) {
307            in = new ByteArrayInput(FileUtils.readFile(file));
308        } else {
309            throw new RuntimeException("bad magic value");
310        }
311
312        ReadContext readContext = new ReadContext(this);
313
314        HeaderItem.readFrom(in, 0, readContext);
315
316        //the map offset was set while reading in the header item
317        int mapOffset = readContext.getSectionOffset(ItemType.TYPE_MAP_LIST);
318
319        in.setCursor(mapOffset);
320        MapItem.readFrom(in, 0, readContext);
321
322        for (Section section: sectionsByType) {
323            if (section == null) {
324                continue;
325            }
326
327            int sectionOffset = readContext.getSectionOffset(section.ItemType);
328            if (sectionOffset > 0) {
329                int sectionSize = readContext.getSectionSize(section.ItemType);
330                in.setCursor(sectionOffset);
331                section.readFrom(sectionSize, in, readContext);
332            }
333        }
334    }
335
336    /**
337     * Constructs a new, blank dex file. Classes can be added to this dex file by calling
338     * the <code>Section.intern()</code> method of <code>ClassDefsSection</code>
339     */
340    public DexFile() {
341        this(true);
342    }
343
344    /**
345     * Get the <code>Section</code> containing items of the same type as the given item
346     * @param item Get the <code>Section</code> that contains items of this type
347     * @param <T> The specific item subclass - inferred from the passed item
348     * @return the <code>Section</code> containing items of the same type as the given item
349     */
350    public <T extends Item> Section<T> getSectionForItem(T item) {
351        return (Section<T>)sectionsByType[item.getItemType().SectionIndex];
352    }
353
354    /**
355     * Get the <code>Section</code> containing items of the given type
356     * @param itemType the type of item
357     * @return the <code>Section</code> containing items of the given type
358     */
359    public Section getSectionForType(ItemType itemType) {
360        return sectionsByType[itemType.SectionIndex];
361    }
362
363    /**
364     * Get a boolean value indicating whether this dex file preserved any signed
365     * registers in the debug info as it read the dex file in. By default, the dex file
366     * doesn't check whether the registers are encoded as unsigned or signed values.
367     *
368     * This does *not* affect the actual register value that is read in. The value is
369     * read correctly regardless
370     *
371     * This does affect whether any signed registers will retain the same encoding or be
372     * forced to the (correct) unsigned encoding when the dex file is written back out.
373     *
374     * See the discussion about signed register values in the documentation for
375     * <code>DexFile</code>
376     * @return a boolean indicating whether this dex file preserved any signed registers
377     * as it was read in
378     */
379    public boolean getPreserveSignedRegisters() {
380        return preserveSignedRegisters;
381    }
382
383    /**
384     * Get a boolean value indicating whether all items should be placed into a
385     * (possibly arbitrary) "canonical" ordering. If false, then only the items
386     * that must be ordered per the dex specification are sorted.
387     *
388     * When true, writing the dex file involves somewhat more overhead
389     *
390     * If both SortAllItems and Inplace are true, Inplace takes precedence
391     * @return a boolean value indicating whether all items should be sorted
392     */
393    public boolean getSortAllItems() {
394        return this.sortAllItems;
395    }
396
397    /**
398     * Set a boolean value indicating whether all items should be placed into a
399     * (possibly arbitrary) "canonical" ordering. If false, then only the items
400     * that must be ordered per the dex specification are sorted.
401     *
402     * When true, writing the dex file involves somewhat more overhead
403     *
404     * If both SortAllItems and Inplace are true, Inplace takes precedence
405     * @param value a boolean value indicating whether all items should be sorted
406     */
407    public void setSortAllItems(boolean value) {
408        this.sortAllItems = value;
409    }
410
411    /**
412     * Disables adding new items to this dex file. The various getInterned*() type
413     * methods on individual items will return null if there isn't an existing item
414     * that matches
415     */
416    public void disableInterning() {
417        this.disableInterning = true;
418    }
419
420    /**
421     * @return a boolean value indicating whether interning new items has been disabled
422     * for this dex file
423     */
424    public boolean getInterningDisabled() {
425        return disableInterning;
426    }
427
428    /**
429     * @return a boolean value indicating whether this dex file was created by reading in an odex file
430     */
431    public boolean isOdex() {
432        return this.isOdex;
433    }
434
435    /**
436     * Get a boolean value indicating whether items in this dex file should be
437     * written back out "in-place", or whether the normal layout logic should be
438     * applied.
439     *
440     * This should only be used for a dex file that has been read from an existing
441     * dex file, and no modifications have been made to the dex file. Otherwise,
442     * there is a good chance that the resulting dex file will be invalid due to
443     * items that aren't placed correctly
444     *
445     * If both SortAllItems and Inplace are true, Inplace takes precedence
446     * @return a boolean value indicating whether items in this dex file should be
447     * written back out in-place.
448     */
449    public boolean getInplace() {
450        return this.inplace;
451    }
452
453    /**
454     * @return the size of the file, in bytes
455     */
456    public int getFileSize() {
457        return fileSize;
458    }
459
460    /**
461     * @return the size of the data section, in bytes
462     */
463    public int getDataSize() {
464        return dataSize;
465    }
466
467    /**
468     * @return the offset where the data section begins
469     */
470    public int getDataOffset() {
471        return dataOffset;
472    }
473
474    /**
475     * Set a boolean value indicating whether items in this dex file should be
476     * written back out "in-place", or whether the normal layout logic should be
477     * applied.
478     *
479     * This should only be used for a dex file that has been read from an existing
480     * dex file, and no modifications have been made to the dex file. Otherwise,
481     * there is a good chance that the resulting dex file will be invalid due to
482     * items that aren't placed correctly
483     *
484     * If both SortAllItems and Inplace are true, Inplace takes precedence
485     * @param value a boolean value indicating whether items in this dex file should be
486     * written back out in-place.
487     */
488    public void setInplace(boolean value) {
489        this.inplace = value;
490    }
491
492    /**
493     * Get an array of Section objects that are sorted by offset.
494     * @return an array of Section objects that are sorted by offset.
495     */
496    protected Section[] getOrderedSections() {
497        int sectionCount = 0;
498
499        for (Section section: sectionsByType) {
500            if (section != null && section.getItems().size() > 0) {
501                sectionCount++;
502            }
503        }
504
505        Section[] sections = new Section[sectionCount];
506        sectionCount = 0;
507        for (Section section: sectionsByType) {
508            if (section != null && section.getItems().size() > 0) {
509                sections[sectionCount++] = section;
510            }
511        }
512
513        Arrays.sort(sections, new Comparator<Section>() {
514            public int compare(Section a, Section b) {
515                return a.getOffset() - b.getOffset();
516            }
517        });
518
519        return sections;
520    }
521
522    /**
523     * This method should be called before writing a dex file. It sorts the sections
524     * as needed or as indicated by <code>getSortAllItems()</code> and <code>getInplace()</code>,
525     * and then performs a pass through all of the items, finalizing the position (i.e.
526     * index and/or offset) of each item in the dex file.
527     *
528     * This step is needed primarily so that the indexes and offsets of all indexed and
529     * offsetted items are available when writing references to those items elsewhere.
530     */
531    public void place() {
532        int offset = HeaderItem.placeAt(0, 0);
533
534        int sectionsPosition = 0;
535        Section[] sections;
536        if (this.inplace) {
537            sections = this.getOrderedSections();
538        } else {
539            sections = new Section[indexedSections.length + offsettedSections.length];
540            System.arraycopy(indexedSections, 0, sections, 0, indexedSections.length);
541            System.arraycopy(offsettedSections, 0, sections, indexedSections.length,  offsettedSections.length);
542        }
543
544        while (sectionsPosition < sections.length && sections[sectionsPosition].ItemType.isIndexedItem()) {
545            Section section = sections[sectionsPosition];
546            if (!this.inplace) {
547                section.sortSection();
548            }
549
550            offset = section.placeAt(offset);
551
552            sectionsPosition++;
553        }
554
555        dataOffset = offset;
556
557        while (sectionsPosition < sections.length) {
558            Section section = sections[sectionsPosition];
559            if (this.sortAllItems && !this.inplace) {
560                section.sortSection();
561            }
562            offset = section.placeAt(offset);
563
564            sectionsPosition++;
565        }
566
567
568        offset = AlignmentUtils.alignOffset(offset, ItemType.TYPE_MAP_LIST.ItemAlignment);
569        offset = MapItem.placeAt(offset, 0);
570
571        fileSize = offset;
572        dataSize = offset - dataOffset;
573    }
574
575    /**
576     * Writes the dex file to the give <code>AnnotatedOutput</code> object. If
577     * <code>out.Annotates()</code> is true, then annotations that document the format
578     * of the dex file are written.
579     *
580     * You must call <code>place()</code> on this dex file, before calling this method
581     * @param out the AnnotatedOutput object to write the dex file and annotations to
582     *
583     * After calling this method, you should call <code>calcSignature()</code> and
584     * then <code>calcChecksum()</code> on the resulting byte array, to calculate the
585     * signature and checksum in the header
586     */
587    public void writeTo(AnnotatedOutput out) {
588
589        out.annotate(0, "-----------------------------");
590        out.annotate(0, "header item");
591        out.annotate(0, "-----------------------------");
592        out.annotate(0, " ");
593        HeaderItem.writeTo(out);
594
595        out.annotate(0, " ");
596
597        int sectionsPosition = 0;
598        Section[] sections;
599        if (this.inplace) {
600            sections = this.getOrderedSections();
601        } else {
602            sections = new Section[indexedSections.length + offsettedSections.length];
603            System.arraycopy(indexedSections, 0, sections, 0, indexedSections.length);
604            System.arraycopy(offsettedSections, 0, sections, indexedSections.length,  offsettedSections.length);
605        }
606
607        while (sectionsPosition < sections.length) {
608            sections[sectionsPosition].writeTo(out);
609            sectionsPosition++;
610        }
611
612        out.alignTo(MapItem.getItemType().ItemAlignment);
613
614        out.annotate(0, " ");
615        out.annotate(0, "-----------------------------");
616        out.annotate(0, "map item");
617        out.annotate(0, "-----------------------------");
618        out.annotate(0, " ");
619        MapItem.writeTo(out);
620    }
621
622    public final HeaderItem HeaderItem = new HeaderItem(this);
623    public final MapItem MapItem = new MapItem(this);
624
625    /**
626     * The <code>IndexedSection</code> containing <code>StringIdItem</code> items
627     */
628    public final IndexedSection<StringIdItem> StringIdsSection =
629            new IndexedSection<StringIdItem>(this, ItemType.TYPE_STRING_ID_ITEM);
630
631    /**
632     * The <code>IndexedSection</code> containing <code>TypeIdItem</code> items
633     */
634    public final IndexedSection<TypeIdItem> TypeIdsSection =
635            new IndexedSection<TypeIdItem>(this, ItemType.TYPE_TYPE_ID_ITEM);
636
637    /**
638     * The <code>IndexedSection</code> containing <code>ProtoIdItem</code> items
639     */
640    public final IndexedSection<ProtoIdItem> ProtoIdsSection =
641            new IndexedSection<ProtoIdItem>(this, ItemType.TYPE_PROTO_ID_ITEM);
642
643    /**
644     * The <code>IndexedSection</code> containing <code>FieldIdItem</code> items
645     */
646    public final IndexedSection<FieldIdItem> FieldIdsSection =
647            new IndexedSection<FieldIdItem>(this, ItemType.TYPE_FIELD_ID_ITEM);
648
649    /**
650     * The <code>IndexedSection</code> containing <code>MethodIdItem</code> items
651     */
652    public final IndexedSection<MethodIdItem> MethodIdsSection =
653            new IndexedSection<MethodIdItem>(this, ItemType.TYPE_METHOD_ID_ITEM);
654
655    /**
656     * The <code>IndexedSection</code> containing <code>ClassDefItem</code> items
657     */
658    public final IndexedSection<ClassDefItem> ClassDefsSection =
659            new IndexedSection<ClassDefItem>(this, ItemType.TYPE_CLASS_DEF_ITEM) {
660
661         public int placeAt(int offset) {
662            if (dexFile.getInplace()) {
663                return super.placeAt(offset);
664            }
665
666            int ret = ClassDefItem.placeClassDefItems(this, offset);
667
668            Collections.sort(this.items, new Comparator<ClassDefItem>() {
669
670                public int compare(ClassDefItem a, ClassDefItem b) {
671                    return a.getOffset() - b.getOffset();
672                }
673            });
674
675            this.offset = items.get(0).getOffset();
676            return ret;
677        }
678    };
679
680    /**
681     * The <code>OffsettedSection</code> containing <code>TypeListItem</code> items
682     */
683    public final OffsettedSection<TypeListItem> TypeListsSection =
684            new OffsettedSection<TypeListItem>(this, ItemType.TYPE_TYPE_LIST);
685
686    /**
687     * The <code>OffsettedSection</code> containing <code>AnnotationSetRefList</code> items
688     */
689    public final OffsettedSection<AnnotationSetRefList> AnnotationSetRefListsSection =
690            new OffsettedSection<AnnotationSetRefList>(this, ItemType.TYPE_ANNOTATION_SET_REF_LIST);
691
692    /**
693     * The <code>OffsettedSection</code> containing <code>AnnotationSetItem</code> items
694     */
695    public final OffsettedSection<AnnotationSetItem> AnnotationSetsSection =
696            new OffsettedSection<AnnotationSetItem>(this, ItemType.TYPE_ANNOTATION_SET_ITEM);
697
698    /**
699     * The <code>OffsettedSection</code> containing <code>ClassDataItem</code> items
700     */
701    public final OffsettedSection<ClassDataItem> ClassDataSection =
702            new OffsettedSection<ClassDataItem>(this, ItemType.TYPE_CLASS_DATA_ITEM);
703
704    /**
705     * The <code>OffsettedSection</code> containing <code>CodeItem</code> items
706     */
707    public final OffsettedSection<CodeItem> CodeItemsSection =
708            new OffsettedSection<CodeItem>(this, ItemType.TYPE_CODE_ITEM);
709
710    /**
711     * The <code>OffsettedSection</code> containing <code>StringDataItem</code> items
712     */
713    public final OffsettedSection<StringDataItem> StringDataSection =
714            new OffsettedSection<StringDataItem>(this, ItemType.TYPE_STRING_DATA_ITEM);
715
716    /**
717     * The <code>OffsettedSection</code> containing <code>DebugInfoItem</code> items
718     */
719    public final OffsettedSection<DebugInfoItem> DebugInfoItemsSection =
720            new OffsettedSection<DebugInfoItem>(this, ItemType.TYPE_DEBUG_INFO_ITEM);
721
722    /**
723     * The <code>OffsettedSection</code> containing <code>AnnotationItem</code> items
724     */
725    public final OffsettedSection<AnnotationItem> AnnotationsSection =
726            new OffsettedSection<AnnotationItem>(this, ItemType.TYPE_ANNOTATION_ITEM);
727
728    /**
729     * The <code>OffsettedSection</code> containing <code>EncodedArrayItem</code> items
730     */
731    public final OffsettedSection<EncodedArrayItem> EncodedArraysSection =
732            new OffsettedSection<EncodedArrayItem>(this, ItemType.TYPE_ENCODED_ARRAY_ITEM);
733
734    /**
735     * The <code>OffsettedSection</code> containing <code>AnnotationDirectoryItem</code> items
736     */
737    public final OffsettedSection<AnnotationDirectoryItem> AnnotationDirectoriesSection =
738            new OffsettedSection<AnnotationDirectoryItem>(this, ItemType.TYPE_ANNOTATIONS_DIRECTORY_ITEM);
739
740
741    /**
742     * Calculates the signature for the dex file in the given byte array,
743     * and then writes the signature to the appropriate location in the header
744     * containing in the array
745     *
746     * @param bytes non-null; the bytes of the file
747     */
748    public static void calcSignature(byte[] bytes) {
749        MessageDigest md;
750
751        try {
752            md = MessageDigest.getInstance("SHA-1");
753        } catch (NoSuchAlgorithmException ex) {
754            throw new RuntimeException(ex);
755        }
756
757        md.update(bytes, 32, bytes.length - 32);
758
759        try {
760            int amt = md.digest(bytes, 12, 20);
761            if (amt != 20) {
762                throw new RuntimeException("unexpected digest write: " + amt +
763                                           " bytes");
764            }
765        } catch (DigestException ex) {
766            throw new RuntimeException(ex);
767        }
768    }
769
770    /**
771     * Calculates the checksum for the <code>.dex</code> file in the
772     * given array, and modify the array to contain it.
773     *
774     * @param bytes non-null; the bytes of the file
775     */
776    public static void calcChecksum(byte[] bytes) {
777        Adler32 a32 = new Adler32();
778
779        a32.update(bytes, 12, bytes.length - 12);
780
781        int sum = (int) a32.getValue();
782
783        bytes[8]  = (byte) sum;
784        bytes[9]  = (byte) (sum >> 8);
785        bytes[10] = (byte) (sum >> 16);
786        bytes[11] = (byte) (sum >> 24);
787    }
788}