Only fill methods with 0xFE on debug builds

The GC scans classes without holding any locks, we can not fill
the methods if it is running. Added a GC critical section to address
this. Fixes random crash when scanning classes' methods.

Only for debug builds to not hurt performance.

(cherry picked from commit 22bd2a1b5ec2a5038cc3ae1964781f30aef0315f)

Bug: 28699001
Change-Id: If96155eaf3fc0e6df31f57dcf32fbd4063b09345
diff --git a/runtime/class_linker.cc b/runtime/class_linker.cc
index 8fcb6b2..d03b57c 100644
--- a/runtime/class_linker.cc
+++ b/runtime/class_linker.cc
@@ -52,6 +52,7 @@
 #include "gc/accounting/card_table-inl.h"
 #include "gc/accounting/heap_bitmap-inl.h"
 #include "gc/heap.h"
+#include "gc/scoped_gc_critical_section.h"
 #include "gc/space/image_space.h"
 #include "handle_scope-inl.h"
 #include "image-inl.h"
@@ -6981,8 +6982,13 @@
       }
     }
     // Put some random garbage in old methods to help find stale pointers.
-    if (methods != old_methods && old_methods != nullptr) {
-      WriterMutexLock mu(self, ClassTableForClassLoader(klass->GetClassLoader())->GetLock());
+    if (methods != old_methods && old_methods != nullptr && kIsDebugBuild) {
+      // Need to make sure the GC is not running since it could be scanning the methods we are
+      // about to overwrite.
+      ScopedThreadStateChange tsc(self, kSuspended);
+      gc::ScopedGCCriticalSection gcs(self,
+                                      gc::kGcCauseClassLinker,
+                                      gc::kCollectorTypeClassLinker);
       memset(old_methods, 0xFEu, old_size);
     }
   } else {