Home | History | Annotate | Download | only in c
      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 /* common includes */
     18 #include "Dalvik.h"
     19 #include "interp/InterpDefs.h"
     20 #include "mterp/Mterp.h"
     21 #include <math.h>                   // needed for fmod, fmodf
     22 #include "mterp/common/FindInterface.h"
     23 
     24 /*
     25  * Configuration defines.  These affect the C implementations, i.e. the
     26  * portable interpreter(s) and C stubs.
     27  *
     28  * Some defines are controlled by the Makefile, e.g.:
     29  *   WITH_INSTR_CHECKS
     30  *   WITH_TRACKREF_CHECKS
     31  *   EASY_GDB
     32  *   NDEBUG
     33  */
     34 
     35 #ifdef WITH_INSTR_CHECKS            /* instruction-level paranoia (slow!) */
     36 # define CHECK_BRANCH_OFFSETS
     37 # define CHECK_REGISTER_INDICES
     38 #endif
     39 
     40 /*
     41  * Some architectures require 64-bit alignment for access to 64-bit data
     42  * types.  We can't just use pointers to copy 64-bit values out of our
     43  * interpreted register set, because gcc may assume the pointer target is
     44  * aligned and generate invalid code.
     45  *
     46  * There are two common approaches:
     47  *  (1) Use a union that defines a 32-bit pair and a 64-bit value.
     48  *  (2) Call memcpy().
     49  *
     50  * Depending upon what compiler you're using and what options are specified,
     51  * one may be faster than the other.  For example, the compiler might
     52  * convert a memcpy() of 8 bytes into a series of instructions and omit
     53  * the call.  The union version could cause some strange side-effects,
     54  * e.g. for a while ARM gcc thought it needed separate storage for each
     55  * inlined instance, and generated instructions to zero out ~700 bytes of
     56  * stack space at the top of the interpreter.
     57  *
     58  * The default is to use memcpy().  The current gcc for ARM seems to do
     59  * better with the union.
     60  */
     61 #if defined(__ARM_EABI__)
     62 # define NO_UNALIGN_64__UNION
     63 #endif
     64 
     65 
     66 //#define LOG_INSTR                   /* verbose debugging */
     67 /* set and adjust ANDROID_LOG_TAGS='*:i jdwp:i dalvikvm:i dalvikvmi:i' */
     68 
     69 /*
     70  * Export another copy of the PC on every instruction; this is largely
     71  * redundant with EXPORT_PC and the debugger code.  This value can be
     72  * compared against what we have stored on the stack with EXPORT_PC to
     73  * help ensure that we aren't missing any export calls.
     74  */
     75 #if WITH_EXTRA_GC_CHECKS > 1
     76 # define EXPORT_EXTRA_PC() (self->currentPc2 = pc)
     77 #else
     78 # define EXPORT_EXTRA_PC()
     79 #endif
     80 
     81 /*
     82  * Adjust the program counter.  "_offset" is a signed int, in 16-bit units.
     83  *
     84  * Assumes the existence of "const u2* pc" and "const u2* curMethod->insns".
     85  *
     86  * We don't advance the program counter until we finish an instruction or
     87  * branch, because we do want to have to unroll the PC if there's an
     88  * exception.
     89  */
     90 #ifdef CHECK_BRANCH_OFFSETS
     91 # define ADJUST_PC(_offset) do {                                            \
     92         int myoff = _offset;        /* deref only once */                   \
     93         if (pc + myoff < curMethod->insns ||                                \
     94             pc + myoff >= curMethod->insns + dvmGetMethodInsnsSize(curMethod)) \
     95         {                                                                   \
     96             char* desc;                                                     \
     97             desc = dexProtoCopyMethodDescriptor(&curMethod->prototype);     \
     98             ALOGE("Invalid branch %d at 0x%04x in %s.%s %s",                 \
     99                 myoff, (int) (pc - curMethod->insns),                       \
    100                 curMethod->clazz->descriptor, curMethod->name, desc);       \
    101             free(desc);                                                     \
    102             dvmAbort();                                                     \
    103         }                                                                   \
    104         pc += myoff;                                                        \
    105         EXPORT_EXTRA_PC();                                                  \
    106     } while (false)
    107 #else
    108 # define ADJUST_PC(_offset) do {                                            \
    109         pc += _offset;                                                      \
    110         EXPORT_EXTRA_PC();                                                  \
    111     } while (false)
    112 #endif
    113 
    114 /*
    115  * If enabled, log instructions as we execute them.
    116  */
    117 #ifdef LOG_INSTR
    118 # define ILOGD(...) ILOG(LOG_DEBUG, __VA_ARGS__)
    119 # define ILOGV(...) ILOG(LOG_VERBOSE, __VA_ARGS__)
    120 # define ILOG(_level, ...) do {                                             \
    121         char debugStrBuf[128];                                              \
    122         snprintf(debugStrBuf, sizeof(debugStrBuf), __VA_ARGS__);            \
    123         if (curMethod != NULL)                                              \
    124             ALOG(_level, LOG_TAG"i", "%-2d|%04x%s",                          \
    125                 self->threadId, (int)(pc - curMethod->insns), debugStrBuf); \
    126         else                                                                \
    127             ALOG(_level, LOG_TAG"i", "%-2d|####%s",                          \
    128                 self->threadId, debugStrBuf);                               \
    129     } while(false)
    130 void dvmDumpRegs(const Method* method, const u4* framePtr, bool inOnly);
    131 # define DUMP_REGS(_meth, _frame, _inOnly) dvmDumpRegs(_meth, _frame, _inOnly)
    132 static const char kSpacing[] = "            ";
    133 #else
    134 # define ILOGD(...) ((void)0)
    135 # define ILOGV(...) ((void)0)
    136 # define DUMP_REGS(_meth, _frame, _inOnly) ((void)0)
    137 #endif
    138 
    139 /* get a long from an array of u4 */
    140 static inline s8 getLongFromArray(const u4* ptr, int idx)
    141 {
    142 #if defined(NO_UNALIGN_64__UNION)
    143     union { s8 ll; u4 parts[2]; } conv;
    144 
    145     ptr += idx;
    146     conv.parts[0] = ptr[0];
    147     conv.parts[1] = ptr[1];
    148     return conv.ll;
    149 #else
    150     s8 val;
    151     memcpy(&val, &ptr[idx], 8);
    152     return val;
    153 #endif
    154 }
    155 
    156 /* store a long into an array of u4 */
    157 static inline void putLongToArray(u4* ptr, int idx, s8 val)
    158 {
    159 #if defined(NO_UNALIGN_64__UNION)
    160     union { s8 ll; u4 parts[2]; } conv;
    161 
    162     ptr += idx;
    163     conv.ll = val;
    164     ptr[0] = conv.parts[0];
    165     ptr[1] = conv.parts[1];
    166 #else
    167     memcpy(&ptr[idx], &val, 8);
    168 #endif
    169 }
    170 
    171 /* get a double from an array of u4 */
    172 static inline double getDoubleFromArray(const u4* ptr, int idx)
    173 {
    174 #if defined(NO_UNALIGN_64__UNION)
    175     union { double d; u4 parts[2]; } conv;
    176 
    177     ptr += idx;
    178     conv.parts[0] = ptr[0];
    179     conv.parts[1] = ptr[1];
    180     return conv.d;
    181 #else
    182     double dval;
    183     memcpy(&dval, &ptr[idx], 8);
    184     return dval;
    185 #endif
    186 }
    187 
    188 /* store a double into an array of u4 */
    189 static inline void putDoubleToArray(u4* ptr, int idx, double dval)
    190 {
    191 #if defined(NO_UNALIGN_64__UNION)
    192     union { double d; u4 parts[2]; } conv;
    193 
    194     ptr += idx;
    195     conv.d = dval;
    196     ptr[0] = conv.parts[0];
    197     ptr[1] = conv.parts[1];
    198 #else
    199     memcpy(&ptr[idx], &dval, 8);
    200 #endif
    201 }
    202 
    203 /*
    204  * If enabled, validate the register number on every access.  Otherwise,
    205  * just do an array access.
    206  *
    207  * Assumes the existence of "u4* fp".
    208  *
    209  * "_idx" may be referenced more than once.
    210  */
    211 #ifdef CHECK_REGISTER_INDICES
    212 # define GET_REGISTER(_idx) \
    213     ( (_idx) < curMethod->registersSize ? \
    214         (fp[(_idx)]) : (assert(!"bad reg"),1969) )
    215 # define SET_REGISTER(_idx, _val) \
    216     ( (_idx) < curMethod->registersSize ? \
    217         (fp[(_idx)] = (u4)(_val)) : (assert(!"bad reg"),1969) )
    218 # define GET_REGISTER_AS_OBJECT(_idx)       ((Object *)GET_REGISTER(_idx))
    219 # define SET_REGISTER_AS_OBJECT(_idx, _val) SET_REGISTER(_idx, (s4)_val)
    220 # define GET_REGISTER_INT(_idx) ((s4) GET_REGISTER(_idx))
    221 # define SET_REGISTER_INT(_idx, _val) SET_REGISTER(_idx, (s4)_val)
    222 # define GET_REGISTER_WIDE(_idx) \
    223     ( (_idx) < curMethod->registersSize-1 ? \
    224         getLongFromArray(fp, (_idx)) : (assert(!"bad reg"),1969) )
    225 # define SET_REGISTER_WIDE(_idx, _val) \
    226     ( (_idx) < curMethod->registersSize-1 ? \
    227         (void)putLongToArray(fp, (_idx), (_val)) : assert(!"bad reg") )
    228 # define GET_REGISTER_FLOAT(_idx) \
    229     ( (_idx) < curMethod->registersSize ? \
    230         (*((float*) &fp[(_idx)])) : (assert(!"bad reg"),1969.0f) )
    231 # define SET_REGISTER_FLOAT(_idx, _val) \
    232     ( (_idx) < curMethod->registersSize ? \
    233         (*((float*) &fp[(_idx)]) = (_val)) : (assert(!"bad reg"),1969.0f) )
    234 # define GET_REGISTER_DOUBLE(_idx) \
    235     ( (_idx) < curMethod->registersSize-1 ? \
    236         getDoubleFromArray(fp, (_idx)) : (assert(!"bad reg"),1969.0) )
    237 # define SET_REGISTER_DOUBLE(_idx, _val) \
    238     ( (_idx) < curMethod->registersSize-1 ? \
    239         (void)putDoubleToArray(fp, (_idx), (_val)) : assert(!"bad reg") )
    240 #else
    241 # define GET_REGISTER(_idx)                 (fp[(_idx)])
    242 # define SET_REGISTER(_idx, _val)           (fp[(_idx)] = (_val))
    243 # define GET_REGISTER_AS_OBJECT(_idx)       ((Object*) fp[(_idx)])
    244 # define SET_REGISTER_AS_OBJECT(_idx, _val) (fp[(_idx)] = (u4)(_val))
    245 # define GET_REGISTER_INT(_idx)             ((s4)GET_REGISTER(_idx))
    246 # define SET_REGISTER_INT(_idx, _val)       SET_REGISTER(_idx, (s4)_val)
    247 # define GET_REGISTER_WIDE(_idx)            getLongFromArray(fp, (_idx))
    248 # define SET_REGISTER_WIDE(_idx, _val)      putLongToArray(fp, (_idx), (_val))
    249 # define GET_REGISTER_FLOAT(_idx)           (*((float*) &fp[(_idx)]))
    250 # define SET_REGISTER_FLOAT(_idx, _val)     (*((float*) &fp[(_idx)]) = (_val))
    251 # define GET_REGISTER_DOUBLE(_idx)          getDoubleFromArray(fp, (_idx))
    252 # define SET_REGISTER_DOUBLE(_idx, _val)    putDoubleToArray(fp, (_idx), (_val))
    253 #endif
    254 
    255 /*
    256  * Get 16 bits from the specified offset of the program counter.  We always
    257  * want to load 16 bits at a time from the instruction stream -- it's more
    258  * efficient than 8 and won't have the alignment problems that 32 might.
    259  *
    260  * Assumes existence of "const u2* pc".
    261  */
    262 #define FETCH(_offset)     (pc[(_offset)])
    263 
    264 /*
    265  * Extract instruction byte from 16-bit fetch (_inst is a u2).
    266  */
    267 #define INST_INST(_inst)    ((_inst) & 0xff)
    268 
    269 /*
    270  * Replace the opcode (used when handling breakpoints).  _opcode is a u1.
    271  */
    272 #define INST_REPLACE_OP(_inst, _opcode) (((_inst) & 0xff00) | _opcode)
    273 
    274 /*
    275  * Extract the "vA, vB" 4-bit registers from the instruction word (_inst is u2).
    276  */
    277 #define INST_A(_inst)       (((_inst) >> 8) & 0x0f)
    278 #define INST_B(_inst)       ((_inst) >> 12)
    279 
    280 /*
    281  * Get the 8-bit "vAA" 8-bit register index from the instruction word.
    282  * (_inst is u2)
    283  */
    284 #define INST_AA(_inst)      ((_inst) >> 8)
    285 
    286 /*
    287  * The current PC must be available to Throwable constructors, e.g.
    288  * those created by the various exception throw routines, so that the
    289  * exception stack trace can be generated correctly.  If we don't do this,
    290  * the offset within the current method won't be shown correctly.  See the
    291  * notes in Exception.c.
    292  *
    293  * This is also used to determine the address for precise GC.
    294  *
    295  * Assumes existence of "u4* fp" and "const u2* pc".
    296  */
    297 #define EXPORT_PC()         (SAVEAREA_FROM_FP(fp)->xtra.currentPc = pc)
    298 
    299 /*
    300  * Check to see if "obj" is NULL.  If so, throw an exception.  Assumes the
    301  * pc has already been exported to the stack.
    302  *
    303  * Perform additional checks on debug builds.
    304  *
    305  * Use this to check for NULL when the instruction handler calls into
    306  * something that could throw an exception (so we have already called
    307  * EXPORT_PC at the top).
    308  */
    309 static inline bool checkForNull(Object* obj)
    310 {
    311     if (obj == NULL) {
    312         dvmThrowNullPointerException(NULL);
    313         return false;
    314     }
    315 #ifdef WITH_EXTRA_OBJECT_VALIDATION
    316     if (!dvmIsHeapAddress(obj)) {
    317         ALOGE("Invalid object %p", obj);
    318         dvmAbort();
    319     }
    320 #endif
    321 #ifndef NDEBUG
    322     if (obj->clazz == NULL || ((u4) obj->clazz) <= 65536) {
    323         /* probable heap corruption */
    324         ALOGE("Invalid object class %p (in %p)", obj->clazz, obj);
    325         dvmAbort();
    326     }
    327 #endif
    328     return true;
    329 }
    330 
    331 /*
    332  * Check to see if "obj" is NULL.  If so, export the PC into the stack
    333  * frame and throw an exception.
    334  *
    335  * Perform additional checks on debug builds.
    336  *
    337  * Use this to check for NULL when the instruction handler doesn't do
    338  * anything else that can throw an exception.
    339  */
    340 static inline bool checkForNullExportPC(Object* obj, u4* fp, const u2* pc)
    341 {
    342     if (obj == NULL) {
    343         EXPORT_PC();
    344         dvmThrowNullPointerException(NULL);
    345         return false;
    346     }
    347 #ifdef WITH_EXTRA_OBJECT_VALIDATION
    348     if (!dvmIsHeapAddress(obj)) {
    349         ALOGE("Invalid object %p", obj);
    350         dvmAbort();
    351     }
    352 #endif
    353 #ifndef NDEBUG
    354     if (obj->clazz == NULL || ((u4) obj->clazz) <= 65536) {
    355         /* probable heap corruption */
    356         ALOGE("Invalid object class %p (in %p)", obj->clazz, obj);
    357         dvmAbort();
    358     }
    359 #endif
    360     return true;
    361 }
    362