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