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     // Do additional checks for special objects: their fields can hold metadata as well.
223     // We want to check class loading/unloading did not corrupt them.
224 
225     if (obj_klass == vmClasses::Class_klass()) {
226       Metadata* klass = obj->metadata_field(java_lang_Class::klass_offset());
227       check(ShenandoahAsserts::_safe_oop, obj,
228             klass == nullptr || Metaspace::contains(klass),
229             "Instance class mirror should point to Metaspace");
230 
231       Metadata* array_klass = obj->metadata_field(java_lang_Class::array_klass_offset());
232       check(ShenandoahAsserts::_safe_oop, obj,
233             array_klass == nullptr || Metaspace::contains(array_klass),
234             "Array class mirror should point to Metaspace");
235     }
236 
237     // ------------ obj and fwd are safe at this point --------------
238 
239     switch (_options._verify_marked) {
240       case ShenandoahVerifier::_verify_marked_disable:
241         // skip
242         break;
243       case ShenandoahVerifier::_verify_marked_incomplete:
244         check(ShenandoahAsserts::_safe_all, obj, _heap->marking_context()->is_marked(obj),
245                "Must be marked in incomplete bitmap");
246         break;
247       case ShenandoahVerifier::_verify_marked_complete:
248         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
249                "Must be marked in complete bitmap");
250         break;
251       case ShenandoahVerifier::_verify_marked_complete_except_references:
252         check(ShenandoahAsserts::_safe_all, obj, _heap->complete_marking_context()->is_marked(obj),
253               "Must be marked in complete bitmap, except j.l.r.Reference referents");
254         break;
255       default:
256         assert(false, "Unhandled mark verification");
257     }
258 
259     switch (_options._verify_forwarded) {
260       case ShenandoahVerifier::_verify_forwarded_disable:
261         // skip
262         break;
263       case ShenandoahVerifier::_verify_forwarded_none: {
264         check(ShenandoahAsserts::_safe_all, obj, (obj == fwd),
265                "Should not be forwarded");
266         break;
267       }
268       case ShenandoahVerifier::_verify_forwarded_allow: {
269         if (obj != fwd) {
270           check(ShenandoahAsserts::_safe_all, obj, obj_reg != fwd_reg,
271                  "Forwardee should be in another region");
272         }
273         break;
274       }
275       default:
276         assert(false, "Unhandled forwarding verification");
277     }
278 
279     switch (_options._verify_cset) {
280       case ShenandoahVerifier::_verify_cset_disable:
281         // skip
282         break;
283       case ShenandoahVerifier::_verify_cset_none:
284         check(ShenandoahAsserts::_safe_all, obj, !_heap->in_collection_set(obj),
285                "Should not have references to collection set");
286         break;
287       case ShenandoahVerifier::_verify_cset_forwarded:
288         if (_heap->in_collection_set(obj)) {
289           check(ShenandoahAsserts::_safe_all, obj, (obj != fwd),
290                  "Object in collection set, should have forwardee");
291         }
292         break;
293       default:
294         assert(false, "Unhandled cset verification");
295     }
296 
297   }
298 
299 public:
300   /**
301    * Verify object with known interior reference.
302    * @param p interior reference where the object is referenced from; can be off-heap
303    * @param obj verified object
304    */
305   template <class T>
306   void verify_oop_at(T* p, oop obj) {
307     _interior_loc = p;
308     verify_oop(obj);
309     _interior_loc = nullptr;
310   }
311 
312   /**
313    * Verify object without known interior reference.
314    * Useful when picking up the object at known offset in heap,
315    * but without knowing what objects reference it.
316    * @param obj verified object
317    */
318   void verify_oop_standalone(oop obj) {
319     _interior_loc = nullptr;
320     verify_oop(obj);
321     _interior_loc = nullptr;
322   }
323 
324   /**
325    * Verify oop fields from this object.
326    * @param obj host object for verified fields
327    */
328   void verify_oops_from(oop obj) {
329     _loc = obj;
330     obj->oop_iterate(this);
331     _loc = nullptr;
332   }
333 
334   virtual void do_oop(oop* p) override { do_oop_work(p); }
335   virtual void do_oop(narrowOop* p) override { do_oop_work(p); }
336 };
337 
338 class ShenandoahCalculateRegionStatsClosure : public ShenandoahHeapRegionClosure {
339 private:
340   size_t _used, _committed, _garbage;
341 public:
342   ShenandoahCalculateRegionStatsClosure() : _used(0), _committed(0), _garbage(0) {};
343 
344   void heap_region_do(ShenandoahHeapRegion* r) {
345     _used += r->used();
346     _garbage += r->garbage();
347     _committed += r->is_committed() ? ShenandoahHeapRegion::region_size_bytes() : 0;
348   }
349 
350   size_t used() { return _used; }
351   size_t committed() { return _committed; }
352   size_t garbage() { return _garbage; }
353 };
354 
355 class ShenandoahVerifyHeapRegionClosure : public ShenandoahHeapRegionClosure {
356 private:
357   ShenandoahHeap* _heap;
358   const char* _phase;
359   ShenandoahVerifier::VerifyRegions _regions;
360 public:
361   ShenandoahVerifyHeapRegionClosure(const char* phase, ShenandoahVerifier::VerifyRegions regions) :
362     _heap(ShenandoahHeap::heap()),
363     _phase(phase),
364     _regions(regions) {};
365 
366   void print_failure(ShenandoahHeapRegion* r, const char* label) {
367     ResourceMark rm;
368 
369     ShenandoahMessageBuffer msg("Shenandoah verification failed; %s: %s\n\n", _phase, label);
370 
371     stringStream ss;
372     r->print_on(&ss);
373     msg.append("%s", ss.as_string());
374 
375     report_vm_error(__FILE__, __LINE__, msg.buffer());
376   }
377 
378   void verify(ShenandoahHeapRegion* r, bool test, const char* msg) {
379     if (!test) {
380       print_failure(r, msg);
381     }
382   }
383 
384   void heap_region_do(ShenandoahHeapRegion* r) {
385     switch (_regions) {
386       case ShenandoahVerifier::_verify_regions_disable:
387         break;
388       case ShenandoahVerifier::_verify_regions_notrash:
389         verify(r, !r->is_trash(),
390                "Should not have trash regions");
391         break;
392       case ShenandoahVerifier::_verify_regions_nocset:
393         verify(r, !r->is_cset(),
394                "Should not have cset regions");
395         break;
396       case ShenandoahVerifier::_verify_regions_notrash_nocset:
397         verify(r, !r->is_trash(),
398                "Should not have trash regions");
399         verify(r, !r->is_cset(),
400                "Should not have cset regions");
401         break;
402       default:
403         ShouldNotReachHere();
404     }
405 
406     verify(r, r->capacity() == ShenandoahHeapRegion::region_size_bytes(),
407            "Capacity should match region size");
408 
409     verify(r, r->bottom() <= r->top(),
410            "Region top should not be less than bottom");
411 
412     verify(r, r->bottom() <= _heap->marking_context()->top_at_mark_start(r),
413            "Region TAMS should not be less than bottom");
414 
415     verify(r, _heap->marking_context()->top_at_mark_start(r) <= r->top(),
416            "Complete TAMS should not be larger than top");
417 
418     verify(r, r->get_live_data_bytes() <= r->capacity(),
419            "Live data cannot be larger than capacity");
420 
421     verify(r, r->garbage() <= r->capacity(),
422            "Garbage cannot be larger than capacity");
423 
424     verify(r, r->used() <= r->capacity(),
425            "Used cannot be larger than capacity");
426 
427     verify(r, r->get_shared_allocs() <= r->capacity(),
428            "Shared alloc count should not be larger than capacity");
429 
430     verify(r, r->get_tlab_allocs() <= r->capacity(),
431            "TLAB alloc count should not be larger than capacity");
432 
433     verify(r, r->get_gclab_allocs() <= r->capacity(),
434            "GCLAB alloc count should not be larger than capacity");
435 
436     verify(r, r->get_shared_allocs() + r->get_tlab_allocs() + r->get_gclab_allocs() == r->used(),
437            "Accurate accounting: shared + TLAB + GCLAB = used");
438 
439     verify(r, !r->is_empty() || !r->has_live(),
440            "Empty regions should not have live data");
441 
442     verify(r, r->is_cset() == _heap->collection_set()->is_in(r),
443            "Transitional: region flags and collection set agree");
444   }
445 };
446 
447 class ShenandoahVerifierReachableTask : public WorkerTask {
448 private:
449   const char* _label;
450   ShenandoahVerifier::VerifyOptions _options;
451   ShenandoahHeap* _heap;
452   ShenandoahLivenessData* _ld;
453   MarkBitMap* _bitmap;
454   volatile size_t _processed;
455 
456 public:
457   ShenandoahVerifierReachableTask(MarkBitMap* bitmap,
458                                   ShenandoahLivenessData* ld,
459                                   const char* label,
460                                   ShenandoahVerifier::VerifyOptions options) :
461     WorkerTask("Shenandoah Verifier Reachable Objects"),
462     _label(label),
463     _options(options),
464     _heap(ShenandoahHeap::heap()),
465     _ld(ld),
466     _bitmap(bitmap),
467     _processed(0) {};
468 
469   size_t processed() {
470     return _processed;
471   }
472 
473   virtual void work(uint worker_id) {
474     ResourceMark rm;
475     ShenandoahVerifierStack stack;
476 
477     // On level 2, we need to only check the roots once.
478     // On level 3, we want to check the roots, and seed the local stack.
479     // It is a lesser evil to accept multiple root scans at level 3, because
480     // extended parallelism would buy us out.
481     if (((ShenandoahVerifyLevel == 2) && (worker_id == 0))
482         || (ShenandoahVerifyLevel >= 3)) {
483         ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
484                                       ShenandoahMessageBuffer("%s, Roots", _label),
485                                       _options);
486         if (_heap->unload_classes()) {
487           ShenandoahRootVerifier::strong_roots_do(&cl);
488         } else {
489           ShenandoahRootVerifier::roots_do(&cl);
490         }
491     }
492 
493     size_t processed = 0;
494 
495     if (ShenandoahVerifyLevel >= 3) {
496       ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
497                                     ShenandoahMessageBuffer("%s, Reachable", _label),
498                                     _options);
499       while (!stack.is_empty()) {
500         processed++;
501         ShenandoahVerifierTask task = stack.pop();
502         cl.verify_oops_from(task.obj());
503       }
504     }
505 
506     Atomic::add(&_processed, processed, memory_order_relaxed);
507   }
508 };
509 
510 class ShenandoahVerifierMarkedRegionTask : public WorkerTask {
511 private:
512   const char* _label;
513   ShenandoahVerifier::VerifyOptions _options;
514   ShenandoahHeap *_heap;
515   MarkBitMap* _bitmap;
516   ShenandoahLivenessData* _ld;
517   volatile size_t _claimed;
518   volatile size_t _processed;
519 
520 public:
521   ShenandoahVerifierMarkedRegionTask(MarkBitMap* bitmap,
522                                      ShenandoahLivenessData* ld,
523                                      const char* label,
524                                      ShenandoahVerifier::VerifyOptions options) :
525           WorkerTask("Shenandoah Verifier Marked Objects"),
526           _label(label),
527           _options(options),
528           _heap(ShenandoahHeap::heap()),
529           _bitmap(bitmap),
530           _ld(ld),
531           _claimed(0),
532           _processed(0) {};
533 
534   size_t processed() {
535     return Atomic::load(&_processed);
536   }
537 
538   virtual void work(uint worker_id) {
539     ShenandoahVerifierStack stack;
540     ShenandoahVerifyOopClosure cl(&stack, _bitmap, _ld,
541                                   ShenandoahMessageBuffer("%s, Marked", _label),
542                                   _options);
543 
544     while (true) {
545       size_t v = Atomic::fetch_then_add(&_claimed, 1u, memory_order_relaxed);
546       if (v < _heap->num_regions()) {
547         ShenandoahHeapRegion* r = _heap->get_region(v);
548         if (!r->is_humongous() && !r->is_trash()) {
549           work_regular(r, stack, cl);
550         } else if (r->is_humongous_start()) {
551           work_humongous(r, stack, cl);
552         }
553       } else {
554         break;
555       }
556     }
557   }
558 
559   virtual void work_humongous(ShenandoahHeapRegion *r, ShenandoahVerifierStack& stack, ShenandoahVerifyOopClosure& cl) {
560     size_t processed = 0;
561     HeapWord* obj = r->bottom();
562     if (_heap->complete_marking_context()->is_marked(cast_to_oop(obj))) {
563       verify_and_follow(obj, stack, cl, &processed);
564     }
565     Atomic::add(&_processed, processed, memory_order_relaxed);
566   }
567 
568   virtual void work_regular(ShenandoahHeapRegion *r, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl) {
569     size_t processed = 0;
570     ShenandoahMarkingContext* ctx = _heap->complete_marking_context();
571     HeapWord* tams = ctx->top_at_mark_start(r);
572 
573     // Bitmaps, before TAMS
574     if (tams > r->bottom()) {
575       HeapWord* start = r->bottom();
576       HeapWord* addr = ctx->get_next_marked_addr(start, tams);
577 
578       while (addr < tams) {
579         verify_and_follow(addr, stack, cl, &processed);
580         addr += 1;
581         if (addr < tams) {
582           addr = ctx->get_next_marked_addr(addr, tams);
583         }
584       }
585     }
586 
587     // Size-based, after TAMS
588     {
589       HeapWord* limit = r->top();
590       HeapWord* addr = tams;
591 
592       while (addr < limit) {
593         verify_and_follow(addr, stack, cl, &processed);
594         addr += cast_to_oop(addr)->size();
595       }
596     }
597 
598     Atomic::add(&_processed, processed, memory_order_relaxed);
599   }
600 
601   void verify_and_follow(HeapWord *addr, ShenandoahVerifierStack &stack, ShenandoahVerifyOopClosure &cl, size_t *processed) {
602     if (!_bitmap->par_mark(addr)) return;
603 
604     // Verify the object itself:
605     oop obj = cast_to_oop(addr);
606     cl.verify_oop_standalone(obj);
607 
608     // Verify everything reachable from that object too, hopefully realizing
609     // everything was already marked, and never touching further:
610     if (!is_instance_ref_klass(obj->klass())) {
611       cl.verify_oops_from(obj);
612       (*processed)++;
613     }
614     while (!stack.is_empty()) {
615       ShenandoahVerifierTask task = stack.pop();
616       cl.verify_oops_from(task.obj());
617       (*processed)++;
618     }
619   }
620 };
621 
622 class VerifyThreadGCState : public ThreadClosure {
623 private:
624   const char* const _label;
625          char const _expected;
626 
627 public:
628   VerifyThreadGCState(const char* label, char expected) : _label(label), _expected(expected) {}
629   void do_thread(Thread* t) {
630     char actual = ShenandoahThreadLocalData::gc_state(t);
631     if (actual != _expected) {
632       fatal("%s: Thread %s: expected gc-state %d, actual %d", _label, t->name(), _expected, actual);
633     }
634   }
635 };
636 
637 void ShenandoahVerifier::verify_at_safepoint(const char *label,
638                                              VerifyForwarded forwarded, VerifyMarked marked,
639                                              VerifyCollectionSet cset,
640                                              VerifyLiveness liveness, VerifyRegions regions,
641                                              VerifyGCState gcstate) {
642   guarantee(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "only when nothing else happens");
643   guarantee(ShenandoahVerify, "only when enabled, and bitmap is initialized in ShenandoahHeap::initialize");
644 
645   ShenandoahHeap::heap()->propagate_gc_state_to_java_threads();
646 
647   // Avoid side-effect of changing workers' active thread count, but bypass concurrent/parallel protocol check
648   ShenandoahPushWorkerScope verify_worker_scope(_heap->workers(), _heap->max_workers(), false /*bypass check*/);
649 
650   log_info(gc,start)("Verify %s, Level " INTX_FORMAT, label, ShenandoahVerifyLevel);
651 
652   // GC state checks
653   {
654     char expected = -1;
655     bool enabled;
656     switch (gcstate) {
657       case _verify_gcstate_disable:
658         enabled = false;
659         break;
660       case _verify_gcstate_forwarded:
661         enabled = true;
662         expected = ShenandoahHeap::HAS_FORWARDED;
663         break;
664       case _verify_gcstate_stable:
665         enabled = true;
666         expected = ShenandoahHeap::STABLE;
667         break;
668       case _verify_gcstate_stable_weakroots:
669         enabled = true;
670         expected = ShenandoahHeap::STABLE;
671         if (!_heap->is_stw_gc_in_progress()) {
672           // Only concurrent GC sets this.
673           expected |= ShenandoahHeap::WEAK_ROOTS;
674         }
675         break;
676       default:
677         enabled = false;
678         assert(false, "Unhandled gc-state verification");
679     }
680 
681     if (enabled) {
682       char actual = _heap->gc_state();
683       if (actual != expected) {
684         fatal("%s: Global gc-state: expected %d, actual %d", label, expected, actual);
685       }
686 
687       VerifyThreadGCState vtgcs(label, expected);
688       Threads::java_threads_do(&vtgcs);
689     }
690   }
691 
692   // Deactivate barriers temporarily: Verifier wants plain heap accesses
693   ShenandoahGCStateResetter resetter;
694 
695   // Heap size checks
696   {
697     ShenandoahHeapLocker lock(_heap->lock());
698 
699     ShenandoahCalculateRegionStatsClosure cl;
700     _heap->heap_region_iterate(&cl);
701     size_t heap_used = _heap->used();
702     guarantee(cl.used() == heap_used,
703               "%s: heap used size must be consistent: heap-used = " SIZE_FORMAT "%s, regions-used = " SIZE_FORMAT "%s",
704               label,
705               byte_size_in_proper_unit(heap_used), proper_unit_for_byte_size(heap_used),
706               byte_size_in_proper_unit(cl.used()), proper_unit_for_byte_size(cl.used()));
707 
708     size_t heap_committed = _heap->committed();
709     guarantee(cl.committed() == heap_committed,
710               "%s: heap committed size must be consistent: heap-committed = " SIZE_FORMAT "%s, regions-committed = " SIZE_FORMAT "%s",
711               label,
712               byte_size_in_proper_unit(heap_committed), proper_unit_for_byte_size(heap_committed),
713               byte_size_in_proper_unit(cl.committed()), proper_unit_for_byte_size(cl.committed()));
714   }
715 
716   // Internal heap region checks
717   if (ShenandoahVerifyLevel >= 1) {
718     ShenandoahVerifyHeapRegionClosure cl(label, regions);
719     _heap->heap_region_iterate(&cl);
720   }
721 
722   OrderAccess::fence();
723 
724   if (UseTLAB) {
725     _heap->labs_make_parsable();
726   }
727 
728   // Allocate temporary bitmap for storing marking wavefront:
729   _verification_bit_map->clear();
730 
731   // Allocate temporary array for storing liveness data
732   ShenandoahLivenessData* ld = NEW_C_HEAP_ARRAY(ShenandoahLivenessData, _heap->num_regions(), mtGC);
733   Copy::fill_to_bytes((void*)ld, _heap->num_regions()*sizeof(ShenandoahLivenessData), 0);
734 
735   const VerifyOptions& options = ShenandoahVerifier::VerifyOptions(forwarded, marked, cset, liveness, regions, gcstate);
736 
737   // Steps 1-2. Scan root set to get initial reachable set. Finish walking the reachable heap.
738   // This verifies what application can see, since it only cares about reachable objects.
739   size_t count_reachable = 0;
740   if (ShenandoahVerifyLevel >= 2) {
741     ShenandoahVerifierReachableTask task(_verification_bit_map, ld, label, options);
742     _heap->workers()->run_task(&task);
743     count_reachable = task.processed();
744   }
745 
746   // Step 3. Walk marked objects. Marked objects might be unreachable. This verifies what collector,
747   // not the application, can see during the region scans. There is no reason to process the objects
748   // that were already verified, e.g. those marked in verification bitmap. There is interaction with TAMS:
749   // before TAMS, we verify the bitmaps, if available; after TAMS, we walk until the top(). It mimics
750   // what marked_object_iterate is doing, without calling into that optimized (and possibly incorrect)
751   // version
752 
753   size_t count_marked = 0;
754   if (ShenandoahVerifyLevel >= 4 && (marked == _verify_marked_complete || marked == _verify_marked_complete_except_references)) {
755     guarantee(_heap->marking_context()->is_complete(), "Marking context should be complete");
756     ShenandoahVerifierMarkedRegionTask task(_verification_bit_map, ld, label, options);
757     _heap->workers()->run_task(&task);
758     count_marked = task.processed();
759   } else {
760     guarantee(ShenandoahVerifyLevel < 4 || marked == _verify_marked_incomplete || marked == _verify_marked_disable, "Should be");
761   }
762 
763   // Step 4. Verify accumulated liveness data, if needed. Only reliable if verification level includes
764   // marked objects.
765 
766   if (ShenandoahVerifyLevel >= 4 && marked == _verify_marked_complete && liveness == _verify_liveness_complete) {
767     for (size_t i = 0; i < _heap->num_regions(); i++) {
768       ShenandoahHeapRegion* r = _heap->get_region(i);
769 
770       juint verf_live = 0;
771       if (r->is_humongous()) {
772         // For humongous objects, test if start region is marked live, and if so,
773         // all humongous regions in that chain have live data equal to their "used".
774         juint start_live = Atomic::load(&ld[r->humongous_start_region()->index()]);
775         if (start_live > 0) {
776           verf_live = (juint)(r->used() / HeapWordSize);
777         }
778       } else {
779         verf_live = Atomic::load(&ld[r->index()]);
780       }
781 
782       size_t reg_live = r->get_live_data_words();
783       if (reg_live != verf_live) {
784         stringStream ss;
785         r->print_on(&ss);
786         fatal("%s: Live data should match: region-live = " SIZE_FORMAT ", verifier-live = " UINT32_FORMAT "\n%s",
787               label, reg_live, verf_live, ss.freeze());
788       }
789     }
790   }
791 
792   log_info(gc)("Verify %s, Level " INTX_FORMAT " (" SIZE_FORMAT " reachable, " SIZE_FORMAT " marked)",
793                label, ShenandoahVerifyLevel, count_reachable, count_marked);
794 
795   FREE_C_HEAP_ARRAY(ShenandoahLivenessData, ld);
796 }
797 
798 void ShenandoahVerifier::verify_generic(VerifyOption vo) {
799   verify_at_safepoint(
800           "Generic Verification",
801           _verify_forwarded_allow,     // conservatively allow forwarded
802           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
803           _verify_cset_disable,        // cset may be inconsistent
804           _verify_liveness_disable,    // no reliable liveness data
805           _verify_regions_disable,     // no reliable region data
806           _verify_gcstate_disable      // no data about gcstate
807   );
808 }
809 
810 void ShenandoahVerifier::verify_before_concmark() {
811     verify_at_safepoint(
812           "Before Mark",
813           _verify_forwarded_none,      // UR should have fixed up
814           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
815           _verify_cset_none,           // UR should have fixed this
816           _verify_liveness_disable,    // no reliable liveness data
817           _verify_regions_notrash,     // no trash regions
818           _verify_gcstate_stable       // there are no forwarded objects
819   );
820 }
821 
822 void ShenandoahVerifier::verify_after_concmark() {
823   verify_at_safepoint(
824           "After Mark",
825           _verify_forwarded_none,      // no forwarded references
826           _verify_marked_complete_except_references, // bitmaps as precise as we can get, except dangling j.l.r.Refs
827           _verify_cset_none,           // no references to cset anymore
828           _verify_liveness_complete,   // liveness data must be complete here
829           _verify_regions_disable,     // trash regions not yet recycled
830           _verify_gcstate_stable_weakroots  // heap is still stable, weakroots are in progress
831   );
832 }
833 
834 void ShenandoahVerifier::verify_before_evacuation() {
835   verify_at_safepoint(
836           "Before Evacuation",
837           _verify_forwarded_none,                    // no forwarded references
838           _verify_marked_complete_except_references, // walk over marked objects too
839           _verify_cset_disable,                      // non-forwarded references to cset expected
840           _verify_liveness_complete,                 // liveness data must be complete here
841           _verify_regions_disable,                   // trash regions not yet recycled
842           _verify_gcstate_stable_weakroots           // heap is still stable, weakroots are in progress
843   );
844 }
845 
846 void ShenandoahVerifier::verify_before_updaterefs() {
847   verify_at_safepoint(
848           "Before Updating References",
849           _verify_forwarded_allow,     // forwarded references allowed
850           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
851           _verify_cset_forwarded,      // all cset refs are fully forwarded
852           _verify_liveness_disable,    // no reliable liveness data anymore
853           _verify_regions_notrash,     // trash regions have been recycled already
854           _verify_gcstate_forwarded    // evacuation should have produced some forwarded objects
855   );
856 }
857 
858 void ShenandoahVerifier::verify_after_updaterefs() {
859   verify_at_safepoint(
860           "After Updating References",
861           _verify_forwarded_none,      // no forwarded references
862           _verify_marked_complete,     // bitmaps might be stale, but alloc-after-mark should be well
863           _verify_cset_none,           // no cset references, all updated
864           _verify_liveness_disable,    // no reliable liveness data anymore
865           _verify_regions_nocset,      // no cset regions, trash regions have appeared
866           _verify_gcstate_stable       // update refs had cleaned up forwarded objects
867   );
868 }
869 
870 void ShenandoahVerifier::verify_after_degenerated() {
871   verify_at_safepoint(
872           "After Degenerated GC",
873           _verify_forwarded_none,      // all objects are non-forwarded
874           _verify_marked_complete,     // all objects are marked in complete bitmap
875           _verify_cset_none,           // no cset references
876           _verify_liveness_disable,    // no reliable liveness data anymore
877           _verify_regions_notrash_nocset, // no trash, no cset
878           _verify_gcstate_stable       // degenerated refs had cleaned up forwarded objects
879   );
880 }
881 
882 void ShenandoahVerifier::verify_before_fullgc() {
883   verify_at_safepoint(
884           "Before Full GC",
885           _verify_forwarded_allow,     // can have forwarded objects
886           _verify_marked_disable,      // do not verify marked: lots ot time wasted checking dead allocations
887           _verify_cset_disable,        // cset might be foobared
888           _verify_liveness_disable,    // no reliable liveness data anymore
889           _verify_regions_disable,     // no reliable region data here
890           _verify_gcstate_disable      // no reliable gcstate data
891   );
892 }
893 
894 void ShenandoahVerifier::verify_after_fullgc() {
895   verify_at_safepoint(
896           "After Full GC",
897           _verify_forwarded_none,      // all objects are non-forwarded
898           _verify_marked_complete,     // all objects are marked in complete bitmap
899           _verify_cset_none,           // no cset references
900           _verify_liveness_disable,    // no reliable liveness data anymore
901           _verify_regions_notrash_nocset, // no trash, no cset
902           _verify_gcstate_stable        // full gc cleaned up everything
903   );
904 }
905 
906 class ShenandoahVerifyNoForwared : public OopClosure {
907 private:
908   template <class T>
909   void do_oop_work(T* p) {
910     T o = RawAccess<>::oop_load(p);
911     if (!CompressedOops::is_null(o)) {
912       oop obj = CompressedOops::decode_not_null(o);
913       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
914       if (obj != fwd) {
915         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
916                                          "Verify Roots", "Should not be forwarded", __FILE__, __LINE__);
917       }
918     }
919   }
920 
921 public:
922   void do_oop(narrowOop* p) { do_oop_work(p); }
923   void do_oop(oop* p)       { do_oop_work(p); }
924 };
925 
926 class ShenandoahVerifyInToSpaceClosure : public OopClosure {
927 private:
928   template <class T>
929   void do_oop_work(T* p) {
930     T o = RawAccess<>::oop_load(p);
931     if (!CompressedOops::is_null(o)) {
932       oop obj = CompressedOops::decode_not_null(o);
933       ShenandoahHeap* heap = ShenandoahHeap::heap();
934 
935       if (!heap->marking_context()->is_marked(obj)) {
936         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
937                 "Verify Roots In To-Space", "Should be marked", __FILE__, __LINE__);
938       }
939 
940       if (heap->in_collection_set(obj)) {
941         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
942                 "Verify Roots In To-Space", "Should not be in collection set", __FILE__, __LINE__);
943       }
944 
945       oop fwd = ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
946       if (obj != fwd) {
947         ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, p, nullptr,
948                 "Verify Roots In To-Space", "Should not be forwarded", __FILE__, __LINE__);
949       }
950     }
951   }
952 
953 public:
954   void do_oop(narrowOop* p) { do_oop_work(p); }
955   void do_oop(oop* p)       { do_oop_work(p); }
956 };
957 
958 void ShenandoahVerifier::verify_roots_in_to_space() {
959   ShenandoahVerifyInToSpaceClosure cl;
960   ShenandoahRootVerifier::roots_do(&cl);
961 }
962 
963 void ShenandoahVerifier::verify_roots_no_forwarded() {
964   ShenandoahVerifyNoForwared cl;
965   ShenandoahRootVerifier::roots_do(&cl);
966 }