-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathti_redefine.cc
3101 lines (2897 loc) · 133 KB
/
ti_redefine.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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2016 The Android Open Source Project
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file implements interfaces from the file jvmti.h. This implementation
* is licensed under the same terms as the file jvmti.h. The
* copyright and license information for the file jvmti.h follows.
*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "ti_redefine.h"
#include <algorithm>
#include <atomic>
#include <iterator>
#include <limits>
#include <sstream>
#include <string_view>
#include <unordered_map>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include "alloc_manager.h"
#include "android-base/macros.h"
#include "android-base/thread_annotations.h"
#include "art_field-inl.h"
#include "art_field.h"
#include "art_jvmti.h"
#include "art_method-inl.h"
#include "art_method.h"
#include "base/array_ref.h"
#include "base/casts.h"
#include "base/enums.h"
#include "base/globals.h"
#include "base/iteration_range.h"
#include "base/length_prefixed_array.h"
#include "base/locks.h"
#include "base/stl_util.h"
#include "base/utils.h"
#include "class_linker-inl.h"
#include "class_linker.h"
#include "class_root-inl.h"
#include "class_status.h"
#include "debugger.h"
#include "dex/art_dex_file_loader.h"
#include "dex/class_accessor-inl.h"
#include "dex/class_accessor.h"
#include "dex/dex_file.h"
#include "dex/dex_file_loader.h"
#include "dex/dex_file_types.h"
#include "dex/primitive.h"
#include "dex/signature-inl.h"
#include "dex/signature.h"
#include "events-inl.h"
#include "events.h"
#include "gc/allocation_listener.h"
#include "gc/heap.h"
#include "gc/heap-inl.h"
#include "gc/heap-visit-objects-inl.h"
#include "handle.h"
#include "handle_scope.h"
#include "instrumentation.h"
#include "intern_table.h"
#include "jit/jit.h"
#include "jit/jit_code_cache.h"
#include "jni/jni_env_ext-inl.h"
#include "jni/jni_id_manager.h"
#include "jvmti.h"
#include "jvmti_allocator.h"
#include "linear_alloc.h"
#include "mirror/array-alloc-inl.h"
#include "mirror/array.h"
#include "mirror/class-alloc-inl.h"
#include "mirror/class-inl.h"
#include "mirror/class-refvisitor-inl.h"
#include "mirror/class.h"
#include "mirror/class_ext-inl.h"
#include "mirror/dex_cache-inl.h"
#include "mirror/dex_cache.h"
#include "mirror/executable-inl.h"
#include "mirror/field-inl.h"
#include "mirror/field.h"
#include "mirror/method.h"
#include "mirror/method_handle_impl-inl.h"
#include "mirror/object.h"
#include "mirror/object_array-alloc-inl.h"
#include "mirror/object_array-inl.h"
#include "mirror/object_array.h"
#include "mirror/string.h"
#include "mirror/var_handle.h"
#include "nativehelper/scoped_local_ref.h"
#include "non_debuggable_classes.h"
#include "obj_ptr.h"
#include "object_lock.h"
#include "reflective_value_visitor.h"
#include "runtime.h"
#include "runtime_globals.h"
#include "scoped_thread_state_change.h"
#include "stack.h"
#include "thread.h"
#include "thread_list.h"
#include "ti_breakpoint.h"
#include "ti_class_definition.h"
#include "ti_class_loader.h"
#include "ti_heap.h"
#include "ti_logging.h"
#include "ti_thread.h"
#include "transform.h"
#include "verifier/class_verifier.h"
#include "verifier/verifier_enums.h"
#include "well_known_classes.h"
#include "write_barrier.h"
namespace openjdkjvmti {
// Debug check to force us to directly check we saw all methods and fields exactly once directly.
// Normally we don't need to do this since if any are missing the count will be different
constexpr bool kCheckAllMethodsSeenOnce = art::kIsDebugBuild;
using android::base::StringPrintf;
// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
class ObsoleteMap {
public:
art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original) const
REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
auto method_pair = id_map_.find(original);
if (method_pair != id_map_.end()) {
art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
method_pair->second, art::kRuntimePointerSize);
DCHECK(res != nullptr);
return res;
} else {
return nullptr;
}
}
void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
DCHECK(original != nullptr);
DCHECK(obsolete != nullptr);
int32_t slot = next_free_slot_++;
DCHECK_LT(slot, obsolete_methods_->GetLength());
DCHECK(nullptr ==
obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
obsolete_dex_caches_->Set(slot, original_dex_cache_);
id_map_.insert({original, slot});
}
ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
art::ObjPtr<art::mirror::DexCache> original_dex_cache)
: next_free_slot_(0),
obsolete_methods_(obsolete_methods),
obsolete_dex_caches_(obsolete_dex_caches),
original_dex_cache_(original_dex_cache) {
// Figure out where the first unused slot in the obsolete_methods_ array is.
while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
next_free_slot_, art::kRuntimePointerSize) != nullptr) {
DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
next_free_slot_++;
}
// Check that the same slot in obsolete_dex_caches_ is free.
DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
}
struct ObsoleteMethodPair {
art::ArtMethod* old_method;
art::ArtMethod* obsolete_method;
};
class ObsoleteMapIter {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = ObsoleteMethodPair;
using difference_type = ptrdiff_t;
using pointer = void; // Unsupported.
using reference = void; // Unsupported.
ObsoleteMethodPair operator*() const
REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
art::ArtMethod* obsolete = map_->obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
iter_->second, art::kRuntimePointerSize);
DCHECK(obsolete != nullptr);
return { iter_->first, obsolete };
}
bool operator==(ObsoleteMapIter other) const {
return map_ == other.map_ && iter_ == other.iter_;
}
bool operator!=(ObsoleteMapIter other) const {
return !(*this == other);
}
ObsoleteMapIter operator++(int) {
ObsoleteMapIter retval = *this;
++(*this);
return retval;
}
ObsoleteMapIter operator++() {
++iter_;
return *this;
}
private:
ObsoleteMapIter(const ObsoleteMap* map,
std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter)
: map_(map), iter_(iter) {}
const ObsoleteMap* map_;
std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter_;
friend class ObsoleteMap;
};
ObsoleteMapIter end() const {
return ObsoleteMapIter(this, id_map_.cend());
}
ObsoleteMapIter begin() const {
return ObsoleteMapIter(this, id_map_.cbegin());
}
private:
int32_t next_free_slot_;
std::unordered_map<art::ArtMethod*, int32_t> id_map_;
// Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
// when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
};
// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
// some basic soundness checks that the obsolete method is valid.
class ObsoleteMethodStackVisitor : public art::StackVisitor {
protected:
ObsoleteMethodStackVisitor(
art::Thread* thread,
art::LinearAlloc* allocator,
const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
ObsoleteMap* obsolete_maps)
: StackVisitor(thread,
/*context=*/nullptr,
StackVisitor::StackWalkKind::kIncludeInlinedFrames),
allocator_(allocator),
obsoleted_methods_(obsoleted_methods),
obsolete_maps_(obsolete_maps) { }
~ObsoleteMethodStackVisitor() override {}
public:
// Returns true if we successfully installed obsolete methods on this thread, filling
// obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
// The stack is cleaned up when we fail.
static void UpdateObsoleteFrames(
art::Thread* thread,
art::LinearAlloc* allocator,
const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
ObsoleteMap* obsolete_maps)
REQUIRES(art::Locks::mutator_lock_) {
ObsoleteMethodStackVisitor visitor(thread,
allocator,
obsoleted_methods,
obsolete_maps);
visitor.WalkStack();
}
bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
art::ArtMethod* old_method = GetMethod();
if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
// We cannot ensure that the right dex file is used in inlined frames so we don't support
// redefining them.
DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
<< old_method->PrettyMethod() << " is inlined into "
<< GetOuterMethod()->PrettyMethod();
art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
if (new_obsolete_method == nullptr) {
// Create a new Obsolete Method and put it in the list.
art::Runtime* runtime = art::Runtime::Current();
art::ClassLinker* cl = runtime->GetClassLinker();
auto ptr_size = cl->GetImagePointerSize();
const size_t method_size = art::ArtMethod::Size(ptr_size);
auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
<< old_method->PrettyMethod() << "'";
new_obsolete_method = new (method_storage) art::ArtMethod();
new_obsolete_method->CopyFrom(old_method, ptr_size);
DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
new_obsolete_method->SetIsObsolete();
new_obsolete_method->SetDontCompile();
cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
}
DCHECK(new_obsolete_method != nullptr);
SetMethod(new_obsolete_method);
}
return true;
}
private:
// The linear allocator we should use to make new methods.
art::LinearAlloc* allocator_;
// The set of all methods which could be obsoleted.
const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
// A map from the original to the newly allocated obsolete method for frames on this thread. The
// values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
// the redefined classes ClassExt as it is filled.
ObsoleteMap* obsolete_maps_;
};
template <RedefinitionType kType>
jvmtiError
Redefiner::IsModifiableClassGeneric(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
if (env == nullptr) {
return ERR(INVALID_ENVIRONMENT);
}
art::Thread* self = art::Thread::Current();
art::ScopedObjectAccess soa(self);
art::StackHandleScope<1> hs(self);
art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
if (obj.IsNull() || !obj->IsClass()) {
return ERR(INVALID_CLASS);
}
art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
std::string err_unused;
*is_redefinable =
Redefiner::GetClassRedefinitionError<kType>(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
? JNI_TRUE
: JNI_FALSE;
return OK;
}
jvmtiError
Redefiner::IsStructurallyModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
return Redefiner::IsModifiableClassGeneric<RedefinitionType::kStructural>(
env, klass, is_redefinable);
}
jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
return Redefiner::IsModifiableClassGeneric<RedefinitionType::kNormal>(env, klass, is_redefinable);
}
template <RedefinitionType kType>
jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/ std::string* error_msg) {
art::Thread* self = art::Thread::Current();
art::ScopedObjectAccess soa(self);
art::StackHandleScope<1> hs(self);
art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
if (obj.IsNull() || !obj->IsClass()) {
return ERR(INVALID_CLASS);
}
art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
return Redefiner::GetClassRedefinitionError<kType>(h_klass, error_msg);
}
template <RedefinitionType kType>
jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
/*out*/ std::string* error_msg) {
art::Thread* self = art::Thread::Current();
if (!klass->IsResolved()) {
// It's only a problem to try to retransform/redefine a unprepared class if it's happening on
// the same thread as the class-linking process. If it's on another thread we will be able to
// wait for the preparation to finish and continue from there.
if (klass->GetLockOwnerThreadId() == self->GetThreadId()) {
*error_msg = "Modification of class " + klass->PrettyClass() +
" from within the classes ClassLoad callback is not supported to prevent deadlocks." +
" Please use ClassFileLoadHook directly instead.";
return ERR(INTERNAL);
} else {
LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
<< "it could cause arbitrary length waits as the class is being resolved.";
}
}
if (klass->IsPrimitive()) {
*error_msg = "Modification of primitive classes is not supported";
return ERR(UNMODIFIABLE_CLASS);
} else if (klass->IsInterface()) {
*error_msg = "Modification of Interface classes is currently not supported";
return ERR(UNMODIFIABLE_CLASS);
} else if (klass->IsStringClass()) {
*error_msg = "Modification of String class is not supported";
return ERR(UNMODIFIABLE_CLASS);
} else if (klass->IsArrayClass()) {
*error_msg = "Modification of Array classes is not supported";
return ERR(UNMODIFIABLE_CLASS);
} else if (klass->IsProxyClass()) {
*error_msg = "Modification of proxy classes is not supported";
return ERR(UNMODIFIABLE_CLASS);
}
for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
if (klass.Get() == self->DecodeJObject(c)->AsClass()) {
*error_msg = "Class might have stack frames that cannot be made obsolete";
return ERR(UNMODIFIABLE_CLASS);
}
}
if (kType == RedefinitionType::kStructural) {
// Class initialization interacts really badly with structural redefinition since we need to
// make the old class obsolete. We currently just blanket don't allow it.
// TODO It might be nice to allow this at some point.
if (klass->IsInitializing() &&
!klass->IsInitialized() &&
klass->GetClinitThreadId() == self->GetTid()) {
// We are in the class-init running on this thread.
*error_msg = "Modification of class " + klass->PrettyClass() + " during class" +
" initialization is not allowed.";
return ERR(INTERNAL);
}
if (!art::Runtime::Current()->GetClassLinker()->EnsureInitialized(
self, klass, /*can_init_fields=*/true, /*can_init_parents=*/true)) {
self->AssertPendingException();
*error_msg = "Class " + klass->PrettyClass() + " failed initialization. Structural" +
" redefinition of erroneous classes is not allowed. Failure was: " +
self->GetException()->Dump();
self->ClearException();
return ERR(INVALID_CLASS);
}
if (klass->IsMirrored()) {
std::string pc(klass->PrettyClass());
*error_msg = StringPrintf("Class %s is a mirror class and cannot be structurally redefined.",
pc.c_str());
return ERR(UNMODIFIABLE_CLASS);
}
// Check Thread specifically since it's not a root but too many things reach into it with Unsafe
// too allow structural redefinition.
if (klass->IsAssignableFrom(
self->DecodeJObject(art::WellKnownClasses::java_lang_Thread)->AsClass())) {
*error_msg =
"java.lang.Thread has fields accessed using sun.misc.unsafe directly. It is not "
"safe to structurally redefine it.";
return ERR(UNMODIFIABLE_CLASS);
}
auto has_pointer_marker =
[](art::ObjPtr<art::mirror::Class> k) REQUIRES_SHARED(art::Locks::mutator_lock_) {
// Check for fields/methods which were returned before moving to index jni id type.
// TODO We might want to rework how this is done. Once full redefinition is implemented we
// will need to check any subtypes too.
art::ObjPtr<art::mirror::ClassExt> ext(k->GetExtData());
if (!ext.IsNull()) {
if (ext->HasInstanceFieldPointerIdMarker() || ext->HasMethodPointerIdMarker() ||
ext->HasStaticFieldPointerIdMarker()) {
return true;
}
}
return false;
};
if (has_pointer_marker(klass.Get())) {
*error_msg =
StringPrintf("%s has active pointer jni-ids and cannot be redefined structurally",
klass->PrettyClass().c_str());
return ERR(UNMODIFIABLE_CLASS);
}
jvmtiError res = OK;
art::ClassFuncVisitor cfv(
[&](art::ObjPtr<art::mirror::Class> k) REQUIRES_SHARED(art::Locks::mutator_lock_) {
// if there is any class 'K' that is a subtype (i.e. extends) klass and has pointer-jni-ids
// we cannot structurally redefine the class 'k' since we would structurally redefine the
// subtype.
if (k->IsLoaded() && klass->IsAssignableFrom(k) && has_pointer_marker(k)) {
*error_msg = StringPrintf(
"%s has active pointer jni-ids from subtype %s and cannot be redefined structurally",
klass->PrettyClass().c_str(),
k->PrettyClass().c_str());
res = ERR(UNMODIFIABLE_CLASS);
return false;
}
return true;
});
art::Runtime::Current()->GetClassLinker()->VisitClasses(&cfv);
return res;
}
return OK;
}
template jvmtiError Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(
art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
template jvmtiError Redefiner::GetClassRedefinitionError<RedefinitionType::kStructural>(
art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
// Moves dex data to an anonymous, read-only mmap'd region.
art::MemMap Redefiner::MoveDataToMemMap(const std::string& original_location,
art::ArrayRef<const unsigned char> data,
std::string* error_msg) {
art::MemMap map = art::MemMap::MapAnonymous(
StringPrintf("%s-transformed", original_location.c_str()).c_str(),
data.size(),
PROT_READ|PROT_WRITE,
/*low_4gb=*/ false,
error_msg);
if (LIKELY(map.IsValid())) {
memcpy(map.Begin(), data.data(), data.size());
// Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
// programs from corrupting it.
map.Protect(PROT_READ);
}
return map;
}
Redefiner::ClassRedefinition::ClassRedefinition(
Redefiner* driver,
jclass klass,
const art::DexFile* redefined_dex_file,
const char* class_sig,
art::ArrayRef<const unsigned char> orig_dex_file) :
driver_(driver),
klass_(klass),
dex_file_(redefined_dex_file),
class_sig_(class_sig),
original_dex_file_(orig_dex_file) {
lock_acquired_ = GetMirrorClass()->MonitorTryEnter(driver_->self_) != nullptr;
}
Redefiner::ClassRedefinition::~ClassRedefinition() {
if (driver_ != nullptr && lock_acquired_) {
GetMirrorClass()->MonitorExit(driver_->self_);
}
}
template<RedefinitionType kType>
jvmtiError Redefiner::RedefineClassesGeneric(jvmtiEnv* jenv,
jint class_count,
const jvmtiClassDefinition* definitions) {
art::Runtime* runtime = art::Runtime::Current();
art::Thread* self = art::Thread::Current();
ArtJvmTiEnv* env = ArtJvmTiEnv::AsArtJvmTiEnv(jenv);
if (env == nullptr) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE env was null!";
return ERR(INVALID_ENVIRONMENT);
} else if (class_count < 0) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE class_count was less then 0";
return ERR(ILLEGAL_ARGUMENT);
} else if (class_count == 0) {
// We don't actually need to do anything. Just return OK.
return OK;
} else if (definitions == nullptr) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE null definitions!";
return ERR(NULL_POINTER);
}
std::string error_msg;
std::vector<ArtClassDefinition> def_vector;
def_vector.reserve(class_count);
for (jint i = 0; i < class_count; i++) {
jvmtiError res = Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(
definitions[i].klass, &error_msg);
if (res != OK) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
return res;
}
ArtClassDefinition def;
res = def.Init(self, definitions[i]);
if (res != OK) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE bad definition " << i;
return res;
}
def_vector.push_back(std::move(def));
}
// Call all the transformation events.
Transformer::RetransformClassesDirect<kType>(self, &def_vector);
if (kType == RedefinitionType::kStructural) {
Transformer::RetransformClassesDirect<RedefinitionType::kNormal>(self, &def_vector);
}
jvmtiError res = RedefineClassesDirect(env, runtime, self, def_vector, kType, &error_msg);
if (res != OK) {
JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
}
return res;
}
jvmtiError Redefiner::StructurallyRedefineClasses(jvmtiEnv* jenv,
jint class_count,
const jvmtiClassDefinition* definitions) {
ArtJvmTiEnv* art_env = ArtJvmTiEnv::AsArtJvmTiEnv(jenv);
if (art_env == nullptr) {
return ERR(INVALID_ENVIRONMENT);
} else if (art_env->capabilities.can_redefine_classes != 1) {
return ERR(MUST_POSSESS_CAPABILITY);
}
return RedefineClassesGeneric<RedefinitionType::kStructural>(jenv, class_count, definitions);
}
jvmtiError Redefiner::RedefineClasses(jvmtiEnv* jenv,
jint class_count,
const jvmtiClassDefinition* definitions) {
return RedefineClassesGeneric<RedefinitionType::kNormal>(jenv, class_count, definitions);
}
jvmtiError Redefiner::StructurallyRedefineClassDirect(jvmtiEnv* env,
jclass klass,
const unsigned char* data,
jint data_size) {
if (env == nullptr) {
return ERR(INVALID_ENVIRONMENT);
} else if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_redefine_classes != 1) {
JVMTI_LOG(INFO, env) << "Does not have can_redefine_classes cap!";
return ERR(MUST_POSSESS_CAPABILITY);
}
std::vector<ArtClassDefinition> acds;
ArtClassDefinition acd;
jvmtiError err = acd.Init(
art::Thread::Current(),
jvmtiClassDefinition{ .klass = klass, .class_byte_count = data_size, .class_bytes = data });
if (err != OK) {
return err;
}
acds.push_back(std::move(acd));
std::string err_msg;
err = RedefineClassesDirect(ArtJvmTiEnv::AsArtJvmTiEnv(env),
art::Runtime::Current(),
art::Thread::Current(),
acds,
RedefinitionType::kStructural,
&err_msg);
if (err != OK) {
JVMTI_LOG(WARNING, env) << "Failed structural redefinition: " << err_msg;
}
return err;
}
jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
art::Runtime* runtime,
art::Thread* self,
const std::vector<ArtClassDefinition>& definitions,
RedefinitionType type,
std::string* error_msg) {
DCHECK(env != nullptr);
if (definitions.size() == 0) {
// We don't actually need to do anything. Just return OK.
return OK;
}
// We need to fiddle with the verification class flags. To do this we need to make sure there are
// no concurrent redefinitions of the same class at the same time. For simplicity and because
// this is not expected to be a common occurrence we will just wrap the whole thing in a TOP-level
// lock.
// Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
// are going to redefine.
// TODO We should prevent user-code suspensions to make sure this isn't held for too long.
art::jit::ScopedJitSuspend suspend_jit;
// Get shared mutator lock so we can lock all the classes.
art::ScopedObjectAccess soa(self);
Redefiner r(env, runtime, self, type, error_msg);
for (const ArtClassDefinition& def : definitions) {
// Only try to transform classes that have been modified.
if (def.IsModified()) {
jvmtiError res = r.AddRedefinition(env, def);
if (res != OK) {
return res;
}
}
}
return r.Run();
}
jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
std::string original_dex_location;
jvmtiError ret = OK;
if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
*error_msg_ = "Unable to get original dex file location!";
return ret;
}
char* generic_ptr_unused = nullptr;
char* signature_ptr = nullptr;
if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
*error_msg_ = "Unable to get class signature!";
return ret;
}
JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
std::ostringstream os;
if (!map.IsValid()) {
os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
<< "in dex file " << original_dex_location << " because: " << *error_msg_;
*error_msg_ = os.str();
return ERR(OUT_OF_MEMORY);
}
if (map.Size() < sizeof(art::DexFile::Header)) {
*error_msg_ = "Could not read dex file header because dex_data was too short";
return ERR(INVALID_CLASS_FORMAT);
}
std::string name = map.GetName();
uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
const art::ArtDexFileLoader dex_file_loader;
std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(name,
checksum,
std::move(map),
/*verify=*/true,
/*verify_checksum=*/true,
error_msg_));
if (dex_file.get() == nullptr) {
os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
*error_msg_ = os.str();
return ERR(INVALID_CLASS_FORMAT);
}
redefinitions_.push_back(
Redefiner::ClassRedefinition(this,
def.GetClass(),
dex_file.release(),
signature_ptr,
def.GetNewOriginalDexFile()));
return OK;
}
art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::GetMirrorClass() {
return driver_->self_->DecodeJObject(klass_)->AsClass();
}
art::ObjPtr<art::mirror::ClassLoader> Redefiner::ClassRedefinition::GetClassLoader() {
return GetMirrorClass()->GetClassLoader();
}
art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
art::Handle<art::mirror::ClassLoader> loader) {
art::StackHandleScope<2> hs(driver_->self_);
art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
art::ObjPtr<art::mirror::DexCache>::DownCast(
art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
if (cache.IsNull()) {
driver_->self_->AssertPendingOOMException();
return nullptr;
}
art::Handle<art::mirror::String> location(hs.NewHandle(
cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
if (location.IsNull()) {
driver_->self_->AssertPendingOOMException();
return nullptr;
}
art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
cache->SetLocation(location.Get());
cache->Initialize(dex_file_.get(), loader.Get());
return cache.Get();
}
void Redefiner::RecordFailure(jvmtiError result,
const std::string& class_sig,
const std::string& error_msg) {
*error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
class_sig.c_str(),
error_msg.c_str());
result_ = result;
}
art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
// If we have been specifically given a new set of bytes use that
if (original_dex_file_.size() != 0) {
return art::mirror::ByteArray::AllocateAndFill(
driver_->self_,
reinterpret_cast<const signed char*>(original_dex_file_.data()),
original_dex_file_.size()).Ptr();
}
// See if we already have one set.
art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
if (!ext.IsNull()) {
art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
if (!old_original_dex_file.IsNull()) {
// We do. Use it.
return old_original_dex_file.Ptr();
}
}
// return the current dex_cache which has the dex file in it.
art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
// TODO Handle this or make it so it cannot happen.
if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
<< "on this class might fail if no transformations are applied to it!";
}
return current_dex_cache.Ptr();
}
struct CallbackCtx {
ObsoleteMap* obsolete_map;
art::LinearAlloc* allocator;
std::unordered_set<art::ArtMethod*> obsolete_methods;
explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
: obsolete_map(map), allocator(alloc) {}
};
void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
data->allocator,
data->obsolete_methods,
data->obsolete_map);
}
// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
// updated so they will be run.
// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
art::ObjPtr<art::mirror::Class> art_klass) {
DCHECK(!IsStructuralRedefinition());
art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
CHECK(ext->GetObsoleteMethods() != nullptr);
art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
// This holds pointers to the obsolete methods map fields which are updated as needed.
ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
// Add all the declared methods to the map
for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
if (m.IsIntrinsic()) {
LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
<< "unexpected use of the original definition of " << m.PrettyMethod() << "in "
<< "methods that have already been compiled.";
}
// It is possible to simply filter out some methods where they cannot really become obsolete,
// such as native methods and keep their original (possibly optimized) implementations. We don't
// do this, however, since we would need to mark these functions (still in the classes
// declared_methods array) as obsolete so we will find the correct dex file to get meta-data
// from (for example about stack-frame size). Furthermore we would be unable to get some useful
// error checking from the interpreter which ensure we don't try to start executing obsolete
// methods.
ctx.obsolete_methods.insert(&m);
}
{
art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
art::ThreadList* list = art::Runtime::Current()->GetThreadList();
list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
// After we've done walking all threads' stacks and updating method pointers on them,
// update JIT data structures (used by the stack walk above) to point to the new methods.
art::jit::Jit* jit = art::Runtime::Current()->GetJit();
if (jit != nullptr) {
for (const ObsoleteMap::ObsoleteMethodPair& it : *ctx.obsolete_map) {
// Notify the JIT we are making this obsolete method. It will update the jit's internal
// structures to keep track of the new obsolete method.
jit->GetCodeCache()->MoveObsoleteMethod(it.old_method, it.obsolete_method);
}
}
}
}
namespace {
template <typename T> struct SignatureType {};
template <> struct SignatureType<art::ArtField> { using type = std::string_view; };
template <> struct SignatureType<art::ArtMethod> { using type = art::Signature; };
template <typename T> struct NameAndSignature {
public:
using SigType = typename SignatureType<T>::type;
NameAndSignature(const art::DexFile* dex_file, uint32_t id);
NameAndSignature(const std::string_view& name, const SigType& sig) : name_(name), sig_(sig) {}
bool operator==(const NameAndSignature<T>& o) {
return name_ == o.name_ && sig_ == o.sig_;
}
std::ostream& dump(std::ostream& os) const {
return os << "'" << name_ << "' (sig: " << sig_ << ")";
}
std::string ToString() const {
std::ostringstream os;
os << *this;
return os.str();
}
std::string_view name_;
SigType sig_;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const NameAndSignature<T>& nas) {
return nas.dump(os);
}
using FieldNameAndSignature = NameAndSignature<art::ArtField>;
template <>
FieldNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
: FieldNameAndSignature(dex_file->GetFieldName(dex_file->GetFieldId(id)),
dex_file->GetFieldTypeDescriptor(dex_file->GetFieldId(id))) {}
using MethodNameAndSignature = NameAndSignature<art::ArtMethod>;
template <>
MethodNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
: MethodNameAndSignature(dex_file->GetMethodName(dex_file->GetMethodId(id)),
dex_file->GetMethodSignature(dex_file->GetMethodId(id))) {}
} // namespace
void Redefiner::ClassRedefinition::RecordNewMethodAdded() {
DCHECK(driver_->IsStructuralRedefinition());
added_methods_ = true;
}
void Redefiner::ClassRedefinition::RecordNewFieldAdded() {
DCHECK(driver_->IsStructuralRedefinition());
added_fields_ = true;
}
bool Redefiner::ClassRedefinition::CheckMethods() {
art::StackHandleScope<1> hs(driver_->self_);
art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
// Make sure we have the same number of methods (or the same or greater if we're structural).
art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
uint32_t num_new_method = accessor.NumMethods();
uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
const bool is_structural = driver_->IsStructuralRedefinition();
if (!is_structural && num_new_method != num_old_method) {
bool bigger = num_new_method > num_old_method;
RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
: ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
StringPrintf("Total number of declared methods changed from %d to %d",
num_old_method,
num_new_method));
return false;
}
// Skip all of the fields. We should have already checked this.
// Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
// files have the same number of methods, which means there must be an equal amount of additions
// and removals. We should have already checked the fields.
const art::DexFile& old_dex_file = h_klass->GetDexFile();
art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
// We need this to check for methods going missing in structural cases.
std::vector<bool> seen_old_methods(
(kCheckAllMethodsSeenOnce || is_structural) ? old_accessor.NumMethods() : 0, false);
const auto old_methods = old_accessor.GetMethods();
for (const art::ClassAccessor::Method& new_method : accessor.GetMethods()) {
// Get the data on the method we are searching for
MethodNameAndSignature new_method_id(dex_file_.get(), new_method.GetIndex());
const auto old_iter =
std::find_if(old_methods.cbegin(), old_methods.cend(), [&](const auto& current_old_method) {
MethodNameAndSignature old_method_id(&old_dex_file, current_old_method.GetIndex());
return old_method_id == new_method_id;
});
if (!new_method.IsStaticOrDirect()) {
RecordHasVirtualMembers();
}
if (old_iter == old_methods.cend()) {
if (is_structural) {
RecordNewMethodAdded();
} else {
RecordFailure(
ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
StringPrintf("Unknown virtual method %s was added!", new_method_id.ToString().c_str()));
return false;
}
} else if (new_method.GetAccessFlags() != old_iter->GetAccessFlags()) {
RecordFailure(
ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
StringPrintf("method %s had different access flags", new_method_id.ToString().c_str()));
return false;
} else if (kCheckAllMethodsSeenOnce || is_structural) {
// We only need this if we are structural.
size_t off = std::distance(old_methods.cbegin(), old_iter);
DCHECK(!seen_old_methods[off])
<< "field at " << off << "("
<< MethodNameAndSignature(&old_dex_file, old_iter->GetIndex()) << ") already seen?";
seen_old_methods[off] = true;
}
}
if ((kCheckAllMethodsSeenOnce || is_structural) &&
!std::all_of(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return x; })) {
DCHECK(is_structural) << "We should have hit an earlier failure before getting here!";
auto first_fail =
std::find_if(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return !x; });
auto off = std::distance(seen_old_methods.cbegin(), first_fail);
auto fail = old_methods.cbegin();
std::advance(fail, off);
RecordFailure(
ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),