1 /*
  2  * Copyright (c) 2017, 2021, Red Hat, Inc. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "gc/shared/tlab_globals.hpp"
 27 #include "gc/shenandoah/shenandoahAsserts.hpp"
 28 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
 29 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
 30 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 31 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
 32 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
 33 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
 34 #include "gc/shenandoah/shenandoahUtils.hpp"
 35 #include "gc/shenandoah/shenandoahVerifier.hpp"
 36 #include "memory/allocation.hpp"
 37 #include "memory/iterator.inline.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/compressedOops.inline.hpp"
 40 #include "runtime/atomic.hpp"
 41 #include "runtime/orderAccess.hpp"
 42 #include "runtime/threads.hpp"
 43 #include "utilities/align.hpp"
 44 
 45 // Avoid name collision on verify_oop (defined in macroAssembler_arm.hpp)
 46 #ifdef verify_oop
 47 #undef verify_oop
 48 #endif
 49 
 50 static bool is_instance_ref_klass(Klass* k) {
 51   return k->is_instance_klass() && InstanceKlass::cast(k)->reference_type() != REF_NONE;
 52 }
 53 
 54 class ShenandoahVerifyOopClosure : public BasicOopIterateClosure {
 55 private:
 56   const char* _phase;
 57   ShenandoahVerifier::VerifyOptions _options;
 58   ShenandoahVerifierStack* _stack;
 59   ShenandoahHeap* _heap;
 60   MarkBitMap* _map;
 61   ShenandoahLivenessData* _ld;
 62   void* _interior_loc;
 63   oop _loc;
 64   ReferenceIterationMode _ref_mode;
 65 
 66 public:
 67   ShenandoahVerifyOopClosure(ShenandoahVerifierStack* stack, MarkBitMap* map, ShenandoahLivenessData* ld,
 68                              const char* phase, ShenandoahVerifier::VerifyOptions options) :
 69     _phase(phase),
 70     _options(options),
 71     _stack(stack),
 72     _heap(ShenandoahHeap::heap()),
 73     _map(map),
 74     _ld(ld),
 75     _interior_loc(nullptr),
 76     _loc(nullptr) {
 77     if (options._verify_marked == ShenandoahVerifier::_verify_marked_complete_except_references ||
 78         options._verify_marked == ShenandoahVerifier::_verify_marked_disable) {
 79       // Unknown status for Reference.referent field. Do not touch it, it might be dead.
 80       // Normally, barriers would prevent us from seeing the dead referents, but verifier
 81       // runs with barriers disabled.
 82       _ref_mode = DO_FIELDS_EXCEPT_REFERENT;
 83     } else {
 84       // Otherwise do all fields.
 85       _ref_mode = DO_FIELDS;
 86     }
 87   }
 88 
 89   ReferenceIterationMode reference_iteration_mode() override {
 90     return _ref_mode;
 91   }
 92 
 93 private:
 94   void check(ShenandoahAsserts::SafeLevel level, oop obj, bool test, const char* label) {
 95     if (!test) {
 96       ShenandoahAsserts::print_failure(level, obj, _interior_loc, _loc, _phase, label, __FILE__, __LINE__);
 97     }
 98   }
 99 
100   template <class T>
101   void do_oop_work(T* p) {
102     T o = RawAccess<>::oop_load(p);
103     if (!CompressedOops::is_null(o)) {
104       oop obj = CompressedOops::decode_not_null(o);
105       if (is_instance_ref_klass(obj->klass())) {
106         obj = ShenandoahForwarding::get_forwardee(obj);
107       }
108       // Single threaded verification can use faster non-atomic stack and bitmap
109       // methods.
110       //
111       // For performance reasons, only fully verify non-marked field values.
112       // We are here when the host object for *p is already marked.
113 
114       if (_map->par_mark(obj)) {
115         verify_oop_at(p, obj);
116         _stack->push(ShenandoahVerifierTask(obj));
117       }
118     }
119   }
120 
121   void verify_oop(oop obj) {
122     // Perform consistency checks with gradually decreasing safety level. This guarantees
123     // that failure report would not try to touch something that was not yet verified to be
124     // safe to process.
125 
126     check(ShenandoahAsserts::_safe_unknown, obj, _heap->is_in_reserved(obj),
127               "oop must be in heap bounds");
128     check(ShenandoahAsserts::_safe_unknown, obj, is_object_aligned(obj),
129               "oop must be aligned");
130 
131     ShenandoahHeapRegion *obj_reg = _heap->heap_region_containing(obj);
132     Klass* obj_klass = obj->klass_or_null();
133 
134     // Verify that obj is not in dead space:
135     {
136       // Do this before touching obj->size()
137       check(ShenandoahAsserts::_safe_unknown, obj, obj_klass != nullptr,
138              "Object klass pointer should not be null");
139       check(ShenandoahAsserts::_safe_unknown, obj, Metaspace::contains(obj_klass),
140              "Object klass pointer must go to metaspace");
141 
142       HeapWord *obj_addr = cast_from_oop<HeapWord*>(obj);
143       check(ShenandoahAsserts::_safe_unknown, obj, obj_addr < obj_reg->top(),
144              "Object start should be within the region");
145 
146       if (!obj_reg->is_humongous()) {
147         check(ShenandoahAsserts::_safe_unknown, obj, (obj_addr + obj->size()) <= obj_reg->top(),
148                "Object end should be within the region");
149       } else {
150         size_t humongous_start = obj_reg->index();
151         size_t humongous_end = humongous_start + (obj->size() >> ShenandoahHeapRegion::region_size_words_shift());
152         for (size_t idx = humongous_start + 1; idx < humongous_end; idx++) {
153           check(ShenandoahAsserts::_safe_unknown, obj, _heap->get_region(idx)->is_humongous_continuation(),
154                  "Humongous object is in continuation that fits it");
155         }
156       }
157 
158       // ------------ obj is safe at this point --------------
159 
160       check(ShenandoahAsserts::_safe_oop, obj, obj_reg->is_active(),
161             "Object should be in active region");
162 
163       switch (_options._verify_liveness) {
164         case ShenandoahVerifier::_verify_liveness_disable:
165           // skip
166           break;
167         case ShenandoahVerifier::_verify_liveness_complete:
168           Atomic::add(&_ld[obj_reg->index()], (uint) obj->size(), memory_order_relaxed);
169           // fallthrough for fast failure for un-live regions:
170         case ShenandoahVerifier::_verify_liveness_conservative:
171           check(ShenandoahAsserts::_safe_oop, obj, obj_reg->has_live(),
172                    "Object must belong to region with live data");
173           break;
174         default:
175           assert(false, "Unhandled liveness verification");
176       }
177     }
178 
179     oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
180 
181     ShenandoahHeapRegion* fwd_reg = nullptr;
182 
183     if (obj != fwd) {
184       check(ShenandoahAsserts::_safe_oop, obj, _heap->is_in_reserved(fwd),
185              "Forwardee must be in heap bounds");
186       check(ShenandoahAsserts::_safe_oop, obj, !CompressedOops::is_null(fwd),
187              "Forwardee is set");
188       check(ShenandoahAsserts::_safe_oop, obj, is_object_aligned(fwd),
189              "Forwardee must be aligned");
190 
191       // Do this before touching fwd->size()
192       Klass* fwd_klass = fwd->klass_or_null();
193       check(ShenandoahAsserts::_safe_oop, obj, fwd_klass != nullptr,
194              "Forwardee klass pointer should not be null");
195       check(ShenandoahAsserts::_safe_oop, obj, Metaspace::contains(fwd_klass),
196              "Forwardee klass pointer must go to metaspace");
197       check(ShenandoahAsserts::_safe_oop, obj, obj_klass == fwd_klass,
198              "Forwardee klass pointer must go to metaspace");
199 
200       fwd_reg = _heap->heap_region_containing(fwd);
201 
202       check(ShenandoahAsserts::_safe_oop, obj, fwd_reg->is_active(),
203             "Forwardee should be in active region");
204 
205       // Verify that forwardee is not in the dead space:
206       check(ShenandoahAsserts::_safe_oop, obj, !fwd_reg->is_humongous(),
207              "Should have no humongous forwardees");
208 
209       HeapWord *fwd_addr = cast_from_oop<HeapWord *>(fwd);
210       check(ShenandoahAsserts::_safe_oop, obj, fwd_addr < fwd_reg->top(),
211              "Forwardee start should be within the region");
212       check(ShenandoahAsserts::_safe_oop, obj, (fwd_addr + fwd->size()) <= fwd_reg->top(),
213              "Forwardee end should be within the region");
214 
215       oop fwd2 = ShenandoahForwarding::get_forwardee_raw_unchecked(fwd);
216       check(ShenandoahAsserts::_safe_oop, obj, (fwd == fwd2),
217              "Double forwarding");
218     } else {
219       fwd_reg = obj_reg;
220     }
221 
222     // ------------ obj and fwd are safe at this point --------------
223 
224     switch (_options._verify_marked) {
225       case ShenandoahVerifier::_verify_marked_disable:
226         // skip
227         break;
228       case ShenandoahVerifier::_verify_marked_incomplete:
229         check(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked(obj),
230                "Must be marked in incomplete bitmap");
231         break;
232       case ShenandoahVerifier::_verify_marked_complete:
233         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
234                "Must be marked in complete bitmap");
235         break;
236       case ShenandoahVerifier::_verify_marked_complete_except_references:
237         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
238               "Must be marked in complete bitmap, except j.l.r.Reference referents");
239         break;
240       default:
241         assert(false, "Unhandled mark verification");
242     }
243 
244     switch (_options._verify_forwarded) {
245       case ShenandoahVerifier::_verify_forwarded_disable:
246         // skip
247         break;
248       case ShenandoahVerifier::_verify_forwarded_none: {
249         check(ShenandoahAsserts::_safe_all, obj, (obj == fwd),
250                "Should not be forwarded");
251         break;
252       }
253       case ShenandoahVerifier::_verify_forwarded_allow: {
254         if (obj != fwd) {
255           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
256                  "Forwardee should be in another region");
257         }
258         break;
259       }
260       default:
261         assert(false, "Unhandled forwarding verification");
262     }
263 
264     switch (_options._verify_cset) {
265       case ShenandoahVerifier::_verify_cset_disable:
266         // skip
267         break;
268       case ShenandoahVerifier::_verify_cset_none:
269         check(ShenandoahAsserts::_safe_all, obj, !_heap->in_collection_set(obj),
270                "Should not have references to collection set");
271         break;
272       case ShenandoahVerifier::_verify_cset_forwarded:
273         if (_heap->in_collection_set(obj)) {
274           check(ShenandoahAsserts::_safe_all, obj, (obj != fwd),
275                  "Object in collection set, should have forwardee");
276         }
277         break;
278       default:
279         assert(false, "Unhandled cset verification");
280     }
281 
282   }
283 
284 public:
285   /**
286    * Verify object with known interior reference.
287    * @param p interior reference where the object is referenced from; can be off-heap
288    * @param obj verified object
289    */
290   template <class T>
291   void verify_oop_at(T* p, oop obj) {
292     _interior_loc = p;
293     verify_oop(obj);
294     _interior_loc = nullptr;
295   }
296 
297   /**
298    * Verify object without known interior reference.
299    * Useful when picking up the object at known offset in heap,
300    * but without knowing what objects reference it.
301    * @param obj verified object
302    */
303   void verify_oop_standalone(oop obj) {
304     _interior_loc = nullptr;
305     verify_oop(obj);
306     _interior_loc = nullptr;
307   }
308 
309   /**
310    * Verify oop fields from this object.
311    * @param obj host object for verified fields
312    */
313   void verify_oops_from(oop obj) {
314     _loc = obj;
315     obj->oop_iterate(this);
316     _loc = nullptr;
317   }
318 
319   virtual void do_oop(oop* p) override { do_oop_work(p); }
320   virtual void do_oop(narrowOop* p) override { do_oop_work(p); }
321 };
322 
323 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
324 private:
325   size_t _used, _committed, _garbage;
326 public:
327   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
328 
329   void heap_region_do(ShenandoahHeapRegion* r) {
330     _used += r->used();
331     _garbage += r->garbage();
332     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
333   }
334 
335   size_t used() { return _used; }
336   size_t committed() { return _committed; }
337   size_t garbage() { return _garbage; }
338 };
339 
340 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
341 private:
342   ShenandoahHeap* _heap;
343   const char* _phase;
344   ShenandoahVerifier::VerifyRegions _regions;
345 public:
346   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
347     _heap(ShenandoahHeap::heap()),
348     _phase(phase),
349     _regions(regions) {};
350 
351   void print_failure(ShenandoahHeapRegion* r, const char* label) {
352     ResourceMark rm;
353 
354     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
355 
356     stringStream ss;
357     r->print_on(&ss);
358     msg.append("%s", ss.as_string());
359 
360     report_vm_error(__FILE__, __LINE__, msg.buffer());
361   }
362 
363   void verify(ShenandoahHeapRegion* r, bool test, const char* msg) {
364     if (!test) {
365       print_failure(r, msg);
366     }
367   }
368 
369   void heap_region_do(ShenandoahHeapRegion* r) {
370     switch (_regions) {
371       case ShenandoahVerifier::_verify_regions_disable:
372         break;
373       case ShenandoahVerifier::_verify_regions_notrash:
374         verify(r, !r->is_trash(),
375                "Should not have trash regions");
376         break;
377       case ShenandoahVerifier::_verify_regions_nocset:
378         verify(r, !r->is_cset(),
379                "Should not have cset regions");
380         break;
381       case ShenandoahVerifier::_verify_regions_notrash_nocset:
382         verify(r, !r->is_trash(),
383                "Should not have trash regions");
384         verify(r, !r->is_cset(),
385                "Should not have cset regions");
386         break;
387       default:
388         ShouldNotReachHere();
389     }
390 
391     verify(r, r->capacity() == ShenandoahHeapRegion::region_size_bytes(),
392            "Capacity should match region size");
393 
394     verify(r, r->bottom() <= r->top(),
395            "Region top should not be less than bottom");
396 
397     verify(r, r->bottom() <= _heap->marking_context()->top_at_mark_start(r),
398            "Region TAMS should not be less than bottom");
399 
400     verify(r, _heap->marking_context()->top_at_mark_start(r) <= r->top(),
401            "Complete TAMS should not be larger than top");
402 
403     verify(r, r->get_live_data_bytes() <= r->capacity(),
404            "Live data cannot be larger than capacity");
405 
406     verify(r, r->garbage() <= r->capacity(),
407            "Garbage cannot be larger than capacity");
408 
409     verify(r, r->used() <= r->capacity(),
410            "Used cannot be larger than capacity");
411 
412     verify(r, r->get_shared_allocs() <= r->capacity(),
413            "Shared alloc count should not be larger than capacity");
414 
415     verify(r, r->get_tlab_allocs() <= r->capacity(),
416            "TLAB alloc count should not be larger than capacity");
417 
418     verify(r, r->get_gclab_allocs() <= r->capacity(),
419            "GCLAB alloc count should not be larger than capacity");
420 
421     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
422            "Accurate accounting: shared + TLAB + GCLAB = used");
423 
424     verify(r, !r->is_empty() || !r->has_live(),
425            "Empty regions should not have live data");
426 
427     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
428            "Transitional: region flags and collection set agree");
429   }
430 };
431 
432 class ShenandoahVerifierReachableTask : public WorkerTask {
433 private:
434   const char* _label;
435   ShenandoahVerifier::VerifyOptions _options;
436   ShenandoahHeap* _heap;
437   ShenandoahLivenessData* _ld;
438   MarkBitMap* _bitmap;
439   volatile size_t _processed;
440 
441 public:
442   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,
443                                   ShenandoahLivenessData* ld,
444                                   const char* label,
445                                   ShenandoahVerifier::VerifyOptions options) :
446     WorkerTask("Shenandoah Verifier Reachable Objects"),
447     _label(label),
448     _options(options),
449     _heap(ShenandoahHeap::heap()),
450     _ld(ld),
451     _bitmap(bitmap),
452     _processed(0) {};
453 
454   size_t processed() {
455     return _processed;
456   }
457 
458   virtual void work(uint worker_id) {
459     ResourceMark rm;
460     ShenandoahVerifierStack stack;
461 
462     // On level 2, we need to only check the roots once.
463     // On level 3, we want to check the roots, and seed the local stack.
464     // It is a lesser evil to accept multiple root scans at level 3, because
465     // extended parallelism would buy us out.
466     if (((ShenandoahVerifyLevel == 2) && (worker_id == 0))
467         || (ShenandoahVerifyLevel >= 3)) {
468         ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
469                                       ShenandoahMessageBuffer("%s, Roots", _label),
470                                       _options);
471         if (_heap->unload_classes()) {
472           ShenandoahRootVerifier::strong_roots_do(&cl);
473         } else {
474           ShenandoahRootVerifier::roots_do(&cl);
475         }
476     }
477 
478     size_t processed = 0;
479 
480     if (ShenandoahVerifyLevel >= 3) {
481       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
482                                     ShenandoahMessageBuffer("%s, Reachable", _label),
483                                     _options);
484       while (!stack.is_empty()) {
485         processed++;
486         ShenandoahVerifierTask task = stack.pop();
487         cl.verify_oops_from(task.obj());
488       }
489     }
490 
491     Atomic::add(&_processed, processed, memory_order_relaxed);
492   }
493 };
494 
495 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
496 private:
497   const char* _label;
498   ShenandoahVerifier::VerifyOptions _options;
499   ShenandoahHeap *_heap;
500   MarkBitMap* _bitmap;
501   ShenandoahLivenessData* _ld;
502   volatile size_t _claimed;
503   volatile size_t _processed;
504 
505 public:
506   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
507                                      ShenandoahLivenessData* ld,
508                                      const char* label,
509                                      ShenandoahVerifier::VerifyOptions options) :
510           WorkerTask("Shenandoah Verifier Marked Objects"),
511           _label(label),
512           _options(options),
513           _heap(ShenandoahHeap::heap()),
514           _bitmap(bitmap),
515           _ld(ld),
516           _claimed(0),
517           _processed(0) {};
518 
519   size_t processed() {
520     return Atomic::load(&_processed);
521   }
522 
523   virtual void work(uint worker_id) {
524     ShenandoahVerifierStack stack;
525     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
526                                   ShenandoahMessageBuffer("%s, Marked", _label),
527                                   _options);
528 
529     while (true) {
530       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
531       if (v < _heap->num_regions()) {
532         ShenandoahHeapRegion* r = _heap->get_region(v);
533         if (!r->is_humongous() && !r->is_trash()) {
534           work_regular(r, stack, cl);
535         } else if (r->is_humongous_start()) {
536           work_humongous(r, stack, cl);
537         }
538       } else {
539         break;
540       }
541     }
542   }
543 
544   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
545     size_t processed = 0;
546     HeapWord* obj = r->bottom();
547     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
548       verify_and_follow(obj, stack, cl, &processed);
549     }
550     Atomic::add(&_processed, processed, memory_order_relaxed);
551   }
552 
553   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
554     size_t processed = 0;
555     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
556     HeapWord* tams = ctx->top_at_mark_start(r);
557 
558     // Bitmaps, before TAMS
559     if (tams > r->bottom()) {
560       HeapWord* start = r->bottom();
561       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
562 
563       while (addr < tams) {
564         verify_and_follow(addr, stack, cl, &processed);
565         addr += 1;
566         if (addr < tams) {
567           addr = ctx->get_next_marked_addr(addr, tams);
568         }
569       }
570     }
571 
572     // Size-based, after TAMS
573     {
574       HeapWord* limit = r->top();
575       HeapWord* addr = tams;
576 
577       while (addr < limit) {
578         verify_and_follow(addr, stack, cl, &processed);
579         addr += cast_to_oop(addr)->size();
580       }
581     }
582 
583     Atomic::add(&_processed, processed, memory_order_relaxed);
584   }
585 
586   void verify_and_follow(HeapWord *addr, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl, size_t *processed) {
587     if (!_bitmap->par_mark(addr)) return;
588 
589     // Verify the object itself:
590     oop obj = cast_to_oop(addr);
591     cl.verify_oop_standalone(obj);
592 
593     // Verify everything reachable from that object too, hopefully realizing
594     // everything was already marked, and never touching further:
595     if (!is_instance_ref_klass(obj->klass())) {
596       cl.verify_oops_from(obj);
597       (*processed)++;
598     }
599     while (!stack.is_empty()) {
600       ShenandoahVerifierTask task = stack.pop();
601       cl.verify_oops_from(task.obj());
602       (*processed)++;
603     }
604   }
605 };
606 
607 class VerifyThreadGCState : public ThreadClosure {
608 private:
609   const char* const _label;
610          char const _expected;
611 
612 public:
613   VerifyThreadGCState(const char* label, char expected) : _label(label), _expected(expected) {}
614   void do_thread(Thread* t) {
615     char actual = ShenandoahThreadLocalData::gc_state(t);
616     if (actual != _expected) {
617       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
618     }
619   }
620 };
621 
622 void ShenandoahVerifier::verify_at_safepoint(const char *label,
623                                              VerifyForwarded forwarded, VerifyMarked marked,
624                                              VerifyCollectionSet cset,
625                                              VerifyLiveness liveness, VerifyRegions regions,
626                                              VerifyGCState gcstate) {
627   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
628   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
629 
630   ShenandoahHeap::heap()->propagate_gc_state_to_java_threads();
631 
632   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
633   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
634 
635   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
636 
637   // GC state checks
638   {
639     char expected = -1;
640     bool enabled;
641     switch (gcstate) {
642       case _verify_gcstate_disable:
643         enabled = false;
644         break;
645       case _verify_gcstate_forwarded:
646         enabled = true;
647         expected = ShenandoahHeap::HAS_FORWARDED;
648         break;
649       case _verify_gcstate_evacuation:
650         enabled = true;
651         expected = ShenandoahHeap::HAS_FORWARDED | ShenandoahHeap::EVACUATION;
652         if (!_heap->is_stw_gc_in_progress()) {
653           // Only concurrent GC sets this.
654           expected |= ShenandoahHeap::WEAK_ROOTS;
655         }
656         break;
657       case _verify_gcstate_stable:
658         enabled = true;
659         expected = ShenandoahHeap::STABLE;
660         break;
661       case _verify_gcstate_stable_weakroots:
662         enabled = true;
663         expected = ShenandoahHeap::STABLE;
664         if (!_heap->is_stw_gc_in_progress()) {
665           // Only concurrent GC sets this.
666           expected |= ShenandoahHeap::WEAK_ROOTS;
667         }
668         break;
669       default:
670         enabled = false;
671         assert(false, "Unhandled gc-state verification");
672     }
673 
674     if (enabled) {
675       char actual = _heap->gc_state();
676       if (actual != expected) {
677         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
678       }
679 
680       VerifyThreadGCState vtgcs(label, expected);
681       Threads::java_threads_do(&vtgcs);
682     }
683   }
684 
685   // Deactivate barriers temporarily: Verifier wants plain heap accesses
686   ShenandoahGCStateResetter resetter;
687 
688   // Heap size checks
689   {
690     ShenandoahHeapLocker lock(_heap->lock());
691 
692     ShenandoahCalculateRegionStatsClosure cl;
693     _heap->heap_region_iterate(&cl);
694     size_t heap_used = _heap->used();
695     guarantee(cl.used() == heap_used,
696               "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
697               label,
698               byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
699               byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used()));
700 
701     size_t heap_committed = _heap->committed();
702     guarantee(cl.committed() == heap_committed,
703               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
704               label,
705               byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
706               byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed()));
707   }
708 
709   // Internal heap region checks
710   if (ShenandoahVerifyLevel >= 1) {
711     ShenandoahVerifyHeapRegionClosure cl(label, regions);
712     _heap->heap_region_iterate(&cl);
713   }
714 
715   OrderAccess::fence();
716 
717   if (UseTLAB) {
718     _heap->labs_make_parsable();
719   }
720 
721   // Allocate temporary bitmap for storing marking wavefront:
722   _verification_bit_map->clear();
723 
724   // Allocate temporary array for storing liveness data
725   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
726   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
727 
728   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
729 
730   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
731   // This verifies what application can see, since it only cares about reachable objects.
732   size_t count_reachable = 0;
733   if (ShenandoahVerifyLevel >= 2) {
734     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, label, options);
735     _heap->workers()->run_task(&task);
736     count_reachable = task.processed();
737   }
738 
739   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
740   // not the application, can see during the region scans. There is no reason to process the objects
741   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
742   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
743   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
744   // version
745 
746   size_t count_marked = 0;
747   if (ShenandoahVerifyLevel >= 4 && (marked == _verify_marked_complete || marked == _verify_marked_complete_except_references)) {
748     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
749     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
750     _heap->workers()->run_task(&task);
751     count_marked = task.processed();
752   } else {
753     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
754   }
755 
756   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
757   // marked objects.
758 
759   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
760     for (size_t i = 0; i < _heap->num_regions(); i++) {
761       ShenandoahHeapRegion* r = _heap->get_region(i);
762 
763       juint verf_live = 0;
764       if (r->is_humongous()) {
765         // For humongous objects, test if start region is marked live, and if so,
766         // all humongous regions in that chain have live data equal to their "used".
767         juint start_live = Atomic::load(&ld[r->humongous_start_region()->index()]);
768         if (start_live > 0) {
769           verf_live = (juint)(r->used() / HeapWordSize);
770         }
771       } else {
772         verf_live = Atomic::load(&ld[r->index()]);
773       }
774 
775       size_t reg_live = r->get_live_data_words();
776       if (reg_live != verf_live) {
777         stringStream ss;
778         r->print_on(&ss);
779         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
780               label, reg_live, verf_live, ss.freeze());
781       }
782     }
783   }
784 
785   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
786                label, ShenandoahVerifyLevel, count_reachable, count_marked);
787 
788   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
789 }
790 
791 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
792   verify_at_safepoint(
793           "Generic Verification",
794           _verify_forwarded_allow,     // conservatively allow forwarded
795           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
796           _verify_cset_disable,        // cset may be inconsistent
797           _verify_liveness_disable,    // no reliable liveness data
798           _verify_regions_disable,     // no reliable region data
799           _verify_gcstate_disable      // no data about gcstate
800   );
801 }
802 
803 void ShenandoahVerifier::verify_before_concmark() {
804     verify_at_safepoint(
805           "Before Mark",
806           _verify_forwarded_none,      // UR should have fixed up
807           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
808           _verify_cset_none,           // UR should have fixed this
809           _verify_liveness_disable,    // no reliable liveness data
810           _verify_regions_notrash,     // no trash regions
811           _verify_gcstate_stable       // there are no forwarded objects
812   );
813 }
814 
815 void ShenandoahVerifier::verify_after_concmark() {
816   verify_at_safepoint(
817           "After Mark",
818           _verify_forwarded_none,      // no forwarded references
819           _verify_marked_complete_except_references, // bitmaps as precise as we can get, except dangling j.l.r.Refs
820           _verify_cset_none,           // no references to cset anymore
821           _verify_liveness_complete,   // liveness data must be complete here
822           _verify_regions_disable,     // trash regions not yet recycled
823           _verify_gcstate_stable_weakroots  // heap is still stable, weakroots are in progress
824   );
825 }
826 
827 void ShenandoahVerifier::verify_before_evacuation() {
828   verify_at_safepoint(
829           "Before Evacuation",
830           _verify_forwarded_none,                    // no forwarded references
831           _verify_marked_complete_except_references, // walk over marked objects too
832           _verify_cset_disable,                      // non-forwarded references to cset expected
833           _verify_liveness_complete,                 // liveness data must be complete here
834           _verify_regions_disable,                   // trash regions not yet recycled
835           _verify_gcstate_stable_weakroots           // heap is still stable, weakroots are in progress
836   );
837 }
838 
839 void ShenandoahVerifier::verify_during_evacuation() {
840   verify_at_safepoint(
841           "During Evacuation",
842           _verify_forwarded_allow,    // some forwarded references are allowed
843           _verify_marked_disable,     // walk only roots
844           _verify_cset_disable,       // some cset references are not forwarded yet
845           _verify_liveness_disable,   // liveness data might be already stale after pre-evacs
846           _verify_regions_disable,    // trash regions not yet recycled
847           _verify_gcstate_evacuation  // evacuation is in progress
848   );
849 }
850 
851 void ShenandoahVerifier::verify_after_evacuation() {
852   verify_at_safepoint(
853           "After Evacuation",
854           _verify_forwarded_allow,     // objects are still forwarded
855           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
856           _verify_cset_forwarded,      // all cset refs are fully forwarded
857           _verify_liveness_disable,    // no reliable liveness data anymore
858           _verify_regions_notrash,     // trash regions have been recycled already
859           _verify_gcstate_forwarded    // evacuation produced some forwarded objects
860   );
861 }
862 
863 void ShenandoahVerifier::verify_before_updaterefs() {
864   verify_at_safepoint(
865           "Before Updating References",
866           _verify_forwarded_allow,     // forwarded references allowed
867           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
868           _verify_cset_forwarded,      // all cset refs are fully forwarded
869           _verify_liveness_disable,    // no reliable liveness data anymore
870           _verify_regions_notrash,     // trash regions have been recycled already
871           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects
872   );
873 }
874 
875 void ShenandoahVerifier::verify_after_updaterefs() {
876   verify_at_safepoint(
877           "After Updating References",
878           _verify_forwarded_none,      // no forwarded references
879           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
880           _verify_cset_none,           // no cset references, all updated
881           _verify_liveness_disable,    // no reliable liveness data anymore
882           _verify_regions_nocset,      // no cset regions, trash regions have appeared
883           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
884   );
885 }
886 
887 void ShenandoahVerifier::verify_after_degenerated() {
888   verify_at_safepoint(
889           "After Degenerated GC",
890           _verify_forwarded_none,      // all objects are non-forwarded
891           _verify_marked_complete,     // all objects are marked in complete bitmap
892           _verify_cset_none,           // no cset references
893           _verify_liveness_disable,    // no reliable liveness data anymore
894           _verify_regions_notrash_nocset, // no trash, no cset
895           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
896   );
897 }
898 
899 void ShenandoahVerifier::verify_before_fullgc() {
900   verify_at_safepoint(
901           "Before Full GC",
902           _verify_forwarded_allow,     // can have forwarded objects
903           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
904           _verify_cset_disable,        // cset might be foobared
905           _verify_liveness_disable,    // no reliable liveness data anymore
906           _verify_regions_disable,     // no reliable region data here
907           _verify_gcstate_disable      // no reliable gcstate data
908   );
909 }
910 
911 void ShenandoahVerifier::verify_after_fullgc() {
912   verify_at_safepoint(
913           "After Full GC",
914           _verify_forwarded_none,      // all objects are non-forwarded
915           _verify_marked_complete,     // all objects are marked in complete bitmap
916           _verify_cset_none,           // no cset references
917           _verify_liveness_disable,    // no reliable liveness data anymore
918           _verify_regions_notrash_nocset, // no trash, no cset
919           _verify_gcstate_stable        // full gc cleaned up everything
920   );
921 }
922 
923 class ShenandoahVerifyNoForwared : public OopClosure {
924 private:
925   template <class T>
926   void do_oop_work(T* p) {
927     T o = RawAccess<>::oop_load(p);
928     if (!CompressedOops::is_null(o)) {
929       oop obj = CompressedOops::decode_not_null(o);
930       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
931       if (obj != fwd) {
932         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
933                                          "Verify Roots", "Should not be forwarded", __FILE__, __LINE__);
934       }
935     }
936   }
937 
938 public:
939   void do_oop(narrowOop* p) { do_oop_work(p); }
940   void do_oop(oop* p)       { do_oop_work(p); }
941 };
942 
943 class ShenandoahVerifyInToSpaceClosure : public OopClosure {
944 private:
945   template <class T>
946   void do_oop_work(T* p) {
947     T o = RawAccess<>::oop_load(p);
948     if (!CompressedOops::is_null(o)) {
949       oop obj = CompressedOops::decode_not_null(o);
950       ShenandoahHeap* heap = ShenandoahHeap::heap();
951 
952       if (!heap->marking_context()->is_marked(obj)) {
953         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
954                 "Verify Roots In To-Space", "Should be marked", __FILE__, __LINE__);
955       }
956 
957       if (heap->in_collection_set(obj)) {
958         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
959                 "Verify Roots In To-Space", "Should not be in collection set", __FILE__, __LINE__);
960       }
961 
962       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
963       if (obj != fwd) {
964         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
965                 "Verify Roots In To-Space", "Should not be forwarded", __FILE__, __LINE__);
966       }
967     }
968   }
969 
970 public:
971   void do_oop(narrowOop* p) { do_oop_work(p); }
972   void do_oop(oop* p)       { do_oop_work(p); }
973 };
974 
975 void ShenandoahVerifier::verify_roots_in_to_space() {
976   ShenandoahVerifyInToSpaceClosure cl;
977   ShenandoahRootVerifier::roots_do(&cl);
978 }
979 
980 void ShenandoahVerifier::verify_roots_no_forwarded() {
981   ShenandoahVerifyNoForwared cl;
982   ShenandoahRootVerifier::roots_do(&cl);
983 }