抽取加固脱壳方案

被抽空的函数什么时候被还原?被执行的时候。怎么让函数执行?两个方法,被动调用和主动调用。

被动调用指app运行过程中所发生的函数调用,只对dex中部分的类完成加载,只对dex中的部分函数完成调用,被动调用也可以用来完成函数粒度的修复,待app将dex中的类正常加载并完成相关函数的调用之后,再进行dex的dump。缺点是调用函数不全,而且有些壳当函数代码执行完毕之后会再次进行抽取。

主动调用指构建虚拟调用,对dex中所有类函数完成调用,能够覆盖dex中的所有函数,可以在函数执行时dump函数体数据,主动调用链构造的越深效果越好。

抽取加固的本质是提取出dex文件中的字节码,并在运行时进行还原。

常见的抽取加固形式:对原有函数体数据空间置0,保留原有空间;对dex文件进行重构,不保留原有空间,可以理解为方法体所在的空间没了,在还原数据时,修改dex文件中指向方法体偏移的字段值,指向内存中另一块区域,这段区域就是真正的方法体的位置;将原有函数体替换为解密代码,运行时解密执行。

常见的抽取加固脱壳机:DexHunter、Fupk3、FART、youpk。

整体加固脱壳方案

常见脱壳点

函数解释执行Execute

通过ClassLinkerDexCacheData进一步得到DexFile

内存搜索Dex文件来dump

通过mCookie脱壳

什么是artMethod

artMethod 的本质 是 ART(Android Runtime)虚拟机中的方法表示结构,它在 ART 运行时负责管理 Java 方法的底层数据。

简单来说,每个 Java 方法(MethodConstructor)在运行时都会对应一个 artMethod 结构,它存储:

1
2
3
4
5
6
方法所属类
方法的访问权限
方法在 DEX 文件中的索引
方法的代码地址(JIT 编译后的机器码)
方法的 DEX 文件指针
方法的字节码在 DEX 文件中的偏移量

可以把 artMethod 看成是 Java 方法的内部表示,它是方法在 ART 运行时的底层封装。

那为什么 artMethod->GetDexFile() 能获取 DEX 文件?

因为在 Android ART 里,每个 artMethod 结构都包含一个指向 dexFile 的指针,这个指针指向方法所属的 DEX 文件。

1
2
3
每个 artMethod 都知道自己属于哪个类(declaring_class_)。
declaring_class_` 这个类又知道自己在哪个 DexFile 里(dex_file_)。
所以,artMethod->GetDexFile() 就是顺着方法找类,再找 DEX,最终返回 dexFile。

FART脱壳组件源码分析

这里分析的是FART_aosp8.0的源码,在interpreter.cc中有Execute()方法

该方法被定义为inline函数static inline JValue Execute,也就是编译的时候是嵌入在其他函数中的,不易被检测到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static inline JValue Execute(
Thread* self,
const DexFile::CodeItem* code_item,
ShadowFrame& shadow_frame,
JValue result_register,
bool stay_in_interpreter = false) REQUIRES_SHARED(Locks::mutator_lock_) {

// 检测函数是否为类的初始化函数
// 类的初始化函数即使是在解释oat文件的时候也会执行,不会因为不是dex文件就不执行了

if(strstr(shadow_frame.GetMethod()->PrettyMethod().c_str(),"<clinit>"))
{
dumpdexfilebyExecute(shadow_frame.GetMethod());
}
...

跟进dumpdexfilebyExecute()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
extern "C" void dumpdexfilebyExecute(ArtMethod* artmethod)  REQUIRES_SHARED(Locks::mutator_lock_) {
// 申请dex文件的内存,后面的dex文件数据会写入到这个内存中
char *dexfilepath=(char*)malloc(sizeof(char)*1000);
if(dexfilepath==nullptr)
{
LOG(ERROR)<< "ArtMethod::dumpdexfilebyArtMethod,methodname:"<<artmethod->PrettyMethod().c_str()<<"malloc 1000 byte failed";
return;
}
int result=0;
int fcmdline =-1;
char szCmdline[64]= {0};
char szProcName[256] = {0};
int procid = getpid();
sprintf(szCmdline,"/proc/%d/cmdline", procid);
fcmdline = open(szCmdline, O_RDONLY,0644);
if(fcmdline >0)
{
result=read(fcmdline, szProcName,256);
if(result<0)
{
LOG(ERROR) << "ArtMethod::dumpdexfilebyArtMethod,open cmdline file error";
}
close(fcmdline);

}

if(szProcName[0])
{
const DexFile* dex_file = artmethod->GetDexFile();
const uint8_t* begin_=dex_file->Begin(); // Start of data.
size_t size_=dex_file->Size(); // Length of data.

memset(dexfilepath,0,1000);
int size_int_=(int)size_;

memset(dexfilepath,0,1000);
sprintf(dexfilepath,"%s","/sdcard/fart");
mkdir(dexfilepath,0777);

memset(dexfilepath,0,1000);
sprintf(dexfilepath,"/sdcard/fart/%s",szProcName);
mkdir(dexfilepath,0777);

memset(dexfilepath,0,1000);
sprintf(dexfilepath,"/sdcard/fart/%s/%d_dexfile_execute.dex",szProcName,size_int_);
int dexfilefp=open(dexfilepath,O_RDONLY,0666);
if(dexfilefp>0){
close(dexfilefp);
dexfilefp=0;

}else{
int fp=open(dexfilepath,O_CREAT|O_APPEND|O_RDWR,0666);
if(fp>0)
{
result=write(fp,(void*)begin_,size_);
if(result<0)
{
LOG(ERROR) << "ArtMethod::dumpdexfilebyArtMethod,open dexfilepath error";
}
fsync(fp);
close(fp);
memset(dexfilepath,0,1000);
// 写入txt文件,文件内容是dex文件中类的名称等信息
sprintf(dexfilepath,"/sdcard/fart/%s/%d_classlist_execute.txt",szProcName,size_int_);
int classlistfile=open(dexfilepath,O_CREAT|O_APPEND|O_RDWR,0666);
if(classlistfile>0)
{
for (size_t ii= 0; ii< dex_file->NumClassDefs(); ++ii)
{
const DexFile::ClassDef& class_def = dex_file->GetClassDef(ii);
const char* descriptor = dex_file->GetClassDescriptor(class_def);
result=write(classlistfile,(void*)descriptor,strlen(descriptor));
if(result<0)
{
LOG(ERROR) << "ArtMethod::dumpdexfilebyArtMethod,write classlistfile file error";
}
const char* temp="\n";
result=write(classlistfile,(void*)temp,1);
if(result<0)
{
LOG(ERROR) << "ArtMethod::dumpdexfilebyArtMethod,write classlistfile file error";
}
}
fsync(classlistfile);
close(classlistfile);
}
}
}
}
if(dexfilepath!=nullptr)
{
free(dexfilepath);
dexfilepath=nullptr;
}
}

其实核心代码就是通过artMethod得到dexfile,然后获取dexfile的起始位置和大小

1
2
3
const DexFile* dex_file = artmethod->GetDexFile();
const uint8_t* begin_=dex_file->Begin(); // Start of data.
size_t size_=dex_file->Size(); // Length of data.

FART魔改和适配Android 10

由于上面的代码是基于Android 8,所以可能会被检测,需要修改一下方法名,而且写入dex文件的路径也需要改,Android 10上/sdcard/目录的权限管理比Android 8要严格,此外还有一些代码的细节和Android 8里不一样

FART的intercept.cc对应的Android 10下的art/runtime/interpreter/interpreter.cc

说白了就是改系统源码,让系统在运行app的时候去脱壳

intercept.cc的一开始先声明方法,然后修改Execute函数,让函数在一开始就判断是否运行了初始化类的方法

1
2
3
4
namespace art {
extern "C" void saveDexFileByExecute(ArtMethod* artMethod);
...

1
2
3
4
5
6
7
8
9
10
11
static inline JValue Execute(
Thread* self,
const CodeItemDataAccessor& accessor,
ShadowFrame& shadow_frame,
JValue result_register,
bool stay_in_interpreter = false,
bool from_deoptimize = false) REQUIRES_SHARED(Locks::mutator_lock_) {

if(strstr(shadow_frame.GetMethod()->PrettyMethod().c_str(), "<clinit>")) {
saveDexFileByExecute(shadow_frame.GetMethod());
}

然后改saveDexFileByExecute的代码,对应的修改位置在art/runtime/art_method.cc

编译成系统

进入/bin/aosp目录,运行source build/envsetup.sh,然后运行lunch,选择对应的机型,pixel是aosp_sailfish-userdebug(有的话直接选序号,没有这个选项可以手动指定),最后make -j

代码见最后demo

编译完成之后会在out/target/product/sailfish下生成一些文件,需要的是vendor.img、boot.img、android-info.txt、system.img、system_other.img五个文件,然后找到刷机包,替换里面的源码部分,把系统刷到手机上去

FART魔改demo

interpreter.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "interpreter.h"

#include <limits>
#include <string_view>

#include "common_dex_operations.h"
#include "common_throws.h"
#include "dex/dex_file_types.h"
#include "interpreter_common.h"
#include "interpreter_mterp_impl.h"
#include "interpreter_switch_impl.h"
#include "jit/jit.h"
#include "jit/jit_code_cache.h"
#include "jvalue-inl.h"
#include "mirror/string-inl.h"
#include "mterp/mterp.h"
#include "nativehelper/scoped_local_ref.h"
#include "scoped_thread_state_change-inl.h"
#include "shadow_frame-inl.h"
#include "stack.h"
#include "thread-inl.h"
#include "unstarted_runtime.h"

namespace art {

extern "C" void saveDexFileByExecute(ArtMethod* artMethod);

namespace interpreter {
ALWAYS_INLINE static ObjPtr<mirror::Object> ObjArg(uint32_t arg)
REQUIRES_SHARED(Locks::mutator_lock_) {
return reinterpret_cast<mirror::Object*>(arg);
}

static void InterpreterJni(Thread* self,
ArtMethod* method,
std::string_view shorty,
ObjPtr<mirror::Object> receiver,
uint32_t* args,
JValue* result)
REQUIRES_SHARED(Locks::mutator_lock_) {
// TODO: The following enters JNI code using a typedef-ed function rather than the JNI compiler,
// it should be removed and JNI compiled stubs used instead.
ScopedObjectAccessUnchecked soa(self);
if (method->IsStatic()) {
if (shorty == "L") {
using fntype = jobject(JNIEnv*, jclass);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
jobject jresult;
{
ScopedThreadStateChange tsc(self, kNative);
jresult = fn(soa.Env(), klass.get());
}
result->SetL(soa.Decode<mirror::Object>(jresult));
} else if (shorty == "V") {
using fntype = void(JNIEnv*, jclass);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
fn(soa.Env(), klass.get());
} else if (shorty == "Z") {
using fntype = jboolean(JNIEnv*, jclass);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
result->SetZ(fn(soa.Env(), klass.get()));
} else if (shorty == "BI") {
using fntype = jbyte(JNIEnv*, jclass, jint);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
result->SetB(fn(soa.Env(), klass.get(), args[0]));
} else if (shorty == "II") {
using fntype = jint(JNIEnv*, jclass, jint);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
result->SetI(fn(soa.Env(), klass.get(), args[0]));
} else if (shorty == "LL") {
using fntype = jobject(JNIEnv*, jclass, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg0(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[0])));
jobject jresult;
{
ScopedThreadStateChange tsc(self, kNative);
jresult = fn(soa.Env(), klass.get(), arg0.get());
}
result->SetL(soa.Decode<mirror::Object>(jresult));
} else if (shorty == "IIZ") {
using fntype = jint(JNIEnv*, jclass, jint, jboolean);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
result->SetI(fn(soa.Env(), klass.get(), args[0], args[1]));
} else if (shorty == "ILI") {
using fntype = jint(JNIEnv*, jclass, jobject, jint);
fntype* const fn = reinterpret_cast<fntype*>(const_cast<void*>(
method->GetEntryPointFromJni()));
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg0(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[0])));
ScopedThreadStateChange tsc(self, kNative);
result->SetI(fn(soa.Env(), klass.get(), arg0.get(), args[1]));
} else if (shorty == "SIZ") {
using fntype = jshort(JNIEnv*, jclass, jint, jboolean);
fntype* const fn =
reinterpret_cast<fntype*>(const_cast<void*>(method->GetEntryPointFromJni()));
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
result->SetS(fn(soa.Env(), klass.get(), args[0], args[1]));
} else if (shorty == "VIZ") {
using fntype = void(JNIEnv*, jclass, jint, jboolean);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedThreadStateChange tsc(self, kNative);
fn(soa.Env(), klass.get(), args[0], args[1]);
} else if (shorty == "ZLL") {
using fntype = jboolean(JNIEnv*, jclass, jobject, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg0(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[0])));
ScopedLocalRef<jobject> arg1(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[1])));
ScopedThreadStateChange tsc(self, kNative);
result->SetZ(fn(soa.Env(), klass.get(), arg0.get(), arg1.get()));
} else if (shorty == "ZILL") {
using fntype = jboolean(JNIEnv*, jclass, jint, jobject, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg1(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[1])));
ScopedLocalRef<jobject> arg2(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[2])));
ScopedThreadStateChange tsc(self, kNative);
result->SetZ(fn(soa.Env(), klass.get(), args[0], arg1.get(), arg2.get()));
} else if (shorty == "VILII") {
using fntype = void(JNIEnv*, jclass, jint, jobject, jint, jint);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg1(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[1])));
ScopedThreadStateChange tsc(self, kNative);
fn(soa.Env(), klass.get(), args[0], arg1.get(), args[2], args[3]);
} else if (shorty == "VLILII") {
using fntype = void(JNIEnv*, jclass, jobject, jint, jobject, jint, jint);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jclass> klass(soa.Env(),
soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
ScopedLocalRef<jobject> arg0(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[0])));
ScopedLocalRef<jobject> arg2(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[2])));
ScopedThreadStateChange tsc(self, kNative);
fn(soa.Env(), klass.get(), arg0.get(), args[1], arg2.get(), args[3], args[4]);
} else {
LOG(FATAL) << "Do something with static native method: " << method->PrettyMethod()
<< " shorty: " << shorty;
}
} else {
if (shorty == "L") {
using fntype = jobject(JNIEnv*, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jobject> rcvr(soa.Env(),
soa.AddLocalReference<jobject>(receiver));
jobject jresult;
{
ScopedThreadStateChange tsc(self, kNative);
jresult = fn(soa.Env(), rcvr.get());
}
result->SetL(soa.Decode<mirror::Object>(jresult));
} else if (shorty == "V") {
using fntype = void(JNIEnv*, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jobject> rcvr(soa.Env(),
soa.AddLocalReference<jobject>(receiver));
ScopedThreadStateChange tsc(self, kNative);
fn(soa.Env(), rcvr.get());
} else if (shorty == "LL") {
using fntype = jobject(JNIEnv*, jobject, jobject);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jobject> rcvr(soa.Env(),
soa.AddLocalReference<jobject>(receiver));
ScopedLocalRef<jobject> arg0(soa.Env(),
soa.AddLocalReference<jobject>(ObjArg(args[0])));
jobject jresult;
{
ScopedThreadStateChange tsc(self, kNative);
jresult = fn(soa.Env(), rcvr.get(), arg0.get());
}
result->SetL(soa.Decode<mirror::Object>(jresult));
ScopedThreadStateChange tsc(self, kNative);
} else if (shorty == "III") {
using fntype = jint(JNIEnv*, jobject, jint, jint);
fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
ScopedLocalRef<jobject> rcvr(soa.Env(),
soa.AddLocalReference<jobject>(receiver));
ScopedThreadStateChange tsc(self, kNative);
result->SetI(fn(soa.Env(), rcvr.get(), args[0], args[1]));
} else {
LOG(FATAL) << "Do something with native method: " << method->PrettyMethod()
<< " shorty: " << shorty;
}
}
}

enum InterpreterImplKind {
kSwitchImplKind, // Switch-based interpreter implementation.
kMterpImplKind // Assembly interpreter
};

#if ART_USE_CXX_INTERPRETER
static constexpr InterpreterImplKind kInterpreterImplKind = kSwitchImplKind;
#else
static constexpr InterpreterImplKind kInterpreterImplKind = kMterpImplKind;
#endif

static inline JValue Execute(
Thread* self,
const CodeItemDataAccessor& accessor,
ShadowFrame& shadow_frame,
JValue result_register,
bool stay_in_interpreter = false,
bool from_deoptimize = false) REQUIRES_SHARED(Locks::mutator_lock_) {

if(strstr(shadow_frame.GetMethod()->PrettyMethod().c_str(), "<clinit>")) {
saveDexFileByExecute(shadow_frame.GetMethod());
}

DCHECK(!shadow_frame.GetMethod()->IsAbstract());
DCHECK(!shadow_frame.GetMethod()->IsNative());

// Check that we are using the right interpreter.
if (kIsDebugBuild && self->UseMterp() != CanUseMterp()) {
// The flag might be currently being updated on all threads. Retry with lock.
MutexLock tll_mu(self, *Locks::thread_list_lock_);
DCHECK_EQ(self->UseMterp(), CanUseMterp());
}

if (LIKELY(!from_deoptimize)) { // Entering the method, but not via deoptimization.
if (kIsDebugBuild) {
CHECK_EQ(shadow_frame.GetDexPC(), 0u);
self->AssertNoPendingException();
}
instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
ArtMethod *method = shadow_frame.GetMethod();

if (UNLIKELY(instrumentation->HasMethodEntryListeners())) {
instrumentation->MethodEnterEvent(self,
shadow_frame.GetThisObject(accessor.InsSize()),
method,
0);
if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
// The caller will retry this invoke. Just return immediately without any value.
DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
DCHECK(PrevFrameWillRetry(self, shadow_frame));
return JValue();
}
if (UNLIKELY(self->IsExceptionPending())) {
instrumentation->MethodUnwindEvent(self,
shadow_frame.GetThisObject(accessor.InsSize()),
method,
0);
return JValue();
}
}

if (!stay_in_interpreter && !self->IsForceInterpreter()) {
jit::Jit* jit = Runtime::Current()->GetJit();
if (jit != nullptr) {
jit->MethodEntered(self, shadow_frame.GetMethod());
if (jit->CanInvokeCompiledCode(method)) {
JValue result;

// Pop the shadow frame before calling into compiled code.
self->PopShadowFrame();
// Calculate the offset of the first input reg. The input registers are in the high regs.
// It's ok to access the code item here since JIT code will have been touched by the
// interpreter and compiler already.
uint16_t arg_offset = accessor.RegistersSize() - accessor.InsSize();
ArtInterpreterToCompiledCodeBridge(self, nullptr, &shadow_frame, arg_offset, &result);
// Push the shadow frame back as the caller will expect it.
self->PushShadowFrame(&shadow_frame);

return result;
}
}
}
}

ArtMethod* method = shadow_frame.GetMethod();

DCheckStaticState(self, method);

// Lock counting is a special version of accessibility checks, and for simplicity and
// reduction of template parameters, we gate it behind access-checks mode.
DCHECK(!method->SkipAccessChecks() || !method->MustCountLocks());

bool transaction_active = Runtime::Current()->IsActiveTransaction();
if (LIKELY(method->SkipAccessChecks())) {
// Enter the "without access check" interpreter.
if (kInterpreterImplKind == kMterpImplKind) {
if (transaction_active) {
// No Mterp variant - just use the switch interpreter.
return ExecuteSwitchImpl<false, true>(self, accessor, shadow_frame, result_register,
false);
} else if (UNLIKELY(!Runtime::Current()->IsStarted())) {
return ExecuteSwitchImpl<false, false>(self, accessor, shadow_frame, result_register,
false);
} else {
while (true) {
// Mterp does not support all instrumentation/debugging.
if (!self->UseMterp()) {
return ExecuteSwitchImpl<false, false>(self, accessor, shadow_frame, result_register,
false);
}
bool returned = ExecuteMterpImpl(self,
accessor.Insns(),
&shadow_frame,
&result_register);
if (returned) {
return result_register;
} else {
// Mterp didn't like that instruction. Single-step it with the reference interpreter.
result_register = ExecuteSwitchImpl<false, false>(self, accessor, shadow_frame,
result_register, true);
if (shadow_frame.GetDexPC() == dex::kDexNoIndex) {
// Single-stepped a return or an exception not handled locally. Return to caller.
return result_register;
}
}
}
}
} else {
DCHECK_EQ(kInterpreterImplKind, kSwitchImplKind);
if (transaction_active) {
return ExecuteSwitchImpl<false, true>(self, accessor, shadow_frame, result_register,
false);
} else {
return ExecuteSwitchImpl<false, false>(self, accessor, shadow_frame, result_register,
false);
}
}
} else {
// Enter the "with access check" interpreter.

// The boot classpath should really not have to run access checks.
DCHECK(method->GetDeclaringClass()->GetClassLoader() != nullptr
|| Runtime::Current()->IsVerificationSoftFail()
|| Runtime::Current()->IsAotCompiler())
<< method->PrettyMethod();

if (kInterpreterImplKind == kMterpImplKind) {
// No access check variants for Mterp. Just use the switch version.
if (transaction_active) {
return ExecuteSwitchImpl<true, true>(self, accessor, shadow_frame, result_register,
false);
} else {
return ExecuteSwitchImpl<true, false>(self, accessor, shadow_frame, result_register,
false);
}
} else {
DCHECK_EQ(kInterpreterImplKind, kSwitchImplKind);
if (transaction_active) {
return ExecuteSwitchImpl<true, true>(self, accessor, shadow_frame, result_register,
false);
} else {
return ExecuteSwitchImpl<true, false>(self, accessor, shadow_frame, result_register,
false);
}
}
}
}

void EnterInterpreterFromInvoke(Thread* self,
ArtMethod* method,
ObjPtr<mirror::Object> receiver,
uint32_t* args,
JValue* result,
bool stay_in_interpreter) {
DCHECK_EQ(self, Thread::Current());
bool implicit_check = !Runtime::Current()->ExplicitStackOverflowChecks();
if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
ThrowStackOverflowError(self);
return;
}

// This can happen if we are in forced interpreter mode and an obsolete method is called using
// reflection.
if (UNLIKELY(method->IsObsolete())) {
ThrowInternalError("Attempting to invoke obsolete version of '%s'.",
method->PrettyMethod().c_str());
return;
}

const char* old_cause = self->StartAssertNoThreadSuspension("EnterInterpreterFromInvoke");
CodeItemDataAccessor accessor(method->DexInstructionData());
uint16_t num_regs;
uint16_t num_ins;
if (accessor.HasCodeItem()) {
num_regs = accessor.RegistersSize();
num_ins = accessor.InsSize();
} else if (!method->IsInvokable()) {
self->EndAssertNoThreadSuspension(old_cause);
method->ThrowInvocationTimeError();
return;
} else {
DCHECK(method->IsNative());
num_regs = num_ins = ArtMethod::NumArgRegisters(method->GetShorty());
if (!method->IsStatic()) {
num_regs++;
num_ins++;
}
}
// Set up shadow frame with matching number of reference slots to vregs.
ShadowFrame* last_shadow_frame = self->GetManagedStack()->GetTopShadowFrame();
ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
CREATE_SHADOW_FRAME(num_regs, last_shadow_frame, method, /* dex pc */ 0);
ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
self->PushShadowFrame(shadow_frame);

size_t cur_reg = num_regs - num_ins;
if (!method->IsStatic()) {
CHECK(receiver != nullptr);
shadow_frame->SetVRegReference(cur_reg, receiver);
++cur_reg;
}
uint32_t shorty_len = 0;
const char* shorty = method->GetShorty(&shorty_len);
for (size_t shorty_pos = 0, arg_pos = 0; cur_reg < num_regs; ++shorty_pos, ++arg_pos, cur_reg++) {
DCHECK_LT(shorty_pos + 1, shorty_len);
switch (shorty[shorty_pos + 1]) {
case 'L': {
ObjPtr<mirror::Object> o =
reinterpret_cast<StackReference<mirror::Object>*>(&args[arg_pos])->AsMirrorPtr();
shadow_frame->SetVRegReference(cur_reg, o);
break;
}
case 'J': case 'D': {
uint64_t wide_value = (static_cast<uint64_t>(args[arg_pos + 1]) << 32) | args[arg_pos];
shadow_frame->SetVRegLong(cur_reg, wide_value);
cur_reg++;
arg_pos++;
break;
}
default:
shadow_frame->SetVReg(cur_reg, args[arg_pos]);
break;
}
}
self->EndAssertNoThreadSuspension(old_cause);
// Do this after populating the shadow frame in case EnsureInitialized causes a GC.
if (method->IsStatic() && UNLIKELY(!method->GetDeclaringClass()->IsInitialized())) {
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
StackHandleScope<1> hs(self);
Handle<mirror::Class> h_class(hs.NewHandle(method->GetDeclaringClass()));
if (UNLIKELY(!class_linker->EnsureInitialized(self, h_class, true, true))) {
CHECK(self->IsExceptionPending());
self->PopShadowFrame();
return;
}
}
if (LIKELY(!method->IsNative())) {
JValue r = Execute(self, accessor, *shadow_frame, JValue(), stay_in_interpreter);
if (result != nullptr) {
*result = r;
}
} else {
// We don't expect to be asked to interpret native code (which is entered via a JNI compiler
// generated stub) except during testing and image writing.
// Update args to be the args in the shadow frame since the input ones could hold stale
// references pointers due to moving GC.
args = shadow_frame->GetVRegArgs(method->IsStatic() ? 0 : 1);
if (!Runtime::Current()->IsStarted()) {
UnstartedRuntime::Jni(self, method, receiver.Ptr(), args, result);
} else {
InterpreterJni(self, method, shorty, receiver, args, result);
}
}
self->PopShadowFrame();
}

static int16_t GetReceiverRegisterForStringInit(const Instruction* instr) {
DCHECK(instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE ||
instr->Opcode() == Instruction::INVOKE_DIRECT);
return (instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) ?
instr->VRegC_3rc() : instr->VRegC_35c();
}

void EnterInterpreterFromDeoptimize(Thread* self,
ShadowFrame* shadow_frame,
JValue* ret_val,
bool from_code,
DeoptimizationMethodType deopt_method_type)
REQUIRES_SHARED(Locks::mutator_lock_) {
JValue value;
// Set value to last known result in case the shadow frame chain is empty.
value.SetJ(ret_val->GetJ());
// How many frames we have executed.
size_t frame_cnt = 0;
while (shadow_frame != nullptr) {
// We do not want to recover lock state for lock counting when deoptimizing. Currently,
// the compiler should not have compiled a method that failed structured-locking checks.
DCHECK(!shadow_frame->GetMethod()->MustCountLocks());

self->SetTopOfShadowStack(shadow_frame);
CodeItemDataAccessor accessor(shadow_frame->GetMethod()->DexInstructionData());
const uint32_t dex_pc = shadow_frame->GetDexPC();
uint32_t new_dex_pc = dex_pc;
if (UNLIKELY(self->IsExceptionPending())) {
// If we deoptimize from the QuickExceptionHandler, we already reported the exception to
// the instrumentation. To prevent from reporting it a second time, we simply pass a
// null Instrumentation*.
const instrumentation::Instrumentation* const instrumentation =
frame_cnt == 0 ? nullptr : Runtime::Current()->GetInstrumentation();
new_dex_pc = MoveToExceptionHandler(
self, *shadow_frame, instrumentation) ? shadow_frame->GetDexPC() : dex::kDexNoIndex;
} else if (!from_code) {
// Deoptimization is not called from code directly.
const Instruction* instr = &accessor.InstructionAt(dex_pc);
if (deopt_method_type == DeoptimizationMethodType::kKeepDexPc ||
shadow_frame->GetForceRetryInstruction()) {
DCHECK(frame_cnt == 0 || (frame_cnt == 1 && shadow_frame->GetForceRetryInstruction()))
<< "frame_cnt: " << frame_cnt
<< " force-retry: " << shadow_frame->GetForceRetryInstruction();
// Need to re-execute the dex instruction.
// (1) An invocation might be split into class initialization and invoke.
// In this case, the invoke should not be skipped.
// (2) A suspend check should also execute the dex instruction at the
// corresponding dex pc.
// If the ForceRetryInstruction bit is set this must be the second frame (the first being
// the one that is being popped).
DCHECK_EQ(new_dex_pc, dex_pc);
shadow_frame->SetForceRetryInstruction(false);
} else if (instr->Opcode() == Instruction::MONITOR_ENTER ||
instr->Opcode() == Instruction::MONITOR_EXIT) {
DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
DCHECK_EQ(frame_cnt, 0u);
// Non-idempotent dex instruction should not be re-executed.
// On the other hand, if a MONITOR_ENTER is at the dex_pc of a suspend
// check, that MONITOR_ENTER should be executed. That case is handled
// above.
new_dex_pc = dex_pc + instr->SizeInCodeUnits();
} else if (instr->IsInvoke()) {
DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
if (IsStringInit(instr, shadow_frame->GetMethod())) {
uint16_t this_obj_vreg = GetReceiverRegisterForStringInit(instr);
// Move the StringFactory.newStringFromChars() result into the register representing
// "this object" when invoking the string constructor in the original dex instruction.
// Also move the result into all aliases.
DCHECK(value.GetL()->IsString());
SetStringInitValueToAllAliases(shadow_frame, this_obj_vreg, value);
// Calling string constructor in the original dex code doesn't generate a result value.
value.SetJ(0);
}
new_dex_pc = dex_pc + instr->SizeInCodeUnits();
} else if (instr->Opcode() == Instruction::NEW_INSTANCE) {
// A NEW_INSTANCE is simply re-executed, including
// "new-instance String" which is compiled into a call into
// StringFactory.newEmptyString().
DCHECK_EQ(new_dex_pc, dex_pc);
} else {
DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
DCHECK_EQ(frame_cnt, 0u);
// By default, we re-execute the dex instruction since if they are not
// an invoke, so that we don't have to decode the dex instruction to move
// result into the right vreg. All slow paths have been audited to be
// idempotent except monitor-enter/exit and invocation stubs.
// TODO: move result and advance dex pc. That also requires that we
// can tell the return type of a runtime method, possibly by decoding
// the dex instruction at the caller.
DCHECK_EQ(new_dex_pc, dex_pc);
}
} else {
// Nothing to do, the dex_pc is the one at which the code requested
// the deoptimization.
DCHECK_EQ(frame_cnt, 0u);
DCHECK_EQ(new_dex_pc, dex_pc);
}
if (new_dex_pc != dex::kDexNoIndex) {
shadow_frame->SetDexPC(new_dex_pc);
value = Execute(self,
accessor,
*shadow_frame,
value,
/* stay_in_interpreter= */ true,
/* from_deoptimize= */ true);
}
ShadowFrame* old_frame = shadow_frame;
shadow_frame = shadow_frame->GetLink();
ShadowFrame::DeleteDeoptimizedFrame(old_frame);
// Following deoptimizations of shadow frames must be at invocation point
// and should advance dex pc past the invoke instruction.
from_code = false;
deopt_method_type = DeoptimizationMethodType::kDefault;
frame_cnt++;
}
ret_val->SetJ(value.GetJ());
}

JValue EnterInterpreterFromEntryPoint(Thread* self, const CodeItemDataAccessor& accessor,
ShadowFrame* shadow_frame) {
DCHECK_EQ(self, Thread::Current());
bool implicit_check = !Runtime::Current()->ExplicitStackOverflowChecks();
if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
ThrowStackOverflowError(self);
return JValue();
}

jit::Jit* jit = Runtime::Current()->GetJit();
if (jit != nullptr) {
jit->NotifyCompiledCodeToInterpreterTransition(self, shadow_frame->GetMethod());
}
return Execute(self, accessor, *shadow_frame, JValue());
}

void ArtInterpreterToInterpreterBridge(Thread* self,
const CodeItemDataAccessor& accessor,
ShadowFrame* shadow_frame,
JValue* result) {
bool implicit_check = !Runtime::Current()->ExplicitStackOverflowChecks();
if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
ThrowStackOverflowError(self);
return;
}

self->PushShadowFrame(shadow_frame);
ArtMethod* method = shadow_frame->GetMethod();
// Ensure static methods are initialized.
const bool is_static = method->IsStatic();
if (is_static) {
ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
if (UNLIKELY(!declaring_class->IsInitialized())) {
StackHandleScope<1> hs(self);
HandleWrapperObjPtr<mirror::Class> h_declaring_class(hs.NewHandleWrapper(&declaring_class));
if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(
self, h_declaring_class, true, true))) {
DCHECK(self->IsExceptionPending());
self->PopShadowFrame();
return;
}
CHECK(h_declaring_class->IsInitializing());
}
}

if (LIKELY(!shadow_frame->GetMethod()->IsNative())) {
result->SetJ(Execute(self, accessor, *shadow_frame, JValue()).GetJ());
} else {
// We don't expect to be asked to interpret native code (which is entered via a JNI compiler
// generated stub) except during testing and image writing.
CHECK(!Runtime::Current()->IsStarted());
ObjPtr<mirror::Object> receiver = is_static ? nullptr : shadow_frame->GetVRegReference(0);
uint32_t* args = shadow_frame->GetVRegArgs(is_static ? 0 : 1);
UnstartedRuntime::Jni(self, shadow_frame->GetMethod(), receiver.Ptr(), args, result);
}

self->PopShadowFrame();
}

void CheckInterpreterAsmConstants() {
CheckMterpAsmConstants();
}

void InitInterpreterTls(Thread* self) {
InitMterpTls(self);
}

bool PrevFrameWillRetry(Thread* self, const ShadowFrame& frame) {
ShadowFrame* prev_frame = frame.GetLink();
if (prev_frame == nullptr) {
NthCallerVisitor vis(self, 1, false);
vis.WalkStack();
prev_frame = vis.GetCurrentShadowFrame();
if (prev_frame == nullptr) {
prev_frame = self->FindDebuggerShadowFrame(vis.GetFrameId());
}
}
return prev_frame != nullptr && prev_frame->GetForceRetryInstruction();
}

} // namespace interpreter
} // namespace art

artMethod.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "art_method.h"

#include <cstddef>

#include "android-base/stringprintf.h"

#include "arch/context.h"
#include "art_method-inl.h"
#include "class_linker-inl.h"
#include "class_root.h"
#include "debugger.h"
#include "dex/class_accessor-inl.h"
#include "dex/descriptors_names.h"
#include "dex/dex_file-inl.h"
#include "dex/dex_file_exception_helpers.h"
#include "dex/dex_instruction.h"
#include "dex/signature-inl.h"
#include "entrypoints/runtime_asm_entrypoints.h"
#include "gc/accounting/card_table-inl.h"
#include "hidden_api.h"
#include "interpreter/interpreter.h"
#include "jit/jit.h"
#include "jit/jit_code_cache.h"
#include "jit/profiling_info.h"
#include "jni/jni_internal.h"
#include "mirror/class-inl.h"
#include "mirror/class_ext-inl.h"
#include "mirror/executable.h"
#include "mirror/object-inl.h"
#include "mirror/object_array-inl.h"
#include "mirror/string.h"
#include "oat_file-inl.h"
#include "quicken_info.h"
#include "runtime_callbacks.h"
#include "scoped_thread_state_change-inl.h"
#include "vdex_file.h"

#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "runtime.h"
#include <android/log.h>
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>

#define gettidv1() syscall(__NR_gettid)
#define LOG_TAG "ActivityThread"
#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

namespace art {

using android::base::StringPrintf;

extern "C" void art_quick_invoke_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
const char*);
extern "C" void art_quick_invoke_static_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
const char*);

// Enforce that we he have the right index for runtime methods.
static_assert(ArtMethod::kRuntimeMethodDexMethodIndex == dex::kDexNoIndex,
"Wrong runtime-method dex method index");

extern "C" void saveDexFileByExecute(ArtMethod * artMethod) REQUIRES_SHARED(Locks::mutator_lock_) {
char* dexFilePath = (char*)malloc(sizeof(char) * 1000);
if (dexFilePath == nullptr) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, methodName: " << artMethod->PrettyMethod().c_str() << " malloc 1000 byte failed";
return;
}
int result = 0;
int fcmdline = -1;
char szCmdline[64] = {0};
char szProcName[256] = {0};
int procid = getpid();
sprintf(szCmdline, "/proc/%d/cmdline", procid);
fcmdline = open(szCmdline, O_RDONLY, 0644);
if (fcmdline > 0) {
result = read(fcmdline, szProcName, 256);
if (result < 0) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, open cmdline file error";
}
close(fcmdline);
} else {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, open cmdline file success";
}

if (szProcName[0]) {
const DexFile* dex_file = artMethod->GetDexFile();
const uint8_t* begin_ = dex_file->Begin(); // Start of data.
size_t size_ = dex_file->Size(); // Length of data.
int size_int_ = (int)size_;

memset(dexFilePath, 0, 1000);
sprintf(dexFilePath, "/data/data/%s/JohnDemo", szProcName);
mkdir(dexFilePath, 0777);

memset(dexFilePath, 0, 1000);
sprintf(dexFilePath, "/data/data/%s/JohnDemo/%d_dexfile_execute.dex", szProcName, size_int_);
int dexFileFp = open(dexFilePath, O_RDONLY, 0666);
if (dexFileFp > 0) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, dexFile exsit";
close(dexFileFp);
dexFileFp = 0;
} else {
int fp = open(dexFilePath, O_CREAT | O_APPEND | O_RDWR, 0666);
if (fp > 0) {
result = write(fp, (void*)begin_, size_);
if (result < 0) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, write dexFilePath error";
}
fsync(fp);
close(fp);
memset(dexFilePath, 0, 1000);
sprintf(dexFilePath, "/data/data/%s/JohnDemo/%d_classlist_execute.txt", szProcName, size_int_);
int classListFile = open(dexFilePath, O_CREAT | O_APPEND | O_RDWR, 0666);
if (classListFile > 0) {
for (size_t ii = 0; ii < dex_file->NumClassDefs(); ++ii) {
const DexFile::ClassDef & class_def = dex_file->GetClassDef(ii);
const char* descriptor = dex_file->GetClassDescriptor(class_def);
result = write(classListFile, (void*)descriptor, strlen(descriptor));
if (result < 0) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, write classListFile file error";
}
const char * temp = "\n";
result = write(classListFile, (void * )temp, 1);
if (result < 0) {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, write classListFile file error";
}
}
fsync(classListFile);
close(classListFile);
}
} else {
LOG(ERROR) << "ArtMethod::saveDexFileByExecute, open dexFilePath error";
}
}
}
if (dexFilePath != nullptr) {
free(dexFilePath);
dexFilePath = nullptr;
}
}

ArtMethod* ArtMethod::GetCanonicalMethod(PointerSize pointer_size) {
if (LIKELY(!IsDefault())) {
return this;
} else {
ObjPtr<mirror::Class> declaring_class = GetDeclaringClass();
DCHECK(declaring_class->IsInterface());
ArtMethod* ret = declaring_class->FindInterfaceMethod(GetDexCache(),
GetDexMethodIndex(),
pointer_size);
DCHECK(ret != nullptr);
return ret;
}
}

ArtMethod* ArtMethod::GetNonObsoleteMethod() {
if (LIKELY(!IsObsolete())) {
return this;
}
DCHECK_EQ(kRuntimePointerSize, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
if (IsDirect()) {
return &GetDeclaringClass()->GetDirectMethodsSlice(kRuntimePointerSize)[GetMethodIndex()];
} else {
return GetDeclaringClass()->GetVTableEntry(GetMethodIndex(), kRuntimePointerSize);
}
}

ArtMethod* ArtMethod::GetSingleImplementation(PointerSize pointer_size) {
if (!IsAbstract()) {
// A non-abstract's single implementation is itself.
return this;
}
return reinterpret_cast<ArtMethod*>(GetDataPtrSize(pointer_size));
}

ArtMethod* ArtMethod::FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable& soa,
jobject jlr_method) {
ObjPtr<mirror::Executable> executable = soa.Decode<mirror::Executable>(jlr_method);
DCHECK(executable != nullptr);
return executable->GetArtMethod();
}

ObjPtr<mirror::DexCache> ArtMethod::GetObsoleteDexCache() {
DCHECK(!Runtime::Current()->IsAotCompiler()) << PrettyMethod();
DCHECK(IsObsolete());
ObjPtr<mirror::ClassExt> ext(GetDeclaringClass()->GetExtData());
CHECK(!ext.IsNull());
ObjPtr<mirror::PointerArray> obsolete_methods(ext->GetObsoleteMethods());
CHECK(!obsolete_methods.IsNull());
DCHECK(ext->GetObsoleteDexCaches() != nullptr);
int32_t len = obsolete_methods->GetLength();
DCHECK_EQ(len, ext->GetObsoleteDexCaches()->GetLength());
// Using kRuntimePointerSize (instead of using the image's pointer size) is fine since images
// should never have obsolete methods in them so they should always be the same.
PointerSize pointer_size = kRuntimePointerSize;
DCHECK_EQ(kRuntimePointerSize, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
for (int32_t i = 0; i < len; i++) {
if (this == obsolete_methods->GetElementPtrSize<ArtMethod*>(i, pointer_size)) {
return ext->GetObsoleteDexCaches()->Get(i);
}
}
LOG(FATAL) << "This method does not appear in the obsolete map of its class!";
UNREACHABLE();
}

uint16_t ArtMethod::FindObsoleteDexClassDefIndex() {
DCHECK(!Runtime::Current()->IsAotCompiler()) << PrettyMethod();
DCHECK(IsObsolete());
const DexFile* dex_file = GetDexFile();
const dex::TypeIndex declaring_class_type = dex_file->GetMethodId(GetDexMethodIndex()).class_idx_;
const dex::ClassDef* class_def = dex_file->FindClassDef(declaring_class_type);
CHECK(class_def != nullptr);
return dex_file->GetIndexForClassDef(*class_def);
}

void ArtMethod::ThrowInvocationTimeError() {
DCHECK(!IsInvokable());
// NOTE: IsDefaultConflicting must be first since the actual method might or might not be abstract
// due to the way we select it.
if (IsDefaultConflicting()) {
ThrowIncompatibleClassChangeErrorForMethodConflict(this);
} else {
DCHECK(IsAbstract());
ThrowAbstractMethodError(this);
}
}

InvokeType ArtMethod::GetInvokeType() {
// TODO: kSuper?
if (IsStatic()) {
return kStatic;
} else if (GetDeclaringClass()->IsInterface()) {
return kInterface;
} else if (IsDirect()) {
return kDirect;
} else if (IsPolymorphicSignature()) {
return kPolymorphic;
} else {
return kVirtual;
}
}

size_t ArtMethod::NumArgRegisters(const char* shorty) {
CHECK_NE(shorty[0], '\0');
uint32_t num_registers = 0;
for (const char* s = shorty + 1; *s != '\0'; ++s) {
if (*s == 'D' || *s == 'J') {
num_registers += 2;
} else {
num_registers += 1;
}
}
return num_registers;
}

bool ArtMethod::HasSameNameAndSignature(ArtMethod* other) {
ScopedAssertNoThreadSuspension ants("HasSameNameAndSignature");
const DexFile* dex_file = GetDexFile();
const dex::MethodId& mid = dex_file->GetMethodId(GetDexMethodIndex());
if (GetDexCache() == other->GetDexCache()) {
const dex::MethodId& mid2 = dex_file->GetMethodId(other->GetDexMethodIndex());
return mid.name_idx_ == mid2.name_idx_ && mid.proto_idx_ == mid2.proto_idx_;
}
const DexFile* dex_file2 = other->GetDexFile();
const dex::MethodId& mid2 = dex_file2->GetMethodId(other->GetDexMethodIndex());
if (!DexFile::StringEquals(dex_file, mid.name_idx_, dex_file2, mid2.name_idx_)) {
return false; // Name mismatch.
}
return dex_file->GetMethodSignature(mid) == dex_file2->GetMethodSignature(mid2);
}

ArtMethod* ArtMethod::FindOverriddenMethod(PointerSize pointer_size) {
if (IsStatic()) {
return nullptr;
}
ObjPtr<mirror::Class> declaring_class = GetDeclaringClass();
ObjPtr<mirror::Class> super_class = declaring_class->GetSuperClass();
uint16_t method_index = GetMethodIndex();
ArtMethod* result = nullptr;
// Did this method override a super class method? If so load the result from the super class'
// vtable
if (super_class->HasVTable() && method_index < super_class->GetVTableLength()) {
result = super_class->GetVTableEntry(method_index, pointer_size);
} else {
// Method didn't override superclass method so search interfaces
if (IsProxyMethod()) {
result = GetInterfaceMethodIfProxy(pointer_size);
DCHECK(result != nullptr);
} else {
ObjPtr<mirror::IfTable> iftable = GetDeclaringClass()->GetIfTable();
for (size_t i = 0; i < iftable->Count() && result == nullptr; i++) {
ObjPtr<mirror::Class> interface = iftable->GetInterface(i);
for (ArtMethod& interface_method : interface->GetVirtualMethods(pointer_size)) {
if (HasSameNameAndSignature(interface_method.GetInterfaceMethodIfProxy(pointer_size))) {
result = &interface_method;
break;
}
}
}
}
}
DCHECK(result == nullptr ||
GetInterfaceMethodIfProxy(pointer_size)->HasSameNameAndSignature(
result->GetInterfaceMethodIfProxy(pointer_size)));
return result;
}

uint32_t ArtMethod::FindDexMethodIndexInOtherDexFile(const DexFile& other_dexfile,
uint32_t name_and_signature_idx) {
const DexFile* dexfile = GetDexFile();
const uint32_t dex_method_idx = GetDexMethodIndex();
const dex::MethodId& mid = dexfile->GetMethodId(dex_method_idx);
const dex::MethodId& name_and_sig_mid = other_dexfile.GetMethodId(name_and_signature_idx);
DCHECK_STREQ(dexfile->GetMethodName(mid), other_dexfile.GetMethodName(name_and_sig_mid));
DCHECK_EQ(dexfile->GetMethodSignature(mid), other_dexfile.GetMethodSignature(name_and_sig_mid));
if (dexfile == &other_dexfile) {
return dex_method_idx;
}
const char* mid_declaring_class_descriptor = dexfile->StringByTypeIdx(mid.class_idx_);
const dex::TypeId* other_type_id = other_dexfile.FindTypeId(mid_declaring_class_descriptor);
if (other_type_id != nullptr) {
const dex::MethodId* other_mid = other_dexfile.FindMethodId(
*other_type_id, other_dexfile.GetStringId(name_and_sig_mid.name_idx_),
other_dexfile.GetProtoId(name_and_sig_mid.proto_idx_));
if (other_mid != nullptr) {
return other_dexfile.GetIndexForMethodId(*other_mid);
}
}
return dex::kDexNoIndex;
}

uint32_t ArtMethod::FindCatchBlock(Handle<mirror::Class> exception_type,
uint32_t dex_pc, bool* has_no_move_exception) {
// Set aside the exception while we resolve its type.
Thread* self = Thread::Current();
StackHandleScope<1> hs(self);
Handle<mirror::Throwable> exception(hs.NewHandle(self->GetException()));
self->ClearException();
// Default to handler not found.
uint32_t found_dex_pc = dex::kDexNoIndex;
// Iterate over the catch handlers associated with dex_pc.
CodeItemDataAccessor accessor(DexInstructionData());
for (CatchHandlerIterator it(accessor, dex_pc); it.HasNext(); it.Next()) {
dex::TypeIndex iter_type_idx = it.GetHandlerTypeIndex();
// Catch all case
if (!iter_type_idx.IsValid()) {
found_dex_pc = it.GetHandlerAddress();
break;
}
// Does this catch exception type apply?
ObjPtr<mirror::Class> iter_exception_type = ResolveClassFromTypeIndex(iter_type_idx);
if (UNLIKELY(iter_exception_type == nullptr)) {
// Now have a NoClassDefFoundError as exception. Ignore in case the exception class was
// removed by a pro-guard like tool.
// Note: this is not RI behavior. RI would have failed when loading the class.
self->ClearException();
// Delete any long jump context as this routine is called during a stack walk which will
// release its in use context at the end.
delete self->GetLongJumpContext();
LOG(WARNING) << "Unresolved exception class when finding catch block: "
<< DescriptorToDot(GetTypeDescriptorFromTypeIdx(iter_type_idx));
} else if (iter_exception_type->IsAssignableFrom(exception_type.Get())) {
found_dex_pc = it.GetHandlerAddress();
break;
}
}
if (found_dex_pc != dex::kDexNoIndex) {
const Instruction& first_catch_instr = accessor.InstructionAt(found_dex_pc);
*has_no_move_exception = (first_catch_instr.Opcode() != Instruction::MOVE_EXCEPTION);
}
// Put the exception back.
if (exception != nullptr) {
self->SetException(exception.Get());
}
return found_dex_pc;
}

void ArtMethod::Invoke(Thread* self, uint32_t* args, uint32_t args_size, JValue* result,
const char* shorty) {
if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEnd())) {
ThrowStackOverflowError(self);
return;
}

if (kIsDebugBuild) {
self->AssertThreadSuspensionIsAllowable();
CHECK_EQ(kRunnable, self->GetState());
CHECK_STREQ(GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(), shorty);
}

// Push a transition back into managed code onto the linked list in thread.
ManagedStack fragment;
self->PushManagedStackFragment(&fragment);

Runtime* runtime = Runtime::Current();
// Call the invoke stub, passing everything as arguments.
// If the runtime is not yet started or it is required by the debugger, then perform the
// Invocation by the interpreter, explicitly forcing interpretation over JIT to prevent
// cycling around the various JIT/Interpreter methods that handle method invocation.
if (UNLIKELY(!runtime->IsStarted() ||
(self->IsForceInterpreter() && !IsNative() && !IsProxyMethod() && IsInvokable()) ||
Dbg::IsForcedInterpreterNeededForCalling(self, this))) {
if (IsStatic()) {
art::interpreter::EnterInterpreterFromInvoke(
self, this, nullptr, args, result, /*stay_in_interpreter=*/ true);
} else {
mirror::Object* receiver =
reinterpret_cast<StackReference<mirror::Object>*>(&args[0])->AsMirrorPtr();
art::interpreter::EnterInterpreterFromInvoke(
self, this, receiver, args + 1, result, /*stay_in_interpreter=*/ true);
}
} else {
DCHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);

constexpr bool kLogInvocationStartAndReturn = false;
bool have_quick_code = GetEntryPointFromQuickCompiledCode() != nullptr;
if (LIKELY(have_quick_code)) {
if (kLogInvocationStartAndReturn) {
LOG(INFO) << StringPrintf(
"Invoking '%s' quick code=%p static=%d", PrettyMethod().c_str(),
GetEntryPointFromQuickCompiledCode(), static_cast<int>(IsStatic() ? 1 : 0));
}

// Ensure that we won't be accidentally calling quick compiled code when -Xint.
if (kIsDebugBuild && runtime->GetInstrumentation()->IsForcedInterpretOnly()) {
CHECK(!runtime->UseJitCompilation());
const void* oat_quick_code =
(IsNative() || !IsInvokable() || IsProxyMethod() || IsObsolete())
? nullptr
: GetOatMethodQuickCode(runtime->GetClassLinker()->GetImagePointerSize());
CHECK(oat_quick_code == nullptr || oat_quick_code != GetEntryPointFromQuickCompiledCode())
<< "Don't call compiled code when -Xint " << PrettyMethod();
}

if (!IsStatic()) {
(*art_quick_invoke_stub)(this, args, args_size, self, result, shorty);
} else {
(*art_quick_invoke_static_stub)(this, args, args_size, self, result, shorty);
}
if (UNLIKELY(self->GetException() == Thread::GetDeoptimizationException())) {
// Unusual case where we were running generated code and an
// exception was thrown to force the activations to be removed from the
// stack. Continue execution in the interpreter.
self->DeoptimizeWithDeoptimizationException(result);
}
if (kLogInvocationStartAndReturn) {
LOG(INFO) << StringPrintf("Returned '%s' quick code=%p", PrettyMethod().c_str(),
GetEntryPointFromQuickCompiledCode());
}
} else {
LOG(INFO) << "Not invoking '" << PrettyMethod() << "' code=null";
if (result != nullptr) {
result->SetJ(0);
}
}
}

// Pop transition.
self->PopManagedStackFragment(fragment);
}

const void* ArtMethod::RegisterNative(const void* native_method) {
CHECK(IsNative()) << PrettyMethod();
CHECK(native_method != nullptr) << PrettyMethod();
void* new_native_method = nullptr;
Runtime::Current()->GetRuntimeCallbacks()->RegisterNativeMethod(this,
native_method,
/*out*/&new_native_method);
SetEntryPointFromJni(new_native_method);
return new_native_method;
}

void ArtMethod::UnregisterNative() {
CHECK(IsNative()) << PrettyMethod();
// restore stub to lookup native pointer via dlsym
SetEntryPointFromJni(GetJniDlsymLookupStub());
}

bool ArtMethod::IsOverridableByDefaultMethod() {
return GetDeclaringClass()->IsInterface();
}

bool ArtMethod::IsPolymorphicSignature() {
// Methods with a polymorphic signature have constraints that they
// are native and varargs and belong to either MethodHandle or VarHandle.
if (!IsNative() || !IsVarargs()) {
return false;
}
ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
Runtime::Current()->GetClassLinker()->GetClassRoots();
ObjPtr<mirror::Class> cls = GetDeclaringClass();
return (cls == GetClassRoot<mirror::MethodHandle>(class_roots) ||
cls == GetClassRoot<mirror::VarHandle>(class_roots));
}

static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
uint16_t class_def_idx,
uint32_t method_idx) {
ClassAccessor accessor(dex_file, class_def_idx);
uint32_t class_def_method_index = 0u;
for (const ClassAccessor::Method& method : accessor.GetMethods()) {
if (method.GetIndex() == method_idx) {
return class_def_method_index;
}
class_def_method_index++;
}
LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
UNREACHABLE();
}

// We use the method's DexFile and declaring class name to find the OatMethod for an obsolete
// method. This is extremely slow but we need it if we want to be able to have obsolete native
// methods since we need this to find the size of its stack frames.
//
// NB We could (potentially) do this differently and rely on the way the transformation is applied
// in order to use the entrypoint to find this information. However, for debugging reasons (most
// notably making sure that new invokes of obsolete methods fail) we choose to instead get the data
// directly from the dex file.
static const OatFile::OatMethod FindOatMethodFromDexFileFor(ArtMethod* method, bool* found)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(method->IsObsolete() && method->IsNative());
const DexFile* dex_file = method->GetDexFile();

// recreate the class_def_index from the descriptor.
std::string descriptor_storage;
const dex::TypeId* declaring_class_type_id =
dex_file->FindTypeId(method->GetDeclaringClass()->GetDescriptor(&descriptor_storage));
CHECK(declaring_class_type_id != nullptr);
dex::TypeIndex declaring_class_type_index = dex_file->GetIndexForTypeId(*declaring_class_type_id);
const dex::ClassDef* declaring_class_type_def =
dex_file->FindClassDef(declaring_class_type_index);
CHECK(declaring_class_type_def != nullptr);
uint16_t declaring_class_def_index = dex_file->GetIndexForClassDef(*declaring_class_type_def);

size_t oat_method_index = GetOatMethodIndexFromMethodIndex(*dex_file,
declaring_class_def_index,
method->GetDexMethodIndex());

OatFile::OatClass oat_class = OatFile::FindOatClass(*dex_file,
declaring_class_def_index,
found);
if (!(*found)) {
return OatFile::OatMethod::Invalid();
}
return oat_class.GetOatMethod(oat_method_index);
}

static const OatFile::OatMethod FindOatMethodFor(ArtMethod* method,
PointerSize pointer_size,
bool* found)
REQUIRES_SHARED(Locks::mutator_lock_) {
if (UNLIKELY(method->IsObsolete())) {
// We shouldn't be calling this with obsolete methods except for native obsolete methods for
// which we need to use the oat method to figure out how large the quick frame is.
DCHECK(method->IsNative()) << "We should only be finding the OatMethod of obsolete methods in "
<< "order to allow stack walking. Other obsolete methods should "
<< "never need to access this information.";
DCHECK_EQ(pointer_size, kRuntimePointerSize) << "Obsolete method in compiler!";
return FindOatMethodFromDexFileFor(method, found);
}
// Although we overwrite the trampoline of non-static methods, we may get here via the resolution
// method for direct methods (or virtual methods made direct).
ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
size_t oat_method_index;
if (method->IsStatic() || method->IsDirect()) {
// Simple case where the oat method index was stashed at load time.
oat_method_index = method->GetMethodIndex();
} else {
// Compute the oat_method_index by search for its position in the declared virtual methods.
oat_method_index = declaring_class->NumDirectMethods();
bool found_virtual = false;
for (ArtMethod& art_method : declaring_class->GetVirtualMethods(pointer_size)) {
// Check method index instead of identity in case of duplicate method definitions.
if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) {
found_virtual = true;
break;
}
oat_method_index++;
}
CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
<< method->PrettyMethod();
}
DCHECK_EQ(oat_method_index,
GetOatMethodIndexFromMethodIndex(declaring_class->GetDexFile(),
method->GetDeclaringClass()->GetDexClassDefIndex(),
method->GetDexMethodIndex()));
OatFile::OatClass oat_class = OatFile::FindOatClass(declaring_class->GetDexFile(),
declaring_class->GetDexClassDefIndex(),
found);
if (!(*found)) {
return OatFile::OatMethod::Invalid();
}
return oat_class.GetOatMethod(oat_method_index);
}

bool ArtMethod::EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params) {
const DexFile* dex_file = GetDexFile();
const auto& method_id = dex_file->GetMethodId(GetDexMethodIndex());
const auto& proto_id = dex_file->GetMethodPrototype(method_id);
const dex::TypeList* proto_params = dex_file->GetProtoParameters(proto_id);
auto count = proto_params != nullptr ? proto_params->Size() : 0u;
auto param_len = params != nullptr ? params->GetLength() : 0u;
if (param_len != count) {
return false;
}
auto* cl = Runtime::Current()->GetClassLinker();
for (size_t i = 0; i < count; ++i) {
dex::TypeIndex type_idx = proto_params->GetTypeItem(i).type_idx_;
ObjPtr<mirror::Class> type = cl->ResolveType(type_idx, this);
if (type == nullptr) {
Thread::Current()->AssertPendingException();
return false;
}
if (type != params->GetWithoutChecks(i)) {
return false;
}
}
return true;
}

ArrayRef<const uint8_t> ArtMethod::GetQuickenedInfo() {
const DexFile& dex_file = *GetDexFile();
const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
if (oat_dex_file == nullptr) {
return ArrayRef<const uint8_t>();
}
return oat_dex_file->GetQuickenedInfoOf(dex_file, GetDexMethodIndex());
}

uint16_t ArtMethod::GetIndexFromQuickening(uint32_t dex_pc) {
ArrayRef<const uint8_t> data = GetQuickenedInfo();
if (data.empty()) {
return DexFile::kDexNoIndex16;
}
QuickenInfoTable table(data);
uint32_t quicken_index = 0;
for (const DexInstructionPcPair& pair : DexInstructions()) {
if (pair.DexPc() == dex_pc) {
return table.GetData(quicken_index);
}
if (QuickenInfoTable::NeedsIndexForInstruction(&pair.Inst())) {
++quicken_index;
}
}
return DexFile::kDexNoIndex16;
}

const OatQuickMethodHeader* ArtMethod::GetOatQuickMethodHeader(uintptr_t pc) {
// Our callers should make sure they don't pass the instrumentation exit pc,
// as this method does not look at the side instrumentation stack.
DCHECK_NE(pc, reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()));

if (IsRuntimeMethod()) {
return nullptr;
}

Runtime* runtime = Runtime::Current();
const void* existing_entry_point = GetEntryPointFromQuickCompiledCode();
CHECK(existing_entry_point != nullptr) << PrettyMethod() << "@" << this;
ClassLinker* class_linker = runtime->GetClassLinker();

if (existing_entry_point == GetQuickProxyInvokeHandler()) {
DCHECK(IsProxyMethod() && !IsConstructor());
// The proxy entry point does not have any method header.
return nullptr;
}

// Check whether the current entry point contains this pc.
if (!class_linker->IsQuickGenericJniStub(existing_entry_point) &&
!class_linker->IsQuickResolutionStub(existing_entry_point) &&
!class_linker->IsQuickToInterpreterBridge(existing_entry_point) &&
existing_entry_point != GetQuickInstrumentationEntryPoint()) {
OatQuickMethodHeader* method_header =
OatQuickMethodHeader::FromEntryPoint(existing_entry_point);

if (method_header->Contains(pc)) {
return method_header;
}
}

// Check whether the pc is in the JIT code cache.
jit::Jit* jit = runtime->GetJit();
if (jit != nullptr) {
jit::JitCodeCache* code_cache = jit->GetCodeCache();
OatQuickMethodHeader* method_header = code_cache->LookupMethodHeader(pc, this);
if (method_header != nullptr) {
DCHECK(method_header->Contains(pc));
return method_header;
} else {
DCHECK(!code_cache->ContainsPc(reinterpret_cast<const void*>(pc)))
<< PrettyMethod()
<< ", pc=" << std::hex << pc
<< ", entry_point=" << std::hex << reinterpret_cast<uintptr_t>(existing_entry_point)
<< ", copy=" << std::boolalpha << IsCopied()
<< ", proxy=" << std::boolalpha << IsProxyMethod();
}
}

// The code has to be in an oat file.
bool found;
OatFile::OatMethod oat_method =
FindOatMethodFor(this, class_linker->GetImagePointerSize(), &found);
if (!found) {
if (IsNative()) {
// We are running the GenericJNI stub. The entrypoint may point
// to different entrypoints or to a JIT-compiled JNI stub.
DCHECK(class_linker->IsQuickGenericJniStub(existing_entry_point) ||
class_linker->IsQuickResolutionStub(existing_entry_point) ||
existing_entry_point == GetQuickInstrumentationEntryPoint() ||
(jit != nullptr && jit->GetCodeCache()->ContainsPc(existing_entry_point)));
return nullptr;
}
// Only for unit tests.
// TODO(ngeoffray): Update these tests to pass the right pc?
return OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
}
const void* oat_entry_point = oat_method.GetQuickCode();
if (oat_entry_point == nullptr || class_linker->IsQuickGenericJniStub(oat_entry_point)) {
DCHECK(IsNative()) << PrettyMethod();
return nullptr;
}

OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromEntryPoint(oat_entry_point);
if (pc == 0) {
// This is a downcall, it can only happen for a native method.
DCHECK(IsNative());
return method_header;
}

DCHECK(method_header->Contains(pc))
<< PrettyMethod()
<< " " << std::hex << pc << " " << oat_entry_point
<< " " << (uintptr_t)(method_header->GetCode() + method_header->GetCodeSize());
return method_header;
}

const void* ArtMethod::GetOatMethodQuickCode(PointerSize pointer_size) {
bool found;
OatFile::OatMethod oat_method = FindOatMethodFor(this, pointer_size, &found);
if (found) {
return oat_method.GetQuickCode();
}
return nullptr;
}

bool ArtMethod::HasAnyCompiledCode() {
if (IsNative() || !IsInvokable() || IsProxyMethod()) {
return false;
}

// Check whether the JIT has compiled it.
Runtime* runtime = Runtime::Current();
jit::Jit* jit = runtime->GetJit();
if (jit != nullptr && jit->GetCodeCache()->ContainsMethod(this)) {
return true;
}

// Check whether we have AOT code.
return GetOatMethodQuickCode(runtime->GetClassLinker()->GetImagePointerSize()) != nullptr;
}

void ArtMethod::SetIntrinsic(uint32_t intrinsic) {
// Currently we only do intrinsics for static/final methods or methods of final
// classes. We don't set kHasSingleImplementation for those methods.
DCHECK(IsStatic() || IsFinal() || GetDeclaringClass()->IsFinal()) <<
"Potential conflict with kAccSingleImplementation";
static const int kAccFlagsShift = CTZ(kAccIntrinsicBits);
DCHECK_LE(intrinsic, kAccIntrinsicBits >> kAccFlagsShift);
uint32_t intrinsic_bits = intrinsic << kAccFlagsShift;
uint32_t new_value = (GetAccessFlags() & ~kAccIntrinsicBits) | kAccIntrinsic | intrinsic_bits;
if (kIsDebugBuild) {
uint32_t java_flags = (GetAccessFlags() & kAccJavaFlagsMask);
bool is_constructor = IsConstructor();
bool is_synchronized = IsSynchronized();
bool skip_access_checks = SkipAccessChecks();
bool is_fast_native = IsFastNative();
bool is_critical_native = IsCriticalNative();
bool is_copied = IsCopied();
bool is_miranda = IsMiranda();
bool is_default = IsDefault();
bool is_default_conflict = IsDefaultConflicting();
bool is_compilable = IsCompilable();
bool must_count_locks = MustCountLocks();
// Recompute flags instead of getting them from the current access flags because
// access flags may have been changed to deduplicate warning messages (b/129063331).
uint32_t hiddenapi_flags = hiddenapi::CreateRuntimeFlags(this);
SetAccessFlags(new_value);
DCHECK_EQ(java_flags, (GetAccessFlags() & kAccJavaFlagsMask));
DCHECK_EQ(is_constructor, IsConstructor());
DCHECK_EQ(is_synchronized, IsSynchronized());
DCHECK_EQ(skip_access_checks, SkipAccessChecks());
DCHECK_EQ(is_fast_native, IsFastNative());
DCHECK_EQ(is_critical_native, IsCriticalNative());
DCHECK_EQ(is_copied, IsCopied());
DCHECK_EQ(is_miranda, IsMiranda());
DCHECK_EQ(is_default, IsDefault());
DCHECK_EQ(is_default_conflict, IsDefaultConflicting());
DCHECK_EQ(is_compilable, IsCompilable());
DCHECK_EQ(must_count_locks, MustCountLocks());
// Only DCHECK that we have preserved the hidden API access flags if the
// original method was not on the whitelist. This is because the core image
// does not have the access flags set (b/77733081).
if ((hiddenapi_flags & kAccHiddenapiBits) != kAccPublicApi) {
DCHECK_EQ(hiddenapi_flags, hiddenapi::GetRuntimeFlags(this)) << PrettyMethod();
}
} else {
SetAccessFlags(new_value);
}
}

void ArtMethod::SetNotIntrinsic() {
if (!IsIntrinsic()) {
return;
}

// Read the existing hiddenapi flags.
uint32_t hiddenapi_runtime_flags = hiddenapi::GetRuntimeFlags(this);

// Clear intrinsic-related access flags.
ClearAccessFlags(kAccIntrinsic | kAccIntrinsicBits);

// Re-apply hidden API access flags now that the method is not an intrinsic.
SetAccessFlags(GetAccessFlags() | hiddenapi_runtime_flags);
DCHECK_EQ(hiddenapi_runtime_flags, hiddenapi::GetRuntimeFlags(this));
}

void ArtMethod::CopyFrom(ArtMethod* src, PointerSize image_pointer_size) {
memcpy(reinterpret_cast<void*>(this), reinterpret_cast<const void*>(src),
Size(image_pointer_size));
declaring_class_ = GcRoot<mirror::Class>(const_cast<ArtMethod*>(src)->GetDeclaringClass());

// If the entry point of the method we are copying from is from JIT code, we just
// put the entry point of the new method to interpreter or GenericJNI. We could set
// the entry point to the JIT code, but this would require taking the JIT code cache
// lock to notify it, which we do not want at this level.
Runtime* runtime = Runtime::Current();
if (runtime->UseJitCompilation()) {
if (runtime->GetJit()->GetCodeCache()->ContainsPc(GetEntryPointFromQuickCompiledCode())) {
SetEntryPointFromQuickCompiledCodePtrSize(
src->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge(),
image_pointer_size);
}
}
// Clear the profiling info for the same reasons as the JIT code.
if (!src->IsNative()) {
SetProfilingInfoPtrSize(nullptr, image_pointer_size);
}
// Clear hotness to let the JIT properly decide when to compile this method.
hotness_count_ = 0;
}

bool ArtMethod::IsImagePointerSize(PointerSize pointer_size) {
// Hijack this function to get access to PtrSizedFieldsOffset.
//
// Ensure that PrtSizedFieldsOffset is correct. We rely here on usually having both 32-bit and
// 64-bit builds.
static_assert(std::is_standard_layout<ArtMethod>::value, "ArtMethod is not standard layout.");
static_assert(
(sizeof(void*) != 4) ||
(offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k32)),
"Unexpected 32-bit class layout.");
static_assert(
(sizeof(void*) != 8) ||
(offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k64)),
"Unexpected 64-bit class layout.");

Runtime* runtime = Runtime::Current();
if (runtime == nullptr) {
return true;
}
return runtime->GetClassLinker()->GetImagePointerSize() == pointer_size;
}

std::string ArtMethod::PrettyMethod(ArtMethod* m, bool with_signature) {
if (m == nullptr) {
return "null";
}
return m->PrettyMethod(with_signature);
}

std::string ArtMethod::PrettyMethod(bool with_signature) {
if (UNLIKELY(IsRuntimeMethod())) {
std::string result = GetDeclaringClassDescriptor();
result += '.';
result += GetName();
// Do not add "<no signature>" even if `with_signature` is true.
return result;
}
ArtMethod* m =
GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
std::string res(m->GetDexFile()->PrettyMethod(m->GetDexMethodIndex(), with_signature));
if (with_signature && m->IsObsolete()) {
return "<OBSOLETE> " + res;
} else {
return res;
}
}

std::string ArtMethod::JniShortName() {
return GetJniShortName(GetDeclaringClassDescriptor(), GetName());
}

std::string ArtMethod::JniLongName() {
std::string long_name;
long_name += JniShortName();
long_name += "__";

std::string signature(GetSignature().ToString());
signature.erase(0, 1);
signature.erase(signature.begin() + signature.find(')'), signature.end());

long_name += MangleForJni(signature);

return long_name;
}

const char* ArtMethod::GetRuntimeMethodName() {
Runtime* const runtime = Runtime::Current();
if (this == runtime->GetResolutionMethod()) {
return "<runtime internal resolution method>";
} else if (this == runtime->GetImtConflictMethod()) {
return "<runtime internal imt conflict method>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves)) {
return "<runtime internal callee-save all registers method>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly)) {
return "<runtime internal callee-save reference registers method>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs)) {
return "<runtime internal callee-save reference and argument registers method>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything)) {
return "<runtime internal save-every-register method>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit)) {
return "<runtime internal save-every-register method for clinit>";
} else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck)) {
return "<runtime internal save-every-register method for suspend check>";
} else {
return "<unknown runtime internal method>";
}
}

// AssertSharedHeld doesn't work in GetAccessFlags, so use a NO_THREAD_SAFETY_ANALYSIS helper.
// TODO: Figure out why ASSERT_SHARED_CAPABILITY doesn't work.
template <ReadBarrierOption kReadBarrierOption>
ALWAYS_INLINE static inline void DoGetAccessFlagsHelper(ArtMethod* method)
NO_THREAD_SAFETY_ANALYSIS {
CHECK(method->IsRuntimeMethod() ||
method->GetDeclaringClass<kReadBarrierOption>()->IsIdxLoaded() ||
method->GetDeclaringClass<kReadBarrierOption>()->IsErroneous());
}

} // namespace art