quick_trampoline_entrypoints.cc revision 59c07060a6fbb93e455b44f00098cafb8e7e26cc
1/*
2 * Copyright (C) 2012 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#include "callee_save_frame.h"
18#include "common_throws.h"
19#include "dex_file-inl.h"
20#include "dex_instruction-inl.h"
21#include "entrypoints/entrypoint_utils-inl.h"
22#include "gc/accounting/card_table-inl.h"
23#include "instruction_set.h"
24#include "interpreter/interpreter.h"
25#include "mirror/art_method-inl.h"
26#include "mirror/class-inl.h"
27#include "mirror/dex_cache-inl.h"
28#include "mirror/object-inl.h"
29#include "mirror/object_array-inl.h"
30#include "runtime.h"
31#include "scoped_thread_state_change.h"
32
33namespace art {
34
35// Visits the arguments as saved to the stack by a Runtime::kRefAndArgs callee save frame.
36class QuickArgumentVisitor {
37  // Number of bytes for each out register in the caller method's frame.
38  static constexpr size_t kBytesStackArgLocation = 4;
39  // Frame size in bytes of a callee-save frame for RefsAndArgs.
40  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_FrameSize =
41      GetCalleeSaveFrameSize(kRuntimeISA, Runtime::kRefsAndArgs);
42#if defined(__arm__)
43  // The callee save frame is pointed to by SP.
44  // | argN       |  |
45  // | ...        |  |
46  // | arg4       |  |
47  // | arg3 spill |  |  Caller's frame
48  // | arg2 spill |  |
49  // | arg1 spill |  |
50  // | Method*    | ---
51  // | LR         |
52  // | ...        |    callee saves
53  // | R3         |    arg3
54  // | R2         |    arg2
55  // | R1         |    arg1
56  // | R0         |    padding
57  // | Method*    |  <- sp
58  static constexpr bool kQuickSoftFloatAbi = true;  // This is a soft float ABI.
59  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
60  static constexpr size_t kNumQuickFprArgs = 0;  // 0 arguments passed in FPRs.
61  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
62      arm::ArmCalleeSaveFpr1Offset(Runtime::kRefsAndArgs);  // Offset of first FPR arg.
63  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
64      arm::ArmCalleeSaveGpr1Offset(Runtime::kRefsAndArgs);  // Offset of first GPR arg.
65  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
66      arm::ArmCalleeSaveLrOffset(Runtime::kRefsAndArgs);  // Offset of return address.
67  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
68    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
69  }
70#elif defined(__aarch64__)
71  // The callee save frame is pointed to by SP.
72  // | argN       |  |
73  // | ...        |  |
74  // | arg4       |  |
75  // | arg3 spill |  |  Caller's frame
76  // | arg2 spill |  |
77  // | arg1 spill |  |
78  // | Method*    | ---
79  // | LR         |
80  // | X29        |
81  // |  :         |
82  // | X20        |
83  // | X7         |
84  // | :          |
85  // | X1         |
86  // | D7         |
87  // |  :         |
88  // | D0         |
89  // |            |    padding
90  // | Method*    |  <- sp
91  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
92  static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
93  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
94  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
95      arm64::Arm64CalleeSaveFpr1Offset(Runtime::kRefsAndArgs);  // Offset of first FPR arg.
96  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
97      arm64::Arm64CalleeSaveGpr1Offset(Runtime::kRefsAndArgs);  // Offset of first GPR arg.
98  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
99      arm64::Arm64CalleeSaveLrOffset(Runtime::kRefsAndArgs);  // Offset of return address.
100  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
101    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
102  }
103#elif defined(__mips__)
104  // The callee save frame is pointed to by SP.
105  // | argN       |  |
106  // | ...        |  |
107  // | arg4       |  |
108  // | arg3 spill |  |  Caller's frame
109  // | arg2 spill |  |
110  // | arg1 spill |  |
111  // | Method*    | ---
112  // | RA         |
113  // | ...        |    callee saves
114  // | A3         |    arg3
115  // | A2         |    arg2
116  // | A1         |    arg1
117  // | A0/Method* |  <- sp
118  static constexpr bool kQuickSoftFloatAbi = true;  // This is a soft float ABI.
119  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
120  static constexpr size_t kNumQuickFprArgs = 0;  // 0 arguments passed in FPRs.
121  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 0;  // Offset of first FPR arg.
122  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 4;  // Offset of first GPR arg.
123  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 60;  // Offset of return address.
124  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
125    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
126  }
127#elif defined(__i386__)
128  // The callee save frame is pointed to by SP.
129  // | argN        |  |
130  // | ...         |  |
131  // | arg4        |  |
132  // | arg3 spill  |  |  Caller's frame
133  // | arg2 spill  |  |
134  // | arg1 spill  |  |
135  // | Method*     | ---
136  // | Return      |
137  // | EBP,ESI,EDI |    callee saves
138  // | EBX         |    arg3
139  // | EDX         |    arg2
140  // | ECX         |    arg1
141  // | EAX/Method* |  <- sp
142  static constexpr bool kQuickSoftFloatAbi = true;  // This is a soft float ABI.
143  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
144  static constexpr size_t kNumQuickFprArgs = 0;  // 0 arguments passed in FPRs.
145  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 0;  // Offset of first FPR arg.
146  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 4;  // Offset of first GPR arg.
147  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 28;  // Offset of return address.
148  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
149    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
150  }
151#elif defined(__x86_64__)
152  // The callee save frame is pointed to by SP.
153  // | argN            |  |
154  // | ...             |  |
155  // | reg. arg spills |  |  Caller's frame
156  // | Method*         | ---
157  // | Return          |
158  // | R15             |    callee save
159  // | R14             |    callee save
160  // | R13             |    callee save
161  // | R12             |    callee save
162  // | R9              |    arg5
163  // | R8              |    arg4
164  // | RSI/R6          |    arg1
165  // | RBP/R5          |    callee save
166  // | RBX/R3          |    callee save
167  // | RDX/R2          |    arg2
168  // | RCX/R1          |    arg3
169  // | XMM7            |    float arg 8
170  // | XMM6            |    float arg 7
171  // | XMM5            |    float arg 6
172  // | XMM4            |    float arg 5
173  // | XMM3            |    float arg 4
174  // | XMM2            |    float arg 3
175  // | XMM1            |    float arg 2
176  // | XMM0            |    float arg 1
177  // | Padding         |
178  // | RDI/Method*     |  <- sp
179  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
180  static constexpr size_t kNumQuickGprArgs = 5;  // 5 arguments passed in GPRs.
181  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
182  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 16;  // Offset of first FPR arg.
183  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 80 + 4*8;  // Offset of first GPR arg.
184  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 168 + 4*8;  // Offset of return address.
185  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
186    switch (gpr_index) {
187      case 0: return (4 * GetBytesPerGprSpillLocation(kRuntimeISA));
188      case 1: return (1 * GetBytesPerGprSpillLocation(kRuntimeISA));
189      case 2: return (0 * GetBytesPerGprSpillLocation(kRuntimeISA));
190      case 3: return (5 * GetBytesPerGprSpillLocation(kRuntimeISA));
191      case 4: return (6 * GetBytesPerGprSpillLocation(kRuntimeISA));
192      default:
193      LOG(FATAL) << "Unexpected GPR index: " << gpr_index;
194      return 0;
195    }
196  }
197#else
198#error "Unsupported architecture"
199#endif
200
201 public:
202  static mirror::ArtMethod* GetCallingMethod(StackReference<mirror::ArtMethod>* sp)
203      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
204    DCHECK(sp->AsMirrorPtr()->IsCalleeSaveMethod());
205    uint8_t* previous_sp = reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize;
206    return reinterpret_cast<StackReference<mirror::ArtMethod>*>(previous_sp)->AsMirrorPtr();
207  }
208
209  // For the given quick ref and args quick frame, return the caller's PC.
210  static uintptr_t GetCallingPc(StackReference<mirror::ArtMethod>* sp)
211      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
212    DCHECK(sp->AsMirrorPtr()->IsCalleeSaveMethod());
213    uint8_t* lr = reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_LrOffset;
214    return *reinterpret_cast<uintptr_t*>(lr);
215  }
216
217  QuickArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static, const char* shorty,
218                       uint32_t shorty_len) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
219          is_static_(is_static), shorty_(shorty), shorty_len_(shorty_len),
220          gpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset),
221          fpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset),
222          stack_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize
223                      + StackArgumentStartFromShorty(is_static, shorty, shorty_len)),
224          gpr_index_(0), fpr_index_(0), stack_index_(0), cur_type_(Primitive::kPrimVoid),
225          is_split_long_or_double_(false) {}
226
227  virtual ~QuickArgumentVisitor() {}
228
229  virtual void Visit() = 0;
230
231  Primitive::Type GetParamPrimitiveType() const {
232    return cur_type_;
233  }
234
235  uint8_t* GetParamAddress() const {
236    if (!kQuickSoftFloatAbi) {
237      Primitive::Type type = GetParamPrimitiveType();
238      if (UNLIKELY((type == Primitive::kPrimDouble) || (type == Primitive::kPrimFloat))) {
239        if ((kNumQuickFprArgs != 0) && (fpr_index_ + 1 < kNumQuickFprArgs + 1)) {
240          return fpr_args_ + (fpr_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
241        }
242        return stack_args_ + (stack_index_ * kBytesStackArgLocation);
243      }
244    }
245    if (gpr_index_ < kNumQuickGprArgs) {
246      return gpr_args_ + GprIndexToGprOffset(gpr_index_);
247    }
248    return stack_args_ + (stack_index_ * kBytesStackArgLocation);
249  }
250
251  bool IsSplitLongOrDouble() const {
252    if ((GetBytesPerGprSpillLocation(kRuntimeISA) == 4) || (GetBytesPerFprSpillLocation(kRuntimeISA) == 4)) {
253      return is_split_long_or_double_;
254    } else {
255      return false;  // An optimization for when GPR and FPRs are 64bit.
256    }
257  }
258
259  bool IsParamAReference() const {
260    return GetParamPrimitiveType() == Primitive::kPrimNot;
261  }
262
263  bool IsParamALongOrDouble() const {
264    Primitive::Type type = GetParamPrimitiveType();
265    return type == Primitive::kPrimLong || type == Primitive::kPrimDouble;
266  }
267
268  uint64_t ReadSplitLongParam() const {
269    DCHECK(IsSplitLongOrDouble());
270    uint64_t low_half = *reinterpret_cast<uint32_t*>(GetParamAddress());
271    uint64_t high_half = *reinterpret_cast<uint32_t*>(stack_args_);
272    return (low_half & 0xffffffffULL) | (high_half << 32);
273  }
274
275  void VisitArguments() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
276    // This implementation doesn't support reg-spill area for hard float
277    // ABI targets such as x86_64 and aarch64. So, for those targets whose
278    // 'kQuickSoftFloatAbi' is 'false':
279    //     (a) 'stack_args_' should point to the first method's argument
280    //     (b) whatever the argument type it is, the 'stack_index_' should
281    //         be moved forward along with every visiting.
282    gpr_index_ = 0;
283    fpr_index_ = 0;
284    stack_index_ = 0;
285    if (!is_static_) {  // Handle this.
286      cur_type_ = Primitive::kPrimNot;
287      is_split_long_or_double_ = false;
288      Visit();
289      if (!kQuickSoftFloatAbi || kNumQuickGprArgs == 0) {
290        stack_index_++;
291      }
292      if (kNumQuickGprArgs > 0) {
293        gpr_index_++;
294      }
295    }
296    for (uint32_t shorty_index = 1; shorty_index < shorty_len_; ++shorty_index) {
297      cur_type_ = Primitive::GetType(shorty_[shorty_index]);
298      switch (cur_type_) {
299        case Primitive::kPrimNot:
300        case Primitive::kPrimBoolean:
301        case Primitive::kPrimByte:
302        case Primitive::kPrimChar:
303        case Primitive::kPrimShort:
304        case Primitive::kPrimInt:
305          is_split_long_or_double_ = false;
306          Visit();
307          if (!kQuickSoftFloatAbi || kNumQuickGprArgs == gpr_index_) {
308            stack_index_++;
309          }
310          if (gpr_index_ < kNumQuickGprArgs) {
311            gpr_index_++;
312          }
313          break;
314        case Primitive::kPrimFloat:
315          is_split_long_or_double_ = false;
316          Visit();
317          if (kQuickSoftFloatAbi) {
318            if (gpr_index_ < kNumQuickGprArgs) {
319              gpr_index_++;
320            } else {
321              stack_index_++;
322            }
323          } else {
324            if ((kNumQuickFprArgs != 0) && (fpr_index_ + 1 < kNumQuickFprArgs + 1)) {
325              fpr_index_++;
326            }
327            stack_index_++;
328          }
329          break;
330        case Primitive::kPrimDouble:
331        case Primitive::kPrimLong:
332          if (kQuickSoftFloatAbi || (cur_type_ == Primitive::kPrimLong)) {
333            is_split_long_or_double_ = (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) &&
334                ((gpr_index_ + 1) == kNumQuickGprArgs);
335            Visit();
336            if (!kQuickSoftFloatAbi || kNumQuickGprArgs == gpr_index_) {
337              if (kBytesStackArgLocation == 4) {
338                stack_index_+= 2;
339              } else {
340                CHECK_EQ(kBytesStackArgLocation, 8U);
341                stack_index_++;
342              }
343            }
344            if (gpr_index_ < kNumQuickGprArgs) {
345              gpr_index_++;
346              if (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) {
347                if (gpr_index_ < kNumQuickGprArgs) {
348                  gpr_index_++;
349                } else if (kQuickSoftFloatAbi) {
350                  stack_index_++;
351                }
352              }
353            }
354          } else {
355            is_split_long_or_double_ = (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) &&
356                ((fpr_index_ + 1) == kNumQuickFprArgs);
357            Visit();
358            if ((kNumQuickFprArgs != 0) && (fpr_index_ + 1 < kNumQuickFprArgs + 1)) {
359              fpr_index_++;
360              if (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) {
361                if ((kNumQuickFprArgs != 0) && (fpr_index_ + 1 < kNumQuickFprArgs + 1)) {
362                  fpr_index_++;
363                }
364              }
365            }
366            if (kBytesStackArgLocation == 4) {
367              stack_index_+= 2;
368            } else {
369              CHECK_EQ(kBytesStackArgLocation, 8U);
370              stack_index_++;
371            }
372          }
373          break;
374        default:
375          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty_;
376      }
377    }
378  }
379
380 private:
381  static size_t StackArgumentStartFromShorty(bool is_static, const char* shorty,
382                                             uint32_t shorty_len) {
383    if (kQuickSoftFloatAbi) {
384      CHECK_EQ(kNumQuickFprArgs, 0U);
385      return (kNumQuickGprArgs * GetBytesPerGprSpillLocation(kRuntimeISA))
386          + sizeof(StackReference<mirror::ArtMethod>) /* StackReference<ArtMethod> */;
387    } else {
388      // For now, there is no reg-spill area for the targets with
389      // hard float ABI. So, the offset pointing to the first method's
390      // parameter ('this' for non-static methods) should be returned.
391      return sizeof(StackReference<mirror::ArtMethod>);  // Skip StackReference<ArtMethod>.
392    }
393  }
394
395 protected:
396  const bool is_static_;
397  const char* const shorty_;
398  const uint32_t shorty_len_;
399
400 private:
401  uint8_t* const gpr_args_;  // Address of GPR arguments in callee save frame.
402  uint8_t* const fpr_args_;  // Address of FPR arguments in callee save frame.
403  uint8_t* const stack_args_;  // Address of stack arguments in caller's frame.
404  uint32_t gpr_index_;  // Index into spilled GPRs.
405  uint32_t fpr_index_;  // Index into spilled FPRs.
406  uint32_t stack_index_;  // Index into arguments on the stack.
407  // The current type of argument during VisitArguments.
408  Primitive::Type cur_type_;
409  // Does a 64bit parameter straddle the register and stack arguments?
410  bool is_split_long_or_double_;
411};
412
413// Visits arguments on the stack placing them into the shadow frame.
414class BuildQuickShadowFrameVisitor FINAL : public QuickArgumentVisitor {
415 public:
416  BuildQuickShadowFrameVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
417                               const char* shorty, uint32_t shorty_len, ShadowFrame* sf,
418                               size_t first_arg_reg) :
419      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), sf_(sf), cur_reg_(first_arg_reg) {}
420
421  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
422
423 private:
424  ShadowFrame* const sf_;
425  uint32_t cur_reg_;
426
427  DISALLOW_COPY_AND_ASSIGN(BuildQuickShadowFrameVisitor);
428};
429
430void BuildQuickShadowFrameVisitor::Visit() {
431  Primitive::Type type = GetParamPrimitiveType();
432  switch (type) {
433    case Primitive::kPrimLong:  // Fall-through.
434    case Primitive::kPrimDouble:
435      if (IsSplitLongOrDouble()) {
436        sf_->SetVRegLong(cur_reg_, ReadSplitLongParam());
437      } else {
438        sf_->SetVRegLong(cur_reg_, *reinterpret_cast<jlong*>(GetParamAddress()));
439      }
440      ++cur_reg_;
441      break;
442    case Primitive::kPrimNot: {
443        StackReference<mirror::Object>* stack_ref =
444            reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
445        sf_->SetVRegReference(cur_reg_, stack_ref->AsMirrorPtr());
446      }
447      break;
448    case Primitive::kPrimBoolean:  // Fall-through.
449    case Primitive::kPrimByte:     // Fall-through.
450    case Primitive::kPrimChar:     // Fall-through.
451    case Primitive::kPrimShort:    // Fall-through.
452    case Primitive::kPrimInt:      // Fall-through.
453    case Primitive::kPrimFloat:
454      sf_->SetVReg(cur_reg_, *reinterpret_cast<jint*>(GetParamAddress()));
455      break;
456    case Primitive::kPrimVoid:
457      LOG(FATAL) << "UNREACHABLE";
458      break;
459  }
460  ++cur_reg_;
461}
462
463extern "C" uint64_t artQuickToInterpreterBridge(mirror::ArtMethod* method, Thread* self,
464                                                StackReference<mirror::ArtMethod>* sp)
465    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
466  // Ensure we don't get thread suspension until the object arguments are safely in the shadow
467  // frame.
468  FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsAndArgs);
469
470  if (method->IsAbstract()) {
471    ThrowAbstractMethodError(method);
472    return 0;
473  } else {
474    DCHECK(!method->IsNative()) << PrettyMethod(method);
475    const char* old_cause = self->StartAssertNoThreadSuspension(
476        "Building interpreter shadow frame");
477    const DexFile::CodeItem* code_item = method->GetCodeItem();
478    DCHECK(code_item != nullptr) << PrettyMethod(method);
479    uint16_t num_regs = code_item->registers_size_;
480    void* memory = alloca(ShadowFrame::ComputeSize(num_regs));
481    // No last shadow coming from quick.
482    ShadowFrame* shadow_frame(ShadowFrame::Create(num_regs, nullptr, method, 0, memory));
483    size_t first_arg_reg = code_item->registers_size_ - code_item->ins_size_;
484    uint32_t shorty_len = 0;
485    const char* shorty = method->GetShorty(&shorty_len);
486    BuildQuickShadowFrameVisitor shadow_frame_builder(sp, method->IsStatic(), shorty, shorty_len,
487                                                      shadow_frame, first_arg_reg);
488    shadow_frame_builder.VisitArguments();
489    // Push a transition back into managed code onto the linked list in thread.
490    ManagedStack fragment;
491    self->PushManagedStackFragment(&fragment);
492    self->PushShadowFrame(shadow_frame);
493    self->EndAssertNoThreadSuspension(old_cause);
494
495    StackHandleScope<1> hs(self);
496    MethodHelper mh(hs.NewHandle(method));
497    if (mh.Get()->IsStatic() && !mh.Get()->GetDeclaringClass()->IsInitialized()) {
498      // Ensure static method's class is initialized.
499      StackHandleScope<1> hs(self);
500      Handle<mirror::Class> h_class(hs.NewHandle(mh.Get()->GetDeclaringClass()));
501      if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
502        DCHECK(Thread::Current()->IsExceptionPending()) << PrettyMethod(mh.Get());
503        self->PopManagedStackFragment(fragment);
504        return 0;
505      }
506    }
507    JValue result = interpreter::EnterInterpreterFromStub(self, mh, code_item, *shadow_frame);
508    // Pop transition.
509    self->PopManagedStackFragment(fragment);
510    // No need to restore the args since the method has already been run by the interpreter.
511    return result.GetJ();
512  }
513}
514
515// Visits arguments on the stack placing them into the args vector, Object* arguments are converted
516// to jobjects.
517class BuildQuickArgumentVisitor FINAL : public QuickArgumentVisitor {
518 public:
519  BuildQuickArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
520                            const char* shorty, uint32_t shorty_len,
521                            ScopedObjectAccessUnchecked* soa, std::vector<jvalue>* args) :
522      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa), args_(args) {}
523
524  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
525
526  void FixupReferences() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
527
528 private:
529  ScopedObjectAccessUnchecked* const soa_;
530  std::vector<jvalue>* const args_;
531  // References which we must update when exiting in case the GC moved the objects.
532  std::vector<std::pair<jobject, StackReference<mirror::Object>*>> references_;
533
534  DISALLOW_COPY_AND_ASSIGN(BuildQuickArgumentVisitor);
535};
536
537void BuildQuickArgumentVisitor::Visit() {
538  jvalue val;
539  Primitive::Type type = GetParamPrimitiveType();
540  switch (type) {
541    case Primitive::kPrimNot: {
542      StackReference<mirror::Object>* stack_ref =
543          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
544      val.l = soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
545      references_.push_back(std::make_pair(val.l, stack_ref));
546      break;
547    }
548    case Primitive::kPrimLong:  // Fall-through.
549    case Primitive::kPrimDouble:
550      if (IsSplitLongOrDouble()) {
551        val.j = ReadSplitLongParam();
552      } else {
553        val.j = *reinterpret_cast<jlong*>(GetParamAddress());
554      }
555      break;
556    case Primitive::kPrimBoolean:  // Fall-through.
557    case Primitive::kPrimByte:     // Fall-through.
558    case Primitive::kPrimChar:     // Fall-through.
559    case Primitive::kPrimShort:    // Fall-through.
560    case Primitive::kPrimInt:      // Fall-through.
561    case Primitive::kPrimFloat:
562      val.i = *reinterpret_cast<jint*>(GetParamAddress());
563      break;
564    case Primitive::kPrimVoid:
565      LOG(FATAL) << "UNREACHABLE";
566      val.j = 0;
567      break;
568  }
569  args_->push_back(val);
570}
571
572void BuildQuickArgumentVisitor::FixupReferences() {
573  // Fixup any references which may have changed.
574  for (const auto& pair : references_) {
575    pair.second->Assign(soa_->Decode<mirror::Object*>(pair.first));
576    soa_->Env()->DeleteLocalRef(pair.first);
577  }
578}
579
580// Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
581// which is responsible for recording callee save registers. We explicitly place into jobjects the
582// incoming reference arguments (so they survive GC). We invoke the invocation handler, which is a
583// field within the proxy object, which will box the primitive arguments and deal with error cases.
584extern "C" uint64_t artQuickProxyInvokeHandler(mirror::ArtMethod* proxy_method,
585                                               mirror::Object* receiver,
586                                               Thread* self, StackReference<mirror::ArtMethod>* sp)
587    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
588  DCHECK(proxy_method->IsProxyMethod()) << PrettyMethod(proxy_method);
589  DCHECK(receiver->GetClass()->IsProxyClass()) << PrettyMethod(proxy_method);
590  // Ensure we don't get thread suspension until the object arguments are safely in jobjects.
591  const char* old_cause =
592      self->StartAssertNoThreadSuspension("Adding to IRT proxy object arguments");
593  // Register the top of the managed stack, making stack crawlable.
594  DCHECK_EQ(sp->AsMirrorPtr(), proxy_method) << PrettyMethod(proxy_method);
595  self->SetTopOfStack(sp, 0);
596  DCHECK_EQ(proxy_method->GetFrameSizeInBytes(),
597            Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs)->GetFrameSizeInBytes())
598      << PrettyMethod(proxy_method);
599  self->VerifyStack();
600  // Start new JNI local reference state.
601  JNIEnvExt* env = self->GetJniEnv();
602  ScopedObjectAccessUnchecked soa(env);
603  ScopedJniEnvLocalRefState env_state(env);
604  // Create local ref. copies of proxy method and the receiver.
605  jobject rcvr_jobj = soa.AddLocalReference<jobject>(receiver);
606
607  // Placing arguments into args vector and remove the receiver.
608  mirror::ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy();
609  CHECK(!non_proxy_method->IsStatic()) << PrettyMethod(proxy_method) << " "
610                                       << PrettyMethod(non_proxy_method);
611  std::vector<jvalue> args;
612  uint32_t shorty_len = 0;
613  const char* shorty = proxy_method->GetShorty(&shorty_len);
614  BuildQuickArgumentVisitor local_ref_visitor(sp, false, shorty, shorty_len, &soa, &args);
615
616  local_ref_visitor.VisitArguments();
617  DCHECK_GT(args.size(), 0U) << PrettyMethod(proxy_method);
618  args.erase(args.begin());
619
620  // Convert proxy method into expected interface method.
621  mirror::ArtMethod* interface_method = proxy_method->FindOverriddenMethod();
622  DCHECK(interface_method != NULL) << PrettyMethod(proxy_method);
623  DCHECK(!interface_method->IsProxyMethod()) << PrettyMethod(interface_method);
624  jobject interface_method_jobj = soa.AddLocalReference<jobject>(interface_method);
625
626  // All naked Object*s should now be in jobjects, so its safe to go into the main invoke code
627  // that performs allocations.
628  self->EndAssertNoThreadSuspension(old_cause);
629  JValue result = InvokeProxyInvocationHandler(soa, shorty, rcvr_jobj, interface_method_jobj, args);
630  // Restore references which might have moved.
631  local_ref_visitor.FixupReferences();
632  return result.GetJ();
633}
634
635// Read object references held in arguments from quick frames and place in a JNI local references,
636// so they don't get garbage collected.
637class RememberForGcArgumentVisitor FINAL : public QuickArgumentVisitor {
638 public:
639  RememberForGcArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
640                               const char* shorty, uint32_t shorty_len,
641                               ScopedObjectAccessUnchecked* soa) :
642      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa) {}
643
644  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
645
646  void FixupReferences() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
647
648 private:
649  ScopedObjectAccessUnchecked* const soa_;
650  // References which we must update when exiting in case the GC moved the objects.
651  std::vector<std::pair<jobject, StackReference<mirror::Object>*> > references_;
652
653  DISALLOW_COPY_AND_ASSIGN(RememberForGcArgumentVisitor);
654};
655
656void RememberForGcArgumentVisitor::Visit() {
657  if (IsParamAReference()) {
658    StackReference<mirror::Object>* stack_ref =
659        reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
660    jobject reference =
661        soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
662    references_.push_back(std::make_pair(reference, stack_ref));
663  }
664}
665
666void RememberForGcArgumentVisitor::FixupReferences() {
667  // Fixup any references which may have changed.
668  for (const auto& pair : references_) {
669    pair.second->Assign(soa_->Decode<mirror::Object*>(pair.first));
670    soa_->Env()->DeleteLocalRef(pair.first);
671  }
672}
673
674// Lazily resolve a method for quick. Called by stub code.
675extern "C" const void* artQuickResolutionTrampoline(mirror::ArtMethod* called,
676                                                    mirror::Object* receiver,
677                                                    Thread* self,
678                                                    StackReference<mirror::ArtMethod>* sp)
679    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
680  FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsAndArgs);
681  // Start new JNI local reference state
682  JNIEnvExt* env = self->GetJniEnv();
683  ScopedObjectAccessUnchecked soa(env);
684  ScopedJniEnvLocalRefState env_state(env);
685  const char* old_cause = self->StartAssertNoThreadSuspension("Quick method resolution set up");
686
687  // Compute details about the called method (avoid GCs)
688  ClassLinker* linker = Runtime::Current()->GetClassLinker();
689  mirror::ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
690  InvokeType invoke_type;
691  const DexFile* dex_file;
692  uint32_t dex_method_idx;
693  if (called->IsRuntimeMethod()) {
694    uint32_t dex_pc = caller->ToDexPc(QuickArgumentVisitor::GetCallingPc(sp));
695    const DexFile::CodeItem* code;
696    dex_file = caller->GetDexFile();
697    code = caller->GetCodeItem();
698    CHECK_LT(dex_pc, code->insns_size_in_code_units_);
699    const Instruction* instr = Instruction::At(&code->insns_[dex_pc]);
700    Instruction::Code instr_code = instr->Opcode();
701    bool is_range;
702    switch (instr_code) {
703      case Instruction::INVOKE_DIRECT:
704        invoke_type = kDirect;
705        is_range = false;
706        break;
707      case Instruction::INVOKE_DIRECT_RANGE:
708        invoke_type = kDirect;
709        is_range = true;
710        break;
711      case Instruction::INVOKE_STATIC:
712        invoke_type = kStatic;
713        is_range = false;
714        break;
715      case Instruction::INVOKE_STATIC_RANGE:
716        invoke_type = kStatic;
717        is_range = true;
718        break;
719      case Instruction::INVOKE_SUPER:
720        invoke_type = kSuper;
721        is_range = false;
722        break;
723      case Instruction::INVOKE_SUPER_RANGE:
724        invoke_type = kSuper;
725        is_range = true;
726        break;
727      case Instruction::INVOKE_VIRTUAL:
728        invoke_type = kVirtual;
729        is_range = false;
730        break;
731      case Instruction::INVOKE_VIRTUAL_RANGE:
732        invoke_type = kVirtual;
733        is_range = true;
734        break;
735      case Instruction::INVOKE_INTERFACE:
736        invoke_type = kInterface;
737        is_range = false;
738        break;
739      case Instruction::INVOKE_INTERFACE_RANGE:
740        invoke_type = kInterface;
741        is_range = true;
742        break;
743      default:
744        LOG(FATAL) << "Unexpected call into trampoline: " << instr->DumpString(NULL);
745        // Avoid used uninitialized warnings.
746        invoke_type = kDirect;
747        is_range = false;
748    }
749    dex_method_idx = (is_range) ? instr->VRegB_3rc() : instr->VRegB_35c();
750  } else {
751    invoke_type = kStatic;
752    dex_file = called->GetDexFile();
753    dex_method_idx = called->GetDexMethodIndex();
754  }
755  uint32_t shorty_len;
756  const char* shorty =
757      dex_file->GetMethodShorty(dex_file->GetMethodId(dex_method_idx), &shorty_len);
758  RememberForGcArgumentVisitor visitor(sp, invoke_type == kStatic, shorty, shorty_len, &soa);
759  visitor.VisitArguments();
760  self->EndAssertNoThreadSuspension(old_cause);
761  bool virtual_or_interface = invoke_type == kVirtual || invoke_type == kInterface;
762  // Resolve method filling in dex cache.
763  if (UNLIKELY(called->IsRuntimeMethod())) {
764    StackHandleScope<1> hs(self);
765    mirror::Object* dummy = nullptr;
766    HandleWrapper<mirror::Object> h_receiver(
767        hs.NewHandleWrapper(virtual_or_interface ? &receiver : &dummy));
768    called = linker->ResolveMethod(self, dex_method_idx, &caller, invoke_type);
769  }
770  const void* code = NULL;
771  if (LIKELY(!self->IsExceptionPending())) {
772    // Incompatible class change should have been handled in resolve method.
773    CHECK(!called->CheckIncompatibleClassChange(invoke_type))
774        << PrettyMethod(called) << " " << invoke_type;
775    if (virtual_or_interface) {
776      // Refine called method based on receiver.
777      CHECK(receiver != nullptr) << invoke_type;
778
779      mirror::ArtMethod* orig_called = called;
780      if (invoke_type == kVirtual) {
781        called = receiver->GetClass()->FindVirtualMethodForVirtual(called);
782      } else {
783        called = receiver->GetClass()->FindVirtualMethodForInterface(called);
784      }
785
786      CHECK(called != nullptr) << PrettyMethod(orig_called) << " "
787                               << PrettyTypeOf(receiver) << " "
788                               << invoke_type << " " << orig_called->GetVtableIndex();
789
790      // We came here because of sharpening. Ensure the dex cache is up-to-date on the method index
791      // of the sharpened method.
792      if (called->HasSameDexCacheResolvedMethods(caller)) {
793        caller->SetDexCacheResolvedMethod(called->GetDexMethodIndex(), called);
794      } else {
795        // Calling from one dex file to another, need to compute the method index appropriate to
796        // the caller's dex file. Since we get here only if the original called was a runtime
797        // method, we've got the correct dex_file and a dex_method_idx from above.
798        DCHECK_EQ(caller->GetDexFile(), dex_file);
799        StackHandleScope<1> hs(self);
800        MethodHelper mh(hs.NewHandle(called));
801        uint32_t method_index = mh.FindDexMethodIndexInOtherDexFile(*dex_file, dex_method_idx);
802        if (method_index != DexFile::kDexNoIndex) {
803          caller->SetDexCacheResolvedMethod(method_index, called);
804        }
805      }
806    }
807    // Ensure that the called method's class is initialized.
808    StackHandleScope<1> hs(soa.Self());
809    Handle<mirror::Class> called_class(hs.NewHandle(called->GetDeclaringClass()));
810    linker->EnsureInitialized(soa.Self(), called_class, true, true);
811    if (LIKELY(called_class->IsInitialized())) {
812      code = called->GetEntryPointFromQuickCompiledCode();
813    } else if (called_class->IsInitializing()) {
814      if (invoke_type == kStatic) {
815        // Class is still initializing, go to oat and grab code (trampoline must be left in place
816        // until class is initialized to stop races between threads).
817        code = linker->GetQuickOatCodeFor(called);
818      } else {
819        // No trampoline for non-static methods.
820        code = called->GetEntryPointFromQuickCompiledCode();
821      }
822    } else {
823      DCHECK(called_class->IsErroneous());
824    }
825  }
826  CHECK_EQ(code == NULL, self->IsExceptionPending());
827  // Fixup any locally saved objects may have moved during a GC.
828  visitor.FixupReferences();
829  // Place called method in callee-save frame to be placed as first argument to quick method.
830  sp->Assign(called);
831  return code;
832}
833
834/*
835 * This class uses a couple of observations to unite the different calling conventions through
836 * a few constants.
837 *
838 * 1) Number of registers used for passing is normally even, so counting down has no penalty for
839 *    possible alignment.
840 * 2) Known 64b architectures store 8B units on the stack, both for integral and floating point
841 *    types, so using uintptr_t is OK. Also means that we can use kRegistersNeededX to denote
842 *    when we have to split things
843 * 3) The only soft-float, Arm, is 32b, so no widening needs to be taken into account for floats
844 *    and we can use Int handling directly.
845 * 4) Only 64b architectures widen, and their stack is aligned 8B anyways, so no padding code
846 *    necessary when widening. Also, widening of Ints will take place implicitly, and the
847 *    extension should be compatible with Aarch64, which mandates copying the available bits
848 *    into LSB and leaving the rest unspecified.
849 * 5) Aligning longs and doubles is necessary on arm only, and it's the same in registers and on
850 *    the stack.
851 * 6) There is only little endian.
852 *
853 *
854 * Actual work is supposed to be done in a delegate of the template type. The interface is as
855 * follows:
856 *
857 * void PushGpr(uintptr_t):   Add a value for the next GPR
858 *
859 * void PushFpr4(float):      Add a value for the next FPR of size 32b. Is only called if we need
860 *                            padding, that is, think the architecture is 32b and aligns 64b.
861 *
862 * void PushFpr8(uint64_t):   Push a double. We _will_ call this on 32b, it's the callee's job to
863 *                            split this if necessary. The current state will have aligned, if
864 *                            necessary.
865 *
866 * void PushStack(uintptr_t): Push a value to the stack.
867 *
868 * uintptr_t PushHandleScope(mirror::Object* ref): Add a reference to the HandleScope. This _will_ have nullptr,
869 *                                          as this might be important for null initialization.
870 *                                          Must return the jobject, that is, the reference to the
871 *                                          entry in the HandleScope (nullptr if necessary).
872 *
873 */
874template<class T> class BuildNativeCallFrameStateMachine {
875 public:
876#if defined(__arm__)
877  // TODO: These are all dummy values!
878  static constexpr bool kNativeSoftFloatAbi = true;
879  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs, r0-r3
880  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
881
882  static constexpr size_t kRegistersNeededForLong = 2;
883  static constexpr size_t kRegistersNeededForDouble = 2;
884  static constexpr bool kMultiRegistersAligned = true;
885  static constexpr bool kMultiRegistersWidened = false;
886  static constexpr bool kAlignLongOnStack = true;
887  static constexpr bool kAlignDoubleOnStack = true;
888#elif defined(__aarch64__)
889  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
890  static constexpr size_t kNumNativeGprArgs = 8;  // 6 arguments passed in GPRs.
891  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
892
893  static constexpr size_t kRegistersNeededForLong = 1;
894  static constexpr size_t kRegistersNeededForDouble = 1;
895  static constexpr bool kMultiRegistersAligned = false;
896  static constexpr bool kMultiRegistersWidened = false;
897  static constexpr bool kAlignLongOnStack = false;
898  static constexpr bool kAlignDoubleOnStack = false;
899#elif defined(__mips__)
900  // TODO: These are all dummy values!
901  static constexpr bool kNativeSoftFloatAbi = true;  // This is a hard float ABI.
902  static constexpr size_t kNumNativeGprArgs = 0;  // 6 arguments passed in GPRs.
903  static constexpr size_t kNumNativeFprArgs = 0;  // 8 arguments passed in FPRs.
904
905  static constexpr size_t kRegistersNeededForLong = 2;
906  static constexpr size_t kRegistersNeededForDouble = 2;
907  static constexpr bool kMultiRegistersAligned = true;
908  static constexpr bool kMultiRegistersWidened = true;
909  static constexpr bool kAlignLongOnStack = false;
910  static constexpr bool kAlignDoubleOnStack = false;
911#elif defined(__i386__)
912  // TODO: Check these!
913  static constexpr bool kNativeSoftFloatAbi = false;  // Not using int registers for fp
914  static constexpr size_t kNumNativeGprArgs = 0;  // 6 arguments passed in GPRs.
915  static constexpr size_t kNumNativeFprArgs = 0;  // 8 arguments passed in FPRs.
916
917  static constexpr size_t kRegistersNeededForLong = 2;
918  static constexpr size_t kRegistersNeededForDouble = 2;
919  static constexpr bool kMultiRegistersAligned = false;  // x86 not using regs, anyways
920  static constexpr bool kMultiRegistersWidened = false;
921  static constexpr bool kAlignLongOnStack = false;
922  static constexpr bool kAlignDoubleOnStack = false;
923#elif defined(__x86_64__)
924  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
925  static constexpr size_t kNumNativeGprArgs = 6;  // 6 arguments passed in GPRs.
926  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
927
928  static constexpr size_t kRegistersNeededForLong = 1;
929  static constexpr size_t kRegistersNeededForDouble = 1;
930  static constexpr bool kMultiRegistersAligned = false;
931  static constexpr bool kMultiRegistersWidened = false;
932  static constexpr bool kAlignLongOnStack = false;
933  static constexpr bool kAlignDoubleOnStack = false;
934#else
935#error "Unsupported architecture"
936#endif
937
938 public:
939  explicit BuildNativeCallFrameStateMachine(T* delegate)
940      : gpr_index_(kNumNativeGprArgs),
941        fpr_index_(kNumNativeFprArgs),
942        stack_entries_(0),
943        delegate_(delegate) {
944    // For register alignment, we want to assume that counters (gpr_index_, fpr_index_) are even iff
945    // the next register is even; counting down is just to make the compiler happy...
946    CHECK_EQ(kNumNativeGprArgs % 2, 0U);
947    CHECK_EQ(kNumNativeFprArgs % 2, 0U);
948  }
949
950  virtual ~BuildNativeCallFrameStateMachine() {}
951
952  bool HavePointerGpr() {
953    return gpr_index_ > 0;
954  }
955
956  void AdvancePointer(const void* val) {
957    if (HavePointerGpr()) {
958      gpr_index_--;
959      PushGpr(reinterpret_cast<uintptr_t>(val));
960    } else {
961      stack_entries_++;  // TODO: have a field for pointer length as multiple of 32b
962      PushStack(reinterpret_cast<uintptr_t>(val));
963      gpr_index_ = 0;
964    }
965  }
966
967  bool HaveHandleScopeGpr() {
968    return gpr_index_ > 0;
969  }
970
971  void AdvanceHandleScope(mirror::Object* ptr) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
972    uintptr_t handle = PushHandle(ptr);
973    if (HaveHandleScopeGpr()) {
974      gpr_index_--;
975      PushGpr(handle);
976    } else {
977      stack_entries_++;
978      PushStack(handle);
979      gpr_index_ = 0;
980    }
981  }
982
983  bool HaveIntGpr() {
984    return gpr_index_ > 0;
985  }
986
987  void AdvanceInt(uint32_t val) {
988    if (HaveIntGpr()) {
989      gpr_index_--;
990      PushGpr(val);
991    } else {
992      stack_entries_++;
993      PushStack(val);
994      gpr_index_ = 0;
995    }
996  }
997
998  bool HaveLongGpr() {
999    return gpr_index_ >= kRegistersNeededForLong + (LongGprNeedsPadding() ? 1 : 0);
1000  }
1001
1002  bool LongGprNeedsPadding() {
1003    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1004        kAlignLongOnStack &&                  // and when it needs alignment
1005        (gpr_index_ & 1) == 1;                // counter is odd, see constructor
1006  }
1007
1008  bool LongStackNeedsPadding() {
1009    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1010        kAlignLongOnStack &&                  // and when it needs 8B alignment
1011        (stack_entries_ & 1) == 1;            // counter is odd
1012  }
1013
1014  void AdvanceLong(uint64_t val) {
1015    if (HaveLongGpr()) {
1016      if (LongGprNeedsPadding()) {
1017        PushGpr(0);
1018        gpr_index_--;
1019      }
1020      if (kRegistersNeededForLong == 1) {
1021        PushGpr(static_cast<uintptr_t>(val));
1022      } else {
1023        PushGpr(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1024        PushGpr(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1025      }
1026      gpr_index_ -= kRegistersNeededForLong;
1027    } else {
1028      if (LongStackNeedsPadding()) {
1029        PushStack(0);
1030        stack_entries_++;
1031      }
1032      if (kRegistersNeededForLong == 1) {
1033        PushStack(static_cast<uintptr_t>(val));
1034        stack_entries_++;
1035      } else {
1036        PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1037        PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1038        stack_entries_ += 2;
1039      }
1040      gpr_index_ = 0;
1041    }
1042  }
1043
1044  bool HaveFloatFpr() {
1045    return fpr_index_ > 0;
1046  }
1047
1048  void AdvanceFloat(float val) {
1049    if (kNativeSoftFloatAbi) {
1050      AdvanceInt(bit_cast<float, uint32_t>(val));
1051    } else {
1052      if (HaveFloatFpr()) {
1053        fpr_index_--;
1054        if (kRegistersNeededForDouble == 1) {
1055          if (kMultiRegistersWidened) {
1056            PushFpr8(bit_cast<double, uint64_t>(val));
1057          } else {
1058            // No widening, just use the bits.
1059            PushFpr8(bit_cast<float, uint64_t>(val));
1060          }
1061        } else {
1062          PushFpr4(val);
1063        }
1064      } else {
1065        stack_entries_++;
1066        if (kRegistersNeededForDouble == 1 && kMultiRegistersWidened) {
1067          // Need to widen before storing: Note the "double" in the template instantiation.
1068          // Note: We need to jump through those hoops to make the compiler happy.
1069          DCHECK_EQ(sizeof(uintptr_t), sizeof(uint64_t));
1070          PushStack(static_cast<uintptr_t>(bit_cast<double, uint64_t>(val)));
1071        } else {
1072          PushStack(bit_cast<float, uintptr_t>(val));
1073        }
1074        fpr_index_ = 0;
1075      }
1076    }
1077  }
1078
1079  bool HaveDoubleFpr() {
1080    return fpr_index_ >= kRegistersNeededForDouble + (DoubleFprNeedsPadding() ? 1 : 0);
1081  }
1082
1083  bool DoubleFprNeedsPadding() {
1084    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1085        kAlignDoubleOnStack &&                  // and when it needs alignment
1086        (fpr_index_ & 1) == 1;                  // counter is odd, see constructor
1087  }
1088
1089  bool DoubleStackNeedsPadding() {
1090    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1091        kAlignDoubleOnStack &&                  // and when it needs 8B alignment
1092        (stack_entries_ & 1) == 1;              // counter is odd
1093  }
1094
1095  void AdvanceDouble(uint64_t val) {
1096    if (kNativeSoftFloatAbi) {
1097      AdvanceLong(val);
1098    } else {
1099      if (HaveDoubleFpr()) {
1100        if (DoubleFprNeedsPadding()) {
1101          PushFpr4(0);
1102          fpr_index_--;
1103        }
1104        PushFpr8(val);
1105        fpr_index_ -= kRegistersNeededForDouble;
1106      } else {
1107        if (DoubleStackNeedsPadding()) {
1108          PushStack(0);
1109          stack_entries_++;
1110        }
1111        if (kRegistersNeededForDouble == 1) {
1112          PushStack(static_cast<uintptr_t>(val));
1113          stack_entries_++;
1114        } else {
1115          PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1116          PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1117          stack_entries_ += 2;
1118        }
1119        fpr_index_ = 0;
1120      }
1121    }
1122  }
1123
1124  uint32_t getStackEntries() {
1125    return stack_entries_;
1126  }
1127
1128  uint32_t getNumberOfUsedGprs() {
1129    return kNumNativeGprArgs - gpr_index_;
1130  }
1131
1132  uint32_t getNumberOfUsedFprs() {
1133    return kNumNativeFprArgs - fpr_index_;
1134  }
1135
1136 private:
1137  void PushGpr(uintptr_t val) {
1138    delegate_->PushGpr(val);
1139  }
1140  void PushFpr4(float val) {
1141    delegate_->PushFpr4(val);
1142  }
1143  void PushFpr8(uint64_t val) {
1144    delegate_->PushFpr8(val);
1145  }
1146  void PushStack(uintptr_t val) {
1147    delegate_->PushStack(val);
1148  }
1149  uintptr_t PushHandle(mirror::Object* ref) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1150    return delegate_->PushHandle(ref);
1151  }
1152
1153  uint32_t gpr_index_;      // Number of free GPRs
1154  uint32_t fpr_index_;      // Number of free FPRs
1155  uint32_t stack_entries_;  // Stack entries are in multiples of 32b, as floats are usually not
1156                            // extended
1157  T* delegate_;             // What Push implementation gets called
1158};
1159
1160// Computes the sizes of register stacks and call stack area. Handling of references can be extended
1161// in subclasses.
1162//
1163// To handle native pointers, use "L" in the shorty for an object reference, which simulates
1164// them with handles.
1165class ComputeNativeCallFrameSize {
1166 public:
1167  ComputeNativeCallFrameSize() : num_stack_entries_(0) {}
1168
1169  virtual ~ComputeNativeCallFrameSize() {}
1170
1171  uint32_t GetStackSize() {
1172    return num_stack_entries_ * sizeof(uintptr_t);
1173  }
1174
1175  uint8_t* LayoutCallStack(uint8_t* sp8) {
1176    sp8 -= GetStackSize();
1177    // Align by kStackAlignment.
1178    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1179    return sp8;
1180  }
1181
1182  uint8_t* LayoutCallRegisterStacks(uint8_t* sp8, uintptr_t** start_gpr, uint32_t** start_fpr) {
1183    // Assumption is OK right now, as we have soft-float arm
1184    size_t fregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeFprArgs;
1185    sp8 -= fregs * sizeof(uintptr_t);
1186    *start_fpr = reinterpret_cast<uint32_t*>(sp8);
1187    size_t iregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeGprArgs;
1188    sp8 -= iregs * sizeof(uintptr_t);
1189    *start_gpr = reinterpret_cast<uintptr_t*>(sp8);
1190    return sp8;
1191  }
1192
1193  uint8_t* LayoutNativeCall(uint8_t* sp8, uintptr_t** start_stack, uintptr_t** start_gpr,
1194                            uint32_t** start_fpr) {
1195    // Native call stack.
1196    sp8 = LayoutCallStack(sp8);
1197    *start_stack = reinterpret_cast<uintptr_t*>(sp8);
1198
1199    // Put fprs and gprs below.
1200    sp8 = LayoutCallRegisterStacks(sp8, start_gpr, start_fpr);
1201
1202    // Return the new bottom.
1203    return sp8;
1204  }
1205
1206  virtual void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm)
1207      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {}
1208
1209  void Walk(const char* shorty, uint32_t shorty_len) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1210    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> sm(this);
1211
1212    WalkHeader(&sm);
1213
1214    for (uint32_t i = 1; i < shorty_len; ++i) {
1215      Primitive::Type cur_type_ = Primitive::GetType(shorty[i]);
1216      switch (cur_type_) {
1217        case Primitive::kPrimNot:
1218          sm.AdvanceHandleScope(
1219              reinterpret_cast<mirror::Object*>(0x12345678));
1220          break;
1221
1222        case Primitive::kPrimBoolean:
1223        case Primitive::kPrimByte:
1224        case Primitive::kPrimChar:
1225        case Primitive::kPrimShort:
1226        case Primitive::kPrimInt:
1227          sm.AdvanceInt(0);
1228          break;
1229        case Primitive::kPrimFloat:
1230          sm.AdvanceFloat(0);
1231          break;
1232        case Primitive::kPrimDouble:
1233          sm.AdvanceDouble(0);
1234          break;
1235        case Primitive::kPrimLong:
1236          sm.AdvanceLong(0);
1237          break;
1238        default:
1239          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty;
1240      }
1241    }
1242
1243    num_stack_entries_ = sm.getStackEntries();
1244  }
1245
1246  void PushGpr(uintptr_t /* val */) {
1247    // not optimizing registers, yet
1248  }
1249
1250  void PushFpr4(float /* val */) {
1251    // not optimizing registers, yet
1252  }
1253
1254  void PushFpr8(uint64_t /* val */) {
1255    // not optimizing registers, yet
1256  }
1257
1258  void PushStack(uintptr_t /* val */) {
1259    // counting is already done in the superclass
1260  }
1261
1262  virtual uintptr_t PushHandle(mirror::Object* /* ptr */) {
1263    return reinterpret_cast<uintptr_t>(nullptr);
1264  }
1265
1266 protected:
1267  uint32_t num_stack_entries_;
1268};
1269
1270class ComputeGenericJniFrameSize FINAL : public ComputeNativeCallFrameSize {
1271 public:
1272  ComputeGenericJniFrameSize() : num_handle_scope_references_(0) {}
1273
1274  // Lays out the callee-save frame. Assumes that the incorrect frame corresponding to RefsAndArgs
1275  // is at *m = sp. Will update to point to the bottom of the save frame.
1276  //
1277  // Note: assumes ComputeAll() has been run before.
1278  void LayoutCalleeSaveFrame(Thread* self, StackReference<mirror::ArtMethod>** m, void* sp,
1279                             HandleScope** handle_scope)
1280      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1281    mirror::ArtMethod* method = (*m)->AsMirrorPtr();
1282
1283    uint8_t* sp8 = reinterpret_cast<uint8_t*>(sp);
1284
1285    // First, fix up the layout of the callee-save frame.
1286    // We have to squeeze in the HandleScope, and relocate the method pointer.
1287
1288    // "Free" the slot for the method.
1289    sp8 += sizeof(void*);  // In the callee-save frame we use a full pointer.
1290
1291    // Under the callee saves put handle scope and new method stack reference.
1292    size_t handle_scope_size = HandleScope::SizeOf(num_handle_scope_references_);
1293    size_t scope_and_method = handle_scope_size + sizeof(StackReference<mirror::ArtMethod>);
1294
1295    sp8 -= scope_and_method;
1296    // Align by kStackAlignment.
1297    sp8 = reinterpret_cast<uint8_t*>(RoundDown(
1298        reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1299
1300    uint8_t* sp8_table = sp8 + sizeof(StackReference<mirror::ArtMethod>);
1301    *handle_scope = HandleScope::Create(sp8_table, self->GetTopHandleScope(),
1302                                        num_handle_scope_references_);
1303
1304    // Add a slot for the method pointer, and fill it. Fix the pointer-pointer given to us.
1305    uint8_t* method_pointer = sp8;
1306    StackReference<mirror::ArtMethod>* new_method_ref =
1307        reinterpret_cast<StackReference<mirror::ArtMethod>*>(method_pointer);
1308    new_method_ref->Assign(method);
1309    *m = new_method_ref;
1310  }
1311
1312  // Adds space for the cookie. Note: may leave stack unaligned.
1313  void LayoutCookie(uint8_t** sp) {
1314    // Reference cookie and padding
1315    *sp -= 8;
1316  }
1317
1318  // Re-layout the callee-save frame (insert a handle-scope). Then add space for the cookie.
1319  // Returns the new bottom. Note: this may be unaligned.
1320  uint8_t* LayoutJNISaveFrame(Thread* self, StackReference<mirror::ArtMethod>** m, void* sp,
1321                              HandleScope** handle_scope)
1322      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1323    // First, fix up the layout of the callee-save frame.
1324    // We have to squeeze in the HandleScope, and relocate the method pointer.
1325    LayoutCalleeSaveFrame(self, m, sp, handle_scope);
1326
1327    // The bottom of the callee-save frame is now where the method is, *m.
1328    uint8_t* sp8 = reinterpret_cast<uint8_t*>(*m);
1329
1330    // Add space for cookie.
1331    LayoutCookie(&sp8);
1332
1333    return sp8;
1334  }
1335
1336  // WARNING: After this, *sp won't be pointing to the method anymore!
1337  uint8_t* ComputeLayout(Thread* self, StackReference<mirror::ArtMethod>** m,
1338                         bool is_static, const char* shorty, uint32_t shorty_len,
1339                         HandleScope** handle_scope,
1340                         uintptr_t** start_stack, uintptr_t** start_gpr, uint32_t** start_fpr)
1341      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1342    Walk(shorty, shorty_len);
1343
1344    // JNI part.
1345    uint8_t* sp8 = LayoutJNISaveFrame(self, m, reinterpret_cast<void*>(*m), handle_scope);
1346
1347    sp8 = LayoutNativeCall(sp8, start_stack, start_gpr, start_fpr);
1348
1349    // Return the new bottom.
1350    return sp8;
1351  }
1352
1353  uintptr_t PushHandle(mirror::Object* /* ptr */) OVERRIDE;
1354
1355  // Add JNIEnv* and jobj/jclass before the shorty-derived elements.
1356  void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) OVERRIDE
1357      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1358
1359 private:
1360  uint32_t num_handle_scope_references_;
1361};
1362
1363uintptr_t ComputeGenericJniFrameSize::PushHandle(mirror::Object* /* ptr */) {
1364  num_handle_scope_references_++;
1365  return reinterpret_cast<uintptr_t>(nullptr);
1366}
1367
1368void ComputeGenericJniFrameSize::WalkHeader(
1369    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) {
1370  // JNIEnv
1371  sm->AdvancePointer(nullptr);
1372
1373  // Class object or this as first argument
1374  sm->AdvanceHandleScope(reinterpret_cast<mirror::Object*>(0x12345678));
1375}
1376
1377// Class to push values to three separate regions. Used to fill the native call part. Adheres to
1378// the template requirements of BuildGenericJniFrameStateMachine.
1379class FillNativeCall {
1380 public:
1381  FillNativeCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) :
1382      cur_gpr_reg_(gpr_regs), cur_fpr_reg_(fpr_regs), cur_stack_arg_(stack_args) {}
1383
1384  virtual ~FillNativeCall() {}
1385
1386  void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1387    cur_gpr_reg_ = gpr_regs;
1388    cur_fpr_reg_ = fpr_regs;
1389    cur_stack_arg_ = stack_args;
1390  }
1391
1392  void PushGpr(uintptr_t val) {
1393    *cur_gpr_reg_ = val;
1394    cur_gpr_reg_++;
1395  }
1396
1397  void PushFpr4(float val) {
1398    *cur_fpr_reg_ = val;
1399    cur_fpr_reg_++;
1400  }
1401
1402  void PushFpr8(uint64_t val) {
1403    uint64_t* tmp = reinterpret_cast<uint64_t*>(cur_fpr_reg_);
1404    *tmp = val;
1405    cur_fpr_reg_ += 2;
1406  }
1407
1408  void PushStack(uintptr_t val) {
1409    *cur_stack_arg_ = val;
1410    cur_stack_arg_++;
1411  }
1412
1413  virtual uintptr_t PushHandle(mirror::Object* ref) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1414    LOG(FATAL) << "(Non-JNI) Native call does not use handles.";
1415    return 0U;
1416  }
1417
1418 private:
1419  uintptr_t* cur_gpr_reg_;
1420  uint32_t* cur_fpr_reg_;
1421  uintptr_t* cur_stack_arg_;
1422};
1423
1424// Visits arguments on the stack placing them into a region lower down the stack for the benefit
1425// of transitioning into native code.
1426class BuildGenericJniFrameVisitor FINAL : public QuickArgumentVisitor {
1427 public:
1428  BuildGenericJniFrameVisitor(Thread* self, bool is_static, const char* shorty, uint32_t shorty_len,
1429                              StackReference<mirror::ArtMethod>** sp)
1430     : QuickArgumentVisitor(*sp, is_static, shorty, shorty_len),
1431       jni_call_(nullptr, nullptr, nullptr, nullptr), sm_(&jni_call_) {
1432    ComputeGenericJniFrameSize fsc;
1433    uintptr_t* start_gpr_reg;
1434    uint32_t* start_fpr_reg;
1435    uintptr_t* start_stack_arg;
1436    bottom_of_used_area_ = fsc.ComputeLayout(self, sp, is_static, shorty, shorty_len,
1437                                             &handle_scope_,
1438                                             &start_stack_arg,
1439                                             &start_gpr_reg, &start_fpr_reg);
1440
1441    jni_call_.Reset(start_gpr_reg, start_fpr_reg, start_stack_arg, handle_scope_);
1442
1443    // jni environment is always first argument
1444    sm_.AdvancePointer(self->GetJniEnv());
1445
1446    if (is_static) {
1447      sm_.AdvanceHandleScope((*sp)->AsMirrorPtr()->GetDeclaringClass());
1448    }
1449  }
1450
1451  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
1452
1453  void FinalizeHandleScope(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1454
1455  StackReference<mirror::Object>* GetFirstHandleScopeEntry()
1456      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1457    return handle_scope_->GetHandle(0).GetReference();
1458  }
1459
1460  jobject GetFirstHandleScopeJObject() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1461    return handle_scope_->GetHandle(0).ToJObject();
1462  }
1463
1464  void* GetBottomOfUsedArea() {
1465    return bottom_of_used_area_;
1466  }
1467
1468 private:
1469  // A class to fill a JNI call. Adds reference/handle-scope management to FillNativeCall.
1470  class FillJniCall FINAL : public FillNativeCall {
1471   public:
1472    FillJniCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args,
1473                HandleScope* handle_scope) : FillNativeCall(gpr_regs, fpr_regs, stack_args),
1474                                             handle_scope_(handle_scope), cur_entry_(0) {}
1475
1476    uintptr_t PushHandle(mirror::Object* ref) OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1477
1478    void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args, HandleScope* scope) {
1479      FillNativeCall::Reset(gpr_regs, fpr_regs, stack_args);
1480      handle_scope_ = scope;
1481      cur_entry_ = 0U;
1482    }
1483
1484    void ResetRemainingScopeSlots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1485      // Initialize padding entries.
1486      size_t expected_slots = handle_scope_->NumberOfReferences();
1487      while (cur_entry_ < expected_slots) {
1488        handle_scope_->GetMutableHandle(cur_entry_++).Assign(nullptr);
1489      }
1490      DCHECK_NE(cur_entry_, 0U);
1491    }
1492
1493   private:
1494    HandleScope* handle_scope_;
1495    size_t cur_entry_;
1496  };
1497
1498  HandleScope* handle_scope_;
1499  FillJniCall jni_call_;
1500  void* bottom_of_used_area_;
1501
1502  BuildNativeCallFrameStateMachine<FillJniCall> sm_;
1503
1504  DISALLOW_COPY_AND_ASSIGN(BuildGenericJniFrameVisitor);
1505};
1506
1507uintptr_t BuildGenericJniFrameVisitor::FillJniCall::PushHandle(mirror::Object* ref) {
1508  uintptr_t tmp;
1509  MutableHandle<mirror::Object> h = handle_scope_->GetMutableHandle(cur_entry_);
1510  h.Assign(ref);
1511  tmp = reinterpret_cast<uintptr_t>(h.ToJObject());
1512  cur_entry_++;
1513  return tmp;
1514}
1515
1516void BuildGenericJniFrameVisitor::Visit() {
1517  Primitive::Type type = GetParamPrimitiveType();
1518  switch (type) {
1519    case Primitive::kPrimLong: {
1520      jlong long_arg;
1521      if (IsSplitLongOrDouble()) {
1522        long_arg = ReadSplitLongParam();
1523      } else {
1524        long_arg = *reinterpret_cast<jlong*>(GetParamAddress());
1525      }
1526      sm_.AdvanceLong(long_arg);
1527      break;
1528    }
1529    case Primitive::kPrimDouble: {
1530      uint64_t double_arg;
1531      if (IsSplitLongOrDouble()) {
1532        // Read into union so that we don't case to a double.
1533        double_arg = ReadSplitLongParam();
1534      } else {
1535        double_arg = *reinterpret_cast<uint64_t*>(GetParamAddress());
1536      }
1537      sm_.AdvanceDouble(double_arg);
1538      break;
1539    }
1540    case Primitive::kPrimNot: {
1541      StackReference<mirror::Object>* stack_ref =
1542          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
1543      sm_.AdvanceHandleScope(stack_ref->AsMirrorPtr());
1544      break;
1545    }
1546    case Primitive::kPrimFloat:
1547      sm_.AdvanceFloat(*reinterpret_cast<float*>(GetParamAddress()));
1548      break;
1549    case Primitive::kPrimBoolean:  // Fall-through.
1550    case Primitive::kPrimByte:     // Fall-through.
1551    case Primitive::kPrimChar:     // Fall-through.
1552    case Primitive::kPrimShort:    // Fall-through.
1553    case Primitive::kPrimInt:      // Fall-through.
1554      sm_.AdvanceInt(*reinterpret_cast<jint*>(GetParamAddress()));
1555      break;
1556    case Primitive::kPrimVoid:
1557      LOG(FATAL) << "UNREACHABLE";
1558      break;
1559  }
1560}
1561
1562void BuildGenericJniFrameVisitor::FinalizeHandleScope(Thread* self) {
1563  // Clear out rest of the scope.
1564  jni_call_.ResetRemainingScopeSlots();
1565  // Install HandleScope.
1566  self->PushHandleScope(handle_scope_);
1567}
1568
1569#if defined(__arm__) || defined(__aarch64__)
1570extern "C" void* artFindNativeMethod();
1571#else
1572extern "C" void* artFindNativeMethod(Thread* self);
1573#endif
1574
1575uint64_t artQuickGenericJniEndJNIRef(Thread* self, uint32_t cookie, jobject l, jobject lock) {
1576  if (lock != nullptr) {
1577    return reinterpret_cast<uint64_t>(JniMethodEndWithReferenceSynchronized(l, cookie, lock, self));
1578  } else {
1579    return reinterpret_cast<uint64_t>(JniMethodEndWithReference(l, cookie, self));
1580  }
1581}
1582
1583void artQuickGenericJniEndJNINonRef(Thread* self, uint32_t cookie, jobject lock) {
1584  if (lock != nullptr) {
1585    JniMethodEndSynchronized(cookie, lock, self);
1586  } else {
1587    JniMethodEnd(cookie, self);
1588  }
1589}
1590
1591/*
1592 * Initializes an alloca region assumed to be directly below sp for a native call:
1593 * Create a HandleScope and call stack and fill a mini stack with values to be pushed to registers.
1594 * The final element on the stack is a pointer to the native code.
1595 *
1596 * On entry, the stack has a standard callee-save frame above sp, and an alloca below it.
1597 * We need to fix this, as the handle scope needs to go into the callee-save frame.
1598 *
1599 * The return of this function denotes:
1600 * 1) How many bytes of the alloca can be released, if the value is non-negative.
1601 * 2) An error, if the value is negative.
1602 */
1603extern "C" TwoWordReturn artQuickGenericJniTrampoline(Thread* self,
1604                                                      StackReference<mirror::ArtMethod>* sp)
1605    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1606  mirror::ArtMethod* called = sp->AsMirrorPtr();
1607  DCHECK(called->IsNative()) << PrettyMethod(called, true);
1608  uint32_t shorty_len = 0;
1609  const char* shorty = called->GetShorty(&shorty_len);
1610
1611  // Run the visitor.
1612  BuildGenericJniFrameVisitor visitor(self, called->IsStatic(), shorty, shorty_len, &sp);
1613  visitor.VisitArguments();
1614  visitor.FinalizeHandleScope(self);
1615
1616  // Fix up managed-stack things in Thread.
1617  self->SetTopOfStack(sp, 0);
1618
1619  self->VerifyStack();
1620
1621  // Start JNI, save the cookie.
1622  uint32_t cookie;
1623  if (called->IsSynchronized()) {
1624    cookie = JniMethodStartSynchronized(visitor.GetFirstHandleScopeJObject(), self);
1625    if (self->IsExceptionPending()) {
1626      self->PopHandleScope();
1627      // A negative value denotes an error.
1628      return GetTwoWordFailureValue();
1629    }
1630  } else {
1631    cookie = JniMethodStart(self);
1632  }
1633  uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
1634  *(sp32 - 1) = cookie;
1635
1636  // Retrieve the stored native code.
1637  const void* nativeCode = called->GetNativeMethod();
1638
1639  // There are two cases for the content of nativeCode:
1640  // 1) Pointer to the native function.
1641  // 2) Pointer to the trampoline for native code binding.
1642  // In the second case, we need to execute the binding and continue with the actual native function
1643  // pointer.
1644  DCHECK(nativeCode != nullptr);
1645  if (nativeCode == GetJniDlsymLookupStub()) {
1646#if defined(__arm__) || defined(__aarch64__)
1647    nativeCode = artFindNativeMethod();
1648#else
1649    nativeCode = artFindNativeMethod(self);
1650#endif
1651
1652    if (nativeCode == nullptr) {
1653      DCHECK(self->IsExceptionPending());    // There should be an exception pending now.
1654
1655      // End JNI, as the assembly will move to deliver the exception.
1656      jobject lock = called->IsSynchronized() ? visitor.GetFirstHandleScopeJObject() : nullptr;
1657      if (shorty[0] == 'L') {
1658        artQuickGenericJniEndJNIRef(self, cookie, nullptr, lock);
1659      } else {
1660        artQuickGenericJniEndJNINonRef(self, cookie, lock);
1661      }
1662
1663      return GetTwoWordFailureValue();
1664    }
1665    // Note that the native code pointer will be automatically set by artFindNativeMethod().
1666  }
1667
1668  // Return native code addr(lo) and bottom of alloca address(hi).
1669  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(visitor.GetBottomOfUsedArea()),
1670                                reinterpret_cast<uintptr_t>(nativeCode));
1671}
1672
1673/*
1674 * Is called after the native JNI code. Responsible for cleanup (handle scope, saved state) and
1675 * unlocking.
1676 */
1677extern "C" uint64_t artQuickGenericJniEndTrampoline(Thread* self, jvalue result, uint64_t result_f)
1678    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1679  StackReference<mirror::ArtMethod>* sp = self->GetManagedStack()->GetTopQuickFrame();
1680  uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
1681  mirror::ArtMethod* called = sp->AsMirrorPtr();
1682  uint32_t cookie = *(sp32 - 1);
1683
1684  jobject lock = nullptr;
1685  if (called->IsSynchronized()) {
1686    HandleScope* table = reinterpret_cast<HandleScope*>(reinterpret_cast<uint8_t*>(sp)
1687        + sizeof(StackReference<mirror::ArtMethod>));
1688    lock = table->GetHandle(0).ToJObject();
1689  }
1690
1691  char return_shorty_char = called->GetShorty()[0];
1692
1693  if (return_shorty_char == 'L') {
1694    return artQuickGenericJniEndJNIRef(self, cookie, result.l, lock);
1695  } else {
1696    artQuickGenericJniEndJNINonRef(self, cookie, lock);
1697
1698    switch (return_shorty_char) {
1699      case 'F': {
1700        if (kRuntimeISA == kX86) {
1701          // Convert back the result to float.
1702          double d = bit_cast<uint64_t, double>(result_f);
1703          return bit_cast<float, uint32_t>(static_cast<float>(d));
1704        } else {
1705          return result_f;
1706        }
1707      }
1708      case 'D':
1709        return result_f;
1710      case 'Z':
1711        return result.z;
1712      case 'B':
1713        return result.b;
1714      case 'C':
1715        return result.c;
1716      case 'S':
1717        return result.s;
1718      case 'I':
1719        return result.i;
1720      case 'J':
1721        return result.j;
1722      case 'V':
1723        return 0;
1724      default:
1725        LOG(FATAL) << "Unexpected return shorty character " << return_shorty_char;
1726        return 0;
1727    }
1728  }
1729}
1730
1731// We use TwoWordReturn to optimize scalar returns. We use the hi value for code, and the lo value
1732// for the method pointer.
1733//
1734// It is valid to use this, as at the usage points here (returns from C functions) we are assuming
1735// to hold the mutator lock (see SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) annotations).
1736
1737template<InvokeType type, bool access_check>
1738static TwoWordReturn artInvokeCommon(uint32_t method_idx, mirror::Object* this_object,
1739                                     mirror::ArtMethod* caller_method,
1740                                     Thread* self, StackReference<mirror::ArtMethod>* sp);
1741
1742template<InvokeType type, bool access_check>
1743static TwoWordReturn artInvokeCommon(uint32_t method_idx, mirror::Object* this_object,
1744                                     mirror::ArtMethod* caller_method,
1745                                     Thread* self, StackReference<mirror::ArtMethod>* sp) {
1746  mirror::ArtMethod* method = FindMethodFast(method_idx, this_object, caller_method, access_check,
1747                                             type);
1748  if (UNLIKELY(method == nullptr)) {
1749    FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsAndArgs);
1750    const DexFile* dex_file = caller_method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1751    uint32_t shorty_len;
1752    const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(method_idx), &shorty_len);
1753    {
1754      // Remember the args in case a GC happens in FindMethodFromCode.
1755      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1756      RememberForGcArgumentVisitor visitor(sp, type == kStatic, shorty, shorty_len, &soa);
1757      visitor.VisitArguments();
1758      method = FindMethodFromCode<type, access_check>(method_idx, &this_object, &caller_method,
1759                                                      self);
1760      visitor.FixupReferences();
1761    }
1762
1763    if (UNLIKELY(method == NULL)) {
1764      CHECK(self->IsExceptionPending());
1765      return GetTwoWordFailureValue();  // Failure.
1766    }
1767  }
1768  DCHECK(!self->IsExceptionPending());
1769  const void* code = method->GetEntryPointFromQuickCompiledCode();
1770
1771  // When we return, the caller will branch to this address, so it had better not be 0!
1772  DCHECK(code != nullptr) << "Code was NULL in method: " << PrettyMethod(method)
1773                          << " location: "
1774                          << method->GetDexFile()->GetLocation();
1775
1776  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
1777                                reinterpret_cast<uintptr_t>(method));
1778}
1779
1780// Explicit artInvokeCommon template function declarations to please analysis tool.
1781#define EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(type, access_check)                                \
1782  template SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)                                          \
1783  TwoWordReturn artInvokeCommon<type, access_check>(uint32_t method_idx,                        \
1784                                                    mirror::Object* this_object,                \
1785                                                    mirror::ArtMethod* caller_method,           \
1786                                                    Thread* self,                               \
1787                                                    StackReference<mirror::ArtMethod>* sp)      \
1788
1789EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, false);
1790EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, true);
1791EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, false);
1792EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, true);
1793EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, false);
1794EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, true);
1795EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, false);
1796EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, true);
1797EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, false);
1798EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, true);
1799#undef EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL
1800
1801// See comments in runtime_support_asm.S
1802extern "C" TwoWordReturn artInvokeInterfaceTrampolineWithAccessCheck(
1803    uint32_t method_idx, mirror::Object* this_object,
1804    mirror::ArtMethod* caller_method, Thread* self,
1805    StackReference<mirror::ArtMethod>* sp)
1806        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1807  return artInvokeCommon<kInterface, true>(method_idx, this_object,
1808                                           caller_method, self, sp);
1809}
1810
1811extern "C" TwoWordReturn artInvokeDirectTrampolineWithAccessCheck(
1812    uint32_t method_idx, mirror::Object* this_object,
1813    mirror::ArtMethod* caller_method, Thread* self,
1814    StackReference<mirror::ArtMethod>* sp)
1815        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1816  return artInvokeCommon<kDirect, true>(method_idx, this_object, caller_method,
1817                                        self, sp);
1818}
1819
1820extern "C" TwoWordReturn artInvokeStaticTrampolineWithAccessCheck(
1821    uint32_t method_idx, mirror::Object* this_object,
1822    mirror::ArtMethod* caller_method, Thread* self,
1823    StackReference<mirror::ArtMethod>* sp)
1824        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1825  return artInvokeCommon<kStatic, true>(method_idx, this_object, caller_method,
1826                                        self, sp);
1827}
1828
1829extern "C" TwoWordReturn artInvokeSuperTrampolineWithAccessCheck(
1830    uint32_t method_idx, mirror::Object* this_object,
1831    mirror::ArtMethod* caller_method, Thread* self,
1832    StackReference<mirror::ArtMethod>* sp)
1833        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1834  return artInvokeCommon<kSuper, true>(method_idx, this_object, caller_method,
1835                                       self, sp);
1836}
1837
1838extern "C" TwoWordReturn artInvokeVirtualTrampolineWithAccessCheck(
1839    uint32_t method_idx, mirror::Object* this_object,
1840    mirror::ArtMethod* caller_method, Thread* self,
1841    StackReference<mirror::ArtMethod>* sp)
1842        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1843  return artInvokeCommon<kVirtual, true>(method_idx, this_object, caller_method,
1844                                         self, sp);
1845}
1846
1847// Determine target of interface dispatch. This object is known non-null.
1848extern "C" TwoWordReturn artInvokeInterfaceTrampoline(mirror::ArtMethod* interface_method,
1849                                                      mirror::Object* this_object,
1850                                                      mirror::ArtMethod* caller_method,
1851                                                      Thread* self,
1852                                                      StackReference<mirror::ArtMethod>* sp)
1853    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1854  mirror::ArtMethod* method;
1855  if (LIKELY(interface_method->GetDexMethodIndex() != DexFile::kDexNoIndex)) {
1856    method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
1857    if (UNLIKELY(method == NULL)) {
1858      FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsAndArgs);
1859      ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(interface_method, this_object,
1860                                                                 caller_method);
1861      return GetTwoWordFailureValue();  // Failure.
1862    }
1863  } else {
1864    FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsAndArgs);
1865    DCHECK(interface_method == Runtime::Current()->GetResolutionMethod());
1866
1867    // Find the caller PC.
1868    constexpr size_t pc_offset = GetCalleeSavePCOffset(kRuntimeISA, Runtime::kRefsAndArgs);
1869    uintptr_t caller_pc = *reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(sp) + pc_offset);
1870
1871    // Map the caller PC to a dex PC.
1872    uint32_t dex_pc = caller_method->ToDexPc(caller_pc);
1873    const DexFile::CodeItem* code = caller_method->GetCodeItem();
1874    CHECK_LT(dex_pc, code->insns_size_in_code_units_);
1875    const Instruction* instr = Instruction::At(&code->insns_[dex_pc]);
1876    Instruction::Code instr_code = instr->Opcode();
1877    CHECK(instr_code == Instruction::INVOKE_INTERFACE ||
1878          instr_code == Instruction::INVOKE_INTERFACE_RANGE)
1879        << "Unexpected call into interface trampoline: " << instr->DumpString(NULL);
1880    uint32_t dex_method_idx;
1881    if (instr_code == Instruction::INVOKE_INTERFACE) {
1882      dex_method_idx = instr->VRegB_35c();
1883    } else {
1884      DCHECK_EQ(instr_code, Instruction::INVOKE_INTERFACE_RANGE);
1885      dex_method_idx = instr->VRegB_3rc();
1886    }
1887
1888    const DexFile* dex_file = caller_method->GetDeclaringClass()->GetDexCache()
1889        ->GetDexFile();
1890    uint32_t shorty_len;
1891    const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(dex_method_idx),
1892                                                   &shorty_len);
1893    {
1894      // Remember the args in case a GC happens in FindMethodFromCode.
1895      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1896      RememberForGcArgumentVisitor visitor(sp, false, shorty, shorty_len, &soa);
1897      visitor.VisitArguments();
1898      method = FindMethodFromCode<kInterface, false>(dex_method_idx, &this_object, &caller_method,
1899                                                     self);
1900      visitor.FixupReferences();
1901    }
1902
1903    if (UNLIKELY(method == nullptr)) {
1904      CHECK(self->IsExceptionPending());
1905      return GetTwoWordFailureValue();  // Failure.
1906    }
1907  }
1908  const void* code = method->GetEntryPointFromQuickCompiledCode();
1909
1910  // When we return, the caller will branch to this address, so it had better not be 0!
1911  DCHECK(code != nullptr) << "Code was NULL in method: " << PrettyMethod(method)
1912                          << " location: " << method->GetDexFile()->GetLocation();
1913
1914  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
1915                                reinterpret_cast<uintptr_t>(method));
1916}
1917
1918}  // namespace art
1919