OSDN Git Service

Code drop from //branches/cupcake/...@124589
[android-x86/dalvik.git] / libdex / DexFile.h
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 /*
17  * Access .dex (Dalvik Executable Format) files.  The code here assumes that
18  * the DEX file has been rewritten (byte-swapped, word-aligned) and that
19  * the contents can be directly accessed as a collection of C arrays.  Please
20  * see docs/dalvik/dex-format.html for a detailed description.
21  *
22  * The structure and field names were chosen to match those in the DEX spec.
23  *
24  * It's generally assumed that the DEX file will be stored in shared memory,
25  * obviating the need to copy code and constant pool entries into newly
26  * allocated storage.  Maintaining local pointers to items in the shared area
27  * is valid and encouraged.
28  *
29  * All memory-mapped structures are 32-bit aligned unless otherwise noted.
30  */
31 #ifndef _LIBDEX_DEXFILE
32 #define _LIBDEX_DEXFILE
33
34 #include "vm/Common.h"      // basic type defs, e.g. u1/u2/u4/u8, and LOG
35 #include "libdex/SysUtil.h"
36
37 /*
38  * gcc-style inline management -- ensures we have a copy of all functions
39  * in the library, so code that links against us will work whether or not
40  * it was built with optimizations enabled.
41  */
42 #ifndef _DEX_GEN_INLINES             /* only defined by DexInlines.c */
43 # define DEX_INLINE extern __inline__
44 #else
45 # define DEX_INLINE
46 #endif
47
48 /* DEX file magic number */
49 #define DEX_MAGIC       "dex\n"
50 /* version, encoded in 4 bytes of ASCII */
51 #define DEX_MAGIC_VERS  "035\0"
52
53 /* same, but for optimized DEX header */
54 #define DEX_OPT_MAGIC   "dey\n"
55 #define DEX_OPT_MAGIC_VERS  "035\0"
56
57 #define DEX_DEP_MAGIC   "deps"
58
59 /*
60  * 160-bit SHA-1 digest.
61  */
62 enum { kSHA1DigestLen = 20,
63        kSHA1DigestOutputLen = kSHA1DigestLen*2 +1 };
64
65 /* general constants */
66 enum {
67     kDexEndianConstant = 0x12345678,    /* the endianness indicator */
68     kDexNoIndex = 0xffffffff,           /* not a valid index value */
69 };
70
71 /*
72  * access flags and masks; the "standard" ones are all <= 0x4000
73  * 
74  * Note: There are related declarations in vm/oo/Object.h in the ClassFlags
75  * enum.
76  */
77 enum {
78     ACC_PUBLIC       = 0x00000001,       // class, field, method, ic
79     ACC_PRIVATE      = 0x00000002,       // field, method, ic
80     ACC_PROTECTED    = 0x00000004,       // field, method, ic
81     ACC_STATIC       = 0x00000008,       // field, method, ic
82     ACC_FINAL        = 0x00000010,       // class, field, method, ic
83     ACC_SYNCHRONIZED = 0x00000020,       // method (only allowed on natives)
84     ACC_SUPER        = 0x00000020,       // class (not used in Dalvik)
85     ACC_VOLATILE     = 0x00000040,       // field
86     ACC_BRIDGE       = 0x00000040,       // method (1.5)
87     ACC_TRANSIENT    = 0x00000080,       // field
88     ACC_VARARGS      = 0x00000080,       // method (1.5)
89     ACC_NATIVE       = 0x00000100,       // method
90     ACC_INTERFACE    = 0x00000200,       // class, ic
91     ACC_ABSTRACT     = 0x00000400,       // class, method, ic
92     ACC_STRICT       = 0x00000800,       // method
93     ACC_SYNTHETIC    = 0x00001000,       // field, method, ic
94     ACC_ANNOTATION   = 0x00002000,       // class, ic (1.5)
95     ACC_ENUM         = 0x00004000,       // class, field, ic (1.5)
96     ACC_CONSTRUCTOR  = 0x00010000,       // method (Dalvik only)
97     ACC_DECLARED_SYNCHRONIZED =
98                        0x00020000,       // method (Dalvik only)
99     ACC_CLASS_MASK = 
100         (ACC_PUBLIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT
101                 | ACC_SYNTHETIC | ACC_ANNOTATION | ACC_ENUM),
102     ACC_INNER_CLASS_MASK =
103         (ACC_CLASS_MASK | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC),
104     ACC_FIELD_MASK =
105         (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL
106                 | ACC_VOLATILE | ACC_TRANSIENT | ACC_SYNTHETIC | ACC_ENUM),
107     ACC_METHOD_MASK =
108         (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL
109                 | ACC_SYNCHRONIZED | ACC_BRIDGE | ACC_VARARGS | ACC_NATIVE
110                 | ACC_ABSTRACT | ACC_STRICT | ACC_SYNTHETIC | ACC_CONSTRUCTOR
111                 | ACC_DECLARED_SYNCHRONIZED),
112 };
113
114 /* annotation constants */
115 enum {
116     kDexVisibilityBuild         = 0x00,     /* annotation visibility */
117     kDexVisibilityRuntime       = 0x01,
118     kDexVisibilitySystem        = 0x02,
119
120     kDexAnnotationByte          = 0x00,
121     kDexAnnotationShort         = 0x02,
122     kDexAnnotationChar          = 0x03,
123     kDexAnnotationInt           = 0x04,
124     kDexAnnotationLong          = 0x06,
125     kDexAnnotationFloat         = 0x10,
126     kDexAnnotationDouble        = 0x11,
127     kDexAnnotationString        = 0x17,
128     kDexAnnotationType          = 0x18,
129     kDexAnnotationField         = 0x19,
130     kDexAnnotationMethod        = 0x1a,
131     kDexAnnotationEnum          = 0x1b,
132     kDexAnnotationArray         = 0x1c,
133     kDexAnnotationAnnotation    = 0x1d,
134     kDexAnnotationNull          = 0x1e,
135     kDexAnnotationBoolean       = 0x1f,
136
137     kDexAnnotationValueTypeMask = 0x1f,     /* low 5 bits */
138     kDexAnnotationValueArgShift = 5,
139 };
140
141 /* map item type codes */
142 enum {
143     kDexTypeHeaderItem               = 0x0000,
144     kDexTypeStringIdItem             = 0x0001,
145     kDexTypeTypeIdItem               = 0x0002,
146     kDexTypeProtoIdItem              = 0x0003,
147     kDexTypeFieldIdItem              = 0x0004,
148     kDexTypeMethodIdItem             = 0x0005,
149     kDexTypeClassDefItem             = 0x0006,
150     kDexTypeMapList                  = 0x1000,
151     kDexTypeTypeList                 = 0x1001,
152     kDexTypeAnnotationSetRefList     = 0x1002,
153     kDexTypeAnnotationSetItem        = 0x1003,
154     kDexTypeClassDataItem            = 0x2000,
155     kDexTypeCodeItem                 = 0x2001,
156     kDexTypeStringDataItem           = 0x2002,
157     kDexTypeDebugInfoItem            = 0x2003,
158     kDexTypeAnnotationItem           = 0x2004,
159     kDexTypeEncodedArrayItem         = 0x2005,
160     kDexTypeAnnotationsDirectoryItem = 0x2006,
161 };
162
163 /* auxillary data section chunk codes */
164 enum {
165     kDexChunkClassLookup            = 0x434c4b50,   /* CLKP */
166
167     kDexChunkReducingIndexMap       = 0x5249584d,   /* RIXM */
168     kDexChunkExpandingIndexMap      = 0x4549584d,   /* EIXM */
169
170     kDexChunkEnd                    = 0x41454e44,   /* AEND */
171 };
172
173 /* debug info opcodes and constants */
174 enum {
175     DBG_END_SEQUENCE         = 0x00,
176     DBG_ADVANCE_PC           = 0x01,
177     DBG_ADVANCE_LINE         = 0x02,
178     DBG_START_LOCAL          = 0x03,
179     DBG_START_LOCAL_EXTENDED = 0x04,
180     DBG_END_LOCAL            = 0x05,
181     DBG_RESTART_LOCAL        = 0x06,
182     DBG_SET_PROLOGUE_END     = 0x07,
183     DBG_SET_EPILOGUE_BEGIN   = 0x08,
184     DBG_SET_FILE             = 0x09,
185     DBG_FIRST_SPECIAL        = 0x0a,
186     DBG_LINE_BASE            = -4,
187     DBG_LINE_RANGE           = 15,
188 };
189
190 /*
191  * Direct-mapped "header_item" struct.
192  */
193 typedef struct DexHeader {
194     u1  magic[8];           /* includes version number */
195     u4  checksum;           /* adler32 checksum */
196     u1  signature[kSHA1DigestLen]; /* SHA-1 hash */
197     u4  fileSize;           /* length of entire file */
198     u4  headerSize;         /* offset to start of next section */
199     u4  endianTag;
200     u4  linkSize;
201     u4  linkOff;
202     u4  mapOff;
203     u4  stringIdsSize;
204     u4  stringIdsOff;
205     u4  typeIdsSize;
206     u4  typeIdsOff;
207     u4  protoIdsSize;
208     u4  protoIdsOff;
209     u4  fieldIdsSize;
210     u4  fieldIdsOff;
211     u4  methodIdsSize;
212     u4  methodIdsOff;
213     u4  classDefsSize;
214     u4  classDefsOff;
215     u4  dataSize;
216     u4  dataOff;
217 } DexHeader;
218
219 /*
220  * Direct-mapped "map_item".
221  */
222 typedef struct DexMapItem {
223     u2  type;              /* type code (see kDexType* above) */
224     u2  unused;
225     u4  size;              /* count of items of the indicated type */
226     u4  offset;            /* file offset to the start of data */
227 } DexMapItem;
228
229 /*
230  * Direct-mapped "map_list".
231  */
232 typedef struct DexMapList {
233     u4  size;               /* #of entries in list */
234     DexMapItem list[1];     /* entries */
235 } DexMapList;
236
237 /*
238  * Direct-mapped "string_id_item".
239  */
240 typedef struct DexStringId {
241     u4  stringDataOff;      /* file offset to string_data_item */
242 } DexStringId;
243
244 /*
245  * Direct-mapped "type_id_item".
246  */
247 typedef struct DexTypeId {
248     u4  descriptorIdx;      /* index into stringIds list for type descriptor */
249 } DexTypeId;
250
251 /*
252  * Direct-mapped "field_id_item".
253  */
254 typedef struct DexFieldId {
255     u2  classIdx;           /* index into typeIds list for defining class */
256     u2  typeIdx;            /* index into typeIds for field type */
257     u4  nameIdx;            /* index into stringIds for field name */
258 } DexFieldId;
259
260 /*
261  * Direct-mapped "method_id_item".
262  */
263 typedef struct DexMethodId {
264     u2  classIdx;           /* index into typeIds list for defining class */
265     u2  protoIdx;           /* index into protoIds for method prototype */
266     u4  nameIdx;            /* index into stringIds for method name */
267 } DexMethodId;
268
269 /*
270  * Direct-mapped "proto_id_item".
271  */
272 typedef struct DexProtoId {
273     u4  shortyIdx;          /* index into stringIds for shorty descriptor */
274     u4  returnTypeIdx;      /* index into typeIds list for return type */
275     u4  parametersOff;      /* file offset to type_list for parameter types */
276 } DexProtoId;
277
278 /*
279  * Direct-mapped "class_def_item".
280  */
281 typedef struct DexClassDef {
282     u4  classIdx;           /* index into typeIds for this class */
283     u4  accessFlags;
284     u4  superclassIdx;      /* index into typeIds for superclass */
285     u4  interfacesOff;      /* file offset to DexTypeList */
286     u4  sourceFileIdx;      /* index into stringIds for source file name */
287     u4  annotationsOff;     /* file offset to annotations_directory_item */
288     u4  classDataOff;       /* file offset to class_data_item */
289     u4  staticValuesOff;    /* file offset to DexEncodedArray */
290 } DexClassDef;
291
292 /*
293  * Direct-mapped "type_item".
294  */
295 typedef struct DexTypeItem {
296     u2  typeIdx;            /* index into typeIds */
297 } DexTypeItem;
298
299 /*
300  * Direct-mapped "type_list".
301  */
302 typedef struct DexTypeList {
303     u4  size;               /* #of entries in list */
304     DexTypeItem list[1];    /* entries */
305 } DexTypeList;
306
307 /*
308  * Direct-mapped "code_item".
309  *
310  * The "catches" table is used when throwing an exception,
311  * "debugInfo" is used when displaying an exception stack trace or
312  * debugging. An offset of zero indicates that there are no entries.
313  */
314 typedef struct DexCode {
315     u2  registersSize;
316     u2  insSize;
317     u2  outsSize;
318     u2  triesSize;
319     u4  debugInfoOff;       /* file offset to debug info stream */
320     u4  insnsSize;          /* size of the insns array, in u2 units */
321     u2  insns[1];
322     /* followed by optional u2 padding */
323     /* followed by try_item[triesSize] */
324     /* followed by uleb128 handlersSize */
325     /* followed by catch_handler_item[handlersSize] */
326 } DexCode;
327
328 /*
329  * Direct-mapped "try_item".
330  */
331 typedef struct DexTry {
332     u4  startAddr;          /* start address, in 16-bit code units */
333     u2  insnCount;          /* instruction count, in 16-bit code units */
334     u2  handlerOff;         /* offset in encoded handler data to handlers */
335 } DexTry;
336
337 /*
338  * Link table.  Currently undefined.
339  */
340 typedef struct DexLink {
341     u1  bleargh;
342 } DexLink;
343
344
345 /*
346  * Direct-mapped "annotations_directory_item".
347  */
348 typedef struct DexAnnotationsDirectoryItem {
349     u4  classAnnotationsOff;  /* offset to DexAnnotationSetItem */
350     u4  fieldsSize;           /* count of DexFieldAnnotationsItem */
351     u4  methodsSize;          /* count of DexMethodAnnotationsItem */
352     u4  parametersSize;       /* count of DexParameterAnnotationsItem */
353     /* followed by DexFieldAnnotationsItem[fieldsSize] */
354     /* followed by DexMethodAnnotationsItem[methodsSize] */
355     /* followed by DexParameterAnnotationsItem[parametersSize] */
356 } DexAnnotationsDirectoryItem;
357
358 /*
359  * Direct-mapped "field_annotations_item".
360  */
361 typedef struct DexFieldAnnotationsItem {
362     u4  fieldIdx;
363     u4  annotationsOff;             /* offset to DexAnnotationSetItem */
364 } DexFieldAnnotationsItem;
365
366 /*
367  * Direct-mapped "method_annotations_item".
368  */
369 typedef struct DexMethodAnnotationsItem {
370     u4  methodIdx;
371     u4  annotationsOff;             /* offset to DexAnnotationSetItem */
372 } DexMethodAnnotationsItem;
373
374 /*
375  * Direct-mapped "parameter_annotations_item".
376  */
377 typedef struct DexParameterAnnotationsItem {
378     u4  methodIdx;
379     u4  annotationsOff;             /* offset to DexAnotationSetRefList */
380 } DexParameterAnnotationsItem;
381
382 /*
383  * Direct-mapped "annotation_set_ref_item".
384  */
385 typedef struct DexAnnotationSetRefItem {
386     u4  annotationsOff;             /* offset to DexAnnotationSetItem */
387 } DexAnnotationSetRefItem;
388
389 /*
390  * Direct-mapped "annotation_set_ref_list".
391  */
392 typedef struct DexAnnotationSetRefList {
393     u4  size;
394     DexAnnotationSetRefItem list[1];
395 } DexAnnotationSetRefList;
396
397 /*
398  * Direct-mapped "anotation_set_item".
399  */
400 typedef struct DexAnnotationSetItem {
401     u4  size;
402     u4  entries[1];                 /* offset to DexAnnotationItem */
403 } DexAnnotationSetItem;
404
405 /*
406  * Direct-mapped "annotation_item".
407  *
408  * NOTE: this structure is byte-aligned.
409  */
410 typedef struct DexAnnotationItem {
411     u1  visibility;
412     u1  annotation[1];              /* data in encoded_annotation format */
413 } DexAnnotationItem;
414
415 /*
416  * Direct-mapped "encoded_array".
417  *
418  * NOTE: this structure is byte-aligned.
419  */
420 typedef struct DexEncodedArray {
421     u1  array[1];                   /* data in encoded_array format */
422 } DexEncodedArray;
423
424 /*
425  * Lookup table for classes.  It provides a mapping from class name to
426  * class definition.  Used by dexFindClass().
427  *
428  * We calculate this at DEX optimization time and embed it in the file so we
429  * don't need the same hash table in every VM.  This is slightly slower than
430  * a hash table with direct pointers to the items, but because it's shared
431  * there's less of a penalty for using a fairly sparse table.
432  */
433 typedef struct DexClassLookup {
434     int     size;                       // total size, including "size"
435     int     numEntries;                 // size of table[]; always power of 2
436     struct {
437         u4      classDescriptorHash;    // class descriptor hash code
438         int     classDescriptorOffset;  // in bytes, from start of DEX
439         int     classDefOffset;         // in bytes, from start of DEX
440     } table[1];
441 } DexClassLookup;
442
443 /*
444  * Map constant pool indices from one form to another.  Some or all of these
445  * may be NULL.
446  *
447  * The map values are 16-bit unsigned values.  If the values we map to
448  * require a larger range, we omit the mapping for that category (which
449  * requires that the lookup code recognize that the data will not be
450  * there for all DEX files in all categories.)
451  */
452 typedef struct DexIndexMap {
453     const u2* classMap;         /* map, either expanding or reducing */
454     u4  classFullCount;         /* same as typeIdsSize */
455     u4  classReducedCount;      /* post-reduction count */
456     const u2* methodMap;
457     u4  methodFullCount;
458     u4  methodReducedCount;
459     const u2* fieldMap;
460     u4  fieldFullCount;
461     u4  fieldReducedCount;
462     const u2* stringMap;
463     u4  stringFullCount;
464     u4  stringReducedCount;
465 } DexIndexMap;
466
467 /*
468  * Header added by DEX optimization pass.  Values are always written in
469  * local byte and structure padding.  The first field (magic + version)
470  * is guaranteed to be present and directly readable for all expected
471  * compiler configurations; the rest is version-dependent.
472  *
473  * Try to keep this simple and fixed-size.
474  */
475 typedef struct DexOptHeader {
476     u1  magic[8];           /* includes version number */
477
478     u4  dexOffset;          /* file offset of DEX header */
479     u4  dexLength;
480     u4  depsOffset;         /* offset of optimized DEX dependency table */
481     u4  depsLength;
482     u4  auxOffset;          /* file offset of pre-calc auxillary data */
483     u4  auxLength;
484
485     u4  flags;              /* some info flags */
486
487     u4  padding;            /* induce 64-bit alignment */
488 } DexOptHeader;
489
490 #define DEX_FLAG_VERIFIED           (1)     /* tried to verify all classes */
491 #define DEX_OPT_FLAG_BIG            (1<<1)  /* swapped to big-endian */
492 #define DEX_OPT_FLAG_FIELDS         (1<<2)  /* field access optimized */
493 #define DEX_OPT_FLAG_INVOCATIONS    (1<<3)  /* method calls optimized */
494
495 #define DEX_INTERFACE_CACHE_SIZE    128     /* must be power of 2 */
496
497 /*
498  * Structure representing a DEX file.
499  *
500  * Code should regard DexFile as opaque, using the API calls provided here
501  * to access specific structures.
502  */
503 typedef struct DexFile {
504     /* directly-mapped "opt" header */
505     const DexOptHeader* pOptHeader;
506
507     /* pointers to directly-mapped structs and arrays in base DEX */
508     const DexHeader*    pHeader;
509     const DexStringId*  pStringIds;
510     const DexTypeId*    pTypeIds;
511     const DexFieldId*   pFieldIds;
512     const DexMethodId*  pMethodIds;
513     const DexProtoId*   pProtoIds;
514     const DexClassDef*  pClassDefs;
515     const DexLink*      pLinkData;
516
517     /* mapped in "auxillary" section */
518     const DexClassLookup* pClassLookup;
519
520     /* mapped in "auxillary" section */
521     DexIndexMap         indexMap;
522
523     /* points to start of DEX file data */
524     const u1*           baseAddr;
525
526     /* track memory overhead for auxillary structures */
527     int                 overhead;
528
529     /* additional app-specific data structures associated with the DEX */
530     //void*               auxData;
531 } DexFile;
532
533 /*
534  * Utility function -- rounds up to the nearest power of 2.
535  */
536 u4 dexRoundUpPower2(u4 val);
537
538 /*
539  * Parse an optimized or unoptimized .dex file sitting in memory.
540  *
541  * On success, return a newly-allocated DexFile.
542  */
543 DexFile* dexFileParse(const u1* data, size_t length, int flags);
544
545 /* bit values for "flags" argument to dexFileParse */
546 enum {
547     kDexParseDefault            = 0,
548     kDexParseVerifyChecksum     = 1,
549 };
550
551 /*
552  * Correct the byte ordering in a memory-mapped DEX file.  This is only
553  * required for code that opens "raw" DEX files, such as the DEX optimizer.
554  *
555  * Return 0 on success.
556  */
557 int dexFixByteOrdering(u1* addr, int len);
558
559 /*
560  * Free a DexFile structure, along with any associated structures.
561  */
562 void dexFileFree(DexFile* pDexFile);
563
564 /*
565  * Create class lookup table.
566  */
567 DexClassLookup* dexCreateClassLookup(DexFile* pDexFile);
568
569 /*
570  * Find a class definition by descriptor.
571  */
572 const DexClassDef* dexFindClass(const DexFile* pFile, const char* descriptor);
573
574 /*
575  * Set up the basic raw data pointers of a DexFile. This function isn't
576  * meant for general use.
577  */
578 void dexFileSetupBasicPointers(DexFile* pDexFile, const u1* data);
579
580 /* return the DexMapList of the file, if any */
581 DEX_INLINE const DexMapList* dexGetMap(const DexFile* pDexFile) {
582     u4 mapOff = pDexFile->pHeader->mapOff;
583
584     if (mapOff == 0) {
585         return NULL;
586     } else {
587         return (const DexMapList*) (pDexFile->baseAddr + mapOff);
588     }
589 }
590
591 /* return the const char* string data referred to by the given string_id */
592 DEX_INLINE const char* dexGetStringData(const DexFile* pDexFile,
593         const DexStringId* pStringId) {
594     const u1* ptr = pDexFile->baseAddr + pStringId->stringDataOff;
595
596     // Skip the uleb128 length.
597     while (*(ptr++) > 0x7f) /* empty */ ;
598
599     return (const char*) ptr;
600 }
601 /* return the StringId with the specified index */
602 DEX_INLINE const DexStringId* dexGetStringId(const DexFile* pDexFile, u4 idx) {
603     assert(idx < pDexFile->pHeader->stringIdsSize);
604     return &pDexFile->pStringIds[idx];
605 }
606 /* return the UTF-8 encoded string with the specified string_id index */
607 DEX_INLINE const char* dexStringById(const DexFile* pDexFile, u4 idx) {
608     const DexStringId* pStringId = dexGetStringId(pDexFile, idx);
609     return dexGetStringData(pDexFile, pStringId);
610 }
611
612 /* Return the UTF-8 encoded string with the specified string_id index,
613  * also filling in the UTF-16 size (number of 16-bit code points).*/
614 const char* dexStringAndSizeById(const DexFile* pDexFile, u4 idx,
615         u4* utf16Size);
616
617 /* return the TypeId with the specified index */
618 DEX_INLINE const DexTypeId* dexGetTypeId(const DexFile* pDexFile, u4 idx) {
619     assert(idx < pDexFile->pHeader->typeIdsSize);
620     return &pDexFile->pTypeIds[idx];
621 }
622
623 /*
624  * Get the descriptor string associated with a given type index.
625  * The caller should not free() the returned string.
626  */
627 DEX_INLINE const char* dexStringByTypeIdx(const DexFile* pDexFile, u4 idx) {
628     const DexTypeId* typeId = dexGetTypeId(pDexFile, idx);
629     return dexStringById(pDexFile, typeId->descriptorIdx);
630 }
631
632 /* return the MethodId with the specified index */
633 DEX_INLINE const DexMethodId* dexGetMethodId(const DexFile* pDexFile, u4 idx) {
634     assert(idx < pDexFile->pHeader->methodIdsSize);
635     return &pDexFile->pMethodIds[idx];
636 }
637
638 /* return the FieldId with the specified index */
639 DEX_INLINE const DexFieldId* dexGetFieldId(const DexFile* pDexFile, u4 idx) {
640     assert(idx < pDexFile->pHeader->fieldIdsSize);
641     return &pDexFile->pFieldIds[idx];
642 }
643
644 /* return the ProtoId with the specified index */
645 DEX_INLINE const DexProtoId* dexGetProtoId(const DexFile* pDexFile, u4 idx) {
646     assert(idx < pDexFile->pHeader->protoIdsSize);
647     return &pDexFile->pProtoIds[idx];
648 }
649
650 /*
651  * Get the parameter list from a ProtoId. The returns NULL if the ProtoId
652  * does not have a parameter list.
653  */
654 DEX_INLINE const DexTypeList* dexGetProtoParameters(
655     const DexFile *pDexFile, const DexProtoId* pProtoId) {
656     if (pProtoId->parametersOff == 0) {
657         return NULL;
658     }
659     return (const DexTypeList*)
660         (pDexFile->baseAddr + pProtoId->parametersOff);
661 }
662
663 /* return the ClassDef with the specified index */
664 DEX_INLINE const DexClassDef* dexGetClassDef(const DexFile* pDexFile, u4 idx) {
665     assert(idx < pDexFile->pHeader->classDefsSize);
666     return &pDexFile->pClassDefs[idx];
667 }
668
669 /* get the interface list for a DexClass */
670 DEX_INLINE const DexTypeList* dexGetInterfacesList(const DexFile* pDexFile,
671     const DexClassDef* pClassDef)
672 {
673     if (pClassDef->interfacesOff == 0)
674         return NULL;
675     return (const DexTypeList*)
676         (pDexFile->baseAddr + pClassDef->interfacesOff);
677 }
678 /* return the Nth entry in a DexTypeList. */
679 DEX_INLINE const DexTypeItem* dexGetTypeItem(const DexTypeList* pList,
680     u4 idx)
681 {
682     assert(idx < pList->size);
683     return &pList->list[idx];
684 }
685 /* return the type_idx for the Nth entry in a TypeList */
686 DEX_INLINE u4 dexTypeListGetIdx(const DexTypeList* pList, u4 idx) {
687     const DexTypeItem* pItem = dexGetTypeItem(pList, idx);
688     return pItem->typeIdx;
689 }
690
691 /* get the static values list for a DexClass */
692 DEX_INLINE const DexEncodedArray* dexGetStaticValuesList(
693     const DexFile* pDexFile, const DexClassDef* pClassDef)
694 {
695     if (pClassDef->staticValuesOff == 0)
696         return NULL;
697     return (const DexEncodedArray*)
698         (pDexFile->baseAddr + pClassDef->staticValuesOff);
699 }
700
701 /* get the annotations directory item for a DexClass */
702 DEX_INLINE const DexAnnotationsDirectoryItem* dexGetAnnotationsDirectoryItem(
703     const DexFile* pDexFile, const DexClassDef* pClassDef)
704 {
705     if (pClassDef->annotationsOff == 0)
706         return NULL;
707     return (const DexAnnotationsDirectoryItem*)
708         (pDexFile->baseAddr + pClassDef->annotationsOff);
709 }
710
711 /* get the source file string */
712 DEX_INLINE const char* dexGetSourceFile(
713     const DexFile* pDexFile, const DexClassDef* pClassDef)
714 {
715     if (pClassDef->sourceFileIdx == 0xffffffff)
716         return NULL;
717     return dexStringById(pDexFile, pClassDef->sourceFileIdx);
718 }
719
720 /* Get the list of "tries" for the given DexCode. */
721 DEX_INLINE const DexTry* dexGetTries(const DexCode* pCode) {
722     const u2* insnsEnd = &pCode->insns[pCode->insnsSize];
723
724     // Round to four bytes.
725     if ((((u4) insnsEnd) & 3) != 0) {
726         insnsEnd++;
727     }
728     
729     return (const DexTry*) insnsEnd;
730 }
731
732 /* Get the base of the encoded data for the given DexCode. */
733 DEX_INLINE const u1* dexGetCatchHandlerData(const DexCode* pCode) {
734     const DexTry* pTries = dexGetTries(pCode);
735     return (const u1*) &pTries[pCode->triesSize];
736 }
737
738 DEX_INLINE const u1* dexGetDebugInfoStream(const DexFile* pDexFile,
739     const DexCode* pCode)
740 {
741     if (pCode->debugInfoOff == 0) {
742         return NULL;
743     } else {
744         return pDexFile->baseAddr + pCode->debugInfoOff;
745     }
746 }
747
748 /*
749  * Callback for "new position table entry".
750  * Returning non-0 causes the decoder to stop early.
751  */
752 typedef int (*DexDebugNewPositionCb)(void *cnxt, u4 address, u4 lineNum);
753
754 /*
755  * Callback for "new locals table entry". "signature" is an empty string
756  * if no signature is available for an entry.
757  */
758 typedef void (*DexDebugNewLocalCb)(void *cnxt, u2 reg, u4 startAddress,
759         u4 endAddress, const char *name, const char *descriptor,
760         const char *signature);
761
762 /*
763  * Decode debug info for method.
764  * 
765  * posCb is called in ascending address order.
766  * localCb is called in order of ascending end address.
767  */
768 void dexDecodeDebugInfo(
769             const DexFile* pDexFile,
770             const DexCode* pDexCode,
771             const char* classDescriptor,
772             u4 protoIdx,
773             u4 accessFlags,
774             DexDebugNewPositionCb posCb, DexDebugNewLocalCb localCb,
775             void* cnxt);
776
777 /* DexClassDef convenience - get class descriptor */
778 DEX_INLINE const char* dexGetClassDescriptor(const DexFile* pDexFile,
779     const DexClassDef* pClassDef)
780 {
781     return dexStringByTypeIdx(pDexFile, pClassDef->classIdx);
782 }
783
784 /* DexClassDef convenience - get superclass descriptor */
785 DEX_INLINE const char* dexGetSuperClassDescriptor(const DexFile* pDexFile,
786     const DexClassDef* pClassDef)
787 {
788     if (pClassDef->superclassIdx == 0)
789         return NULL;
790     return dexStringByTypeIdx(pDexFile, pClassDef->superclassIdx);
791 }
792
793 /* DexClassDef convenience - get class_data_item pointer */
794 DEX_INLINE const u1* dexGetClassData(const DexFile* pDexFile,
795     const DexClassDef* pClassDef)
796 {
797     if (pClassDef->classDataOff == 0)
798         return NULL;
799     return (const u1*) (pDexFile->baseAddr + pClassDef->classDataOff);
800 }
801
802 /* Get an annotation set at a particular offset. */
803 DEX_INLINE const DexAnnotationSetItem* dexGetAnnotationSetItem(
804     const DexFile* pDexFile, u4 offset)
805 {
806     return (const DexAnnotationSetItem*) (pDexFile->baseAddr + offset);
807 }
808 /* get the class' annotation set */
809 DEX_INLINE const DexAnnotationSetItem* dexGetClassAnnotationSet(
810     const DexFile* pDexFile, const DexAnnotationsDirectoryItem* pAnnoDir)
811 {
812     if (pAnnoDir->classAnnotationsOff == 0)
813         return NULL;
814     return dexGetAnnotationSetItem(pDexFile, pAnnoDir->classAnnotationsOff);
815 }
816
817 /* get the class' field annotation list */
818 DEX_INLINE const DexFieldAnnotationsItem* dexGetFieldAnnotations(
819     const DexFile* pDexFile, const DexAnnotationsDirectoryItem* pAnnoDir)
820 {
821     if (pAnnoDir->fieldsSize == 0)
822         return NULL;
823
824     // Skip past the header to the start of the field annotations.
825     return (const DexFieldAnnotationsItem*) &pAnnoDir[1];
826 }
827
828 /* get field annotation list size */
829 DEX_INLINE int dexGetFieldAnnotationsSize(const DexFile* pDexFile,
830     const DexAnnotationsDirectoryItem* pAnnoDir)
831 {
832     return pAnnoDir->fieldsSize;
833 }
834
835 /* return a pointer to the field's annotation set */
836 DEX_INLINE const DexAnnotationSetItem* dexGetFieldAnnotationSetItem(
837     const DexFile* pDexFile, const DexFieldAnnotationsItem* pItem)
838 {
839     return dexGetAnnotationSetItem(pDexFile, pItem->annotationsOff);
840 }
841
842 /* get the class' method annotation list */
843 DEX_INLINE const DexMethodAnnotationsItem* dexGetMethodAnnotations(
844     const DexFile* pDexFile, const DexAnnotationsDirectoryItem* pAnnoDir)
845 {
846     if (pAnnoDir->methodsSize == 0)
847         return NULL;
848
849     /*
850      * Skip past the header and field annotations to the start of the
851      * method annotations.
852      */
853     const u1* addr = (const u1*) &pAnnoDir[1];
854     addr += pAnnoDir->fieldsSize * sizeof (DexFieldAnnotationsItem);
855     return (const DexMethodAnnotationsItem*) addr;
856 }
857
858 /* get method annotation list size */
859 DEX_INLINE int dexGetMethodAnnotationsSize(const DexFile* pDexFile,
860     const DexAnnotationsDirectoryItem* pAnnoDir)
861 {
862     return pAnnoDir->methodsSize;
863 }
864
865 /* return a pointer to the method's annotation set */
866 DEX_INLINE const DexAnnotationSetItem* dexGetMethodAnnotationSetItem(
867     const DexFile* pDexFile, const DexMethodAnnotationsItem* pItem)
868 {
869     return dexGetAnnotationSetItem(pDexFile, pItem->annotationsOff);
870 }
871
872 /* get the class' parameter annotation list */
873 DEX_INLINE const DexParameterAnnotationsItem* dexGetParameterAnnotations(
874     const DexFile* pDexFile, const DexAnnotationsDirectoryItem* pAnnoDir)
875 {
876     if (pAnnoDir->parametersSize == 0)
877         return NULL;
878
879     /*
880      * Skip past the header, field annotations, and method annotations
881      * to the start of the parameter annotations.
882      */
883     const u1* addr = (const u1*) &pAnnoDir[1];
884     addr += pAnnoDir->fieldsSize * sizeof (DexFieldAnnotationsItem);
885     addr += pAnnoDir->methodsSize * sizeof (DexMethodAnnotationsItem);
886     return (const DexParameterAnnotationsItem*) addr;
887 }
888
889 /* get method annotation list size */
890 DEX_INLINE int dexGetParameterAnnotationsSize(const DexFile* pDexFile,
891     const DexAnnotationsDirectoryItem* pAnnoDir)
892 {
893     return pAnnoDir->parametersSize;
894 }
895
896 /* return the parameter annotation ref list */
897 DEX_INLINE const DexAnnotationSetRefList* dexGetParameterAnnotationSetRefList(
898     const DexFile* pDexFile, const DexParameterAnnotationsItem* pItem)
899 {
900     return (const DexAnnotationSetRefList*)
901         (pDexFile->baseAddr + pItem->annotationsOff);
902 }
903
904 /* get method annotation list size */
905 DEX_INLINE int dexGetParameterAnnotationSetRefSize(const DexFile* pDexFile,
906     const DexParameterAnnotationsItem* pItem)
907 {
908     if (pItem->annotationsOff == 0)
909         return 0;
910     return dexGetParameterAnnotationSetRefList(pDexFile, pItem)->size;
911 }
912
913 /* return the Nth entry from an annotation set ref list */
914 DEX_INLINE const DexAnnotationSetRefItem* dexGetParameterAnnotationSetRef(
915     const DexAnnotationSetRefList* pList, u4 idx)
916 {
917     assert(idx < pList->size);
918     return &pList->list[idx];
919 }
920
921 /* given a DexAnnotationSetRefItem, return the DexAnnotationSetItem */
922 DEX_INLINE const DexAnnotationSetItem* dexGetSetRefItemItem(
923     const DexFile* pDexFile, const DexAnnotationSetRefItem* pItem)
924 {
925     return dexGetAnnotationSetItem(pDexFile, pItem->annotationsOff);
926 }
927
928 /* return the Nth annotation offset from a DexAnnotationSetItem */
929 DEX_INLINE u4 dexGetAnnotationOff(
930     const DexAnnotationSetItem* pAnnoSet, u4 idx)
931 {
932     assert(idx < pAnnoSet->size);
933     return pAnnoSet->entries[idx];
934 }
935
936 /* return the Nth annotation item from a DexAnnotationSetItem */
937 DEX_INLINE const DexAnnotationItem* dexGetAnnotationItem(
938     const DexFile* pDexFile, const DexAnnotationSetItem* pAnnoSet, u4 idx)
939 {
940     return (const DexAnnotationItem*)
941         (pDexFile->baseAddr + dexGetAnnotationOff(pAnnoSet, idx));
942 }
943
944
945 /*
946  * ===========================================================================
947  *      Utility Functions
948  * ===========================================================================
949  */
950
951 /*
952  * Retrieve the next UTF-16 character from a UTF-8 string.
953  *
954  * Advances "*pUtf8Ptr" to the start of the next character.
955  *
956  * WARNING: If a string is corrupted by dropping a '\0' in the middle
957  * of a 3-byte sequence, you can end up overrunning the buffer with
958  * reads (and possibly with the writes if the length was computed and
959  * cached before the damage). For performance reasons, this function
960  * assumes that the string being parsed is known to be valid (e.g., by
961  * already being verified). Most strings we process here are coming
962  * out of dex files or other internal translations, so the only real
963  * risk comes from the JNI NewStringUTF call.
964  */
965 DEX_INLINE u2 dexGetUtf16FromUtf8(const char** pUtf8Ptr)
966 {
967     unsigned int one, two, three;
968
969     one = *(*pUtf8Ptr)++;
970     if ((one & 0x80) != 0) {
971         /* two- or three-byte encoding */
972         two = *(*pUtf8Ptr)++;
973         if ((one & 0x20) != 0) {
974             /* three-byte encoding */
975             three = *(*pUtf8Ptr)++;
976             return ((one & 0x0f) << 12) |
977                    ((two & 0x3f) << 6) |
978                    (three & 0x3f);
979         } else {
980             /* two-byte encoding */
981             return ((one & 0x1f) << 6) |
982                    (two & 0x3f);
983         }
984     } else {
985         /* one-byte encoding */
986         return one;
987     }
988 }
989
990 /* Compare two '\0'-terminated modified UTF-8 strings, using Unicode
991  * code point values for comparison. This treats different encodings
992  * for the same code point as equivalent, except that only a real '\0'
993  * byte is considered the string terminator. The return value is as
994  * for strcmp(). */
995 int dexUtf8Cmp(const char* s1, const char* s2);
996
997
998 /* for dexIsValidMemberNameUtf8(), a bit vector indicating valid low ascii */
999 extern u4 DEX_MEMBER_VALID_LOW_ASCII[4];
1000
1001 /* Helper for dexIsValidMemberUtf8(); do not call directly. */
1002 bool dexIsValidMemberNameUtf8_0(const char** pUtf8Ptr);
1003
1004 /* Return whether the pointed-at modified-UTF-8 encoded character is
1005  * valid as part of a member name, updating the pointer to point past
1006  * the consumed character. This will consume two encoded UTF-16 code
1007  * points if the character is encoded as a surrogate pair. Also, if
1008  * this function returns false, then the given pointer may only have
1009  * been partially advanced. */
1010 DEX_INLINE bool dexIsValidMemberNameUtf8(const char** pUtf8Ptr) {
1011     u1 c = (u1) **pUtf8Ptr;
1012     if (c <= 0x7f) {
1013         // It's low-ascii, so check the table.
1014         u4 wordIdx = c >> 5;
1015         u4 bitIdx = c & 0x1f;
1016         (*pUtf8Ptr)++;
1017         return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
1018     }
1019
1020     /*
1021      * It's a multibyte encoded character. Call a non-inline function
1022      * for the heavy lifting.
1023      */
1024     return dexIsValidMemberNameUtf8_0(pUtf8Ptr);
1025 }
1026
1027 /* Return whether the given string is a valid field or method name. */
1028 bool dexIsValidMemberName(const char* s);
1029
1030 /* Return whether the given string is a valid type descriptor. */
1031 bool dexIsValidTypeDescriptor(const char* s);
1032
1033 /* Return whether the given string is a valid reference descriptor. This
1034  * is true if dexIsValidTypeDescriptor() returns true and the descriptor
1035  * is for a class or array and not a primitive type. */
1036 bool dexIsReferenceDescriptor(const char* s);
1037
1038 /* Return whether the given string is a valid class descriptor. This
1039  * is true if dexIsValidTypeDescriptor() returns true and the descriptor
1040  * is for a class and not an array or primitive type. */
1041 bool dexIsClassDescriptor(const char* s);
1042
1043 /* Return whether the given string is a valid field type descriptor. This
1044  * is true if dexIsValidTypeDescriptor() returns true and the descriptor
1045  * is for anything but "void". */
1046 bool dexIsFieldDescriptor(const char* s);
1047
1048 #endif /*_LIBDEX_DEXFILE*/