Skip to content

Commit

Permalink
Add MountItemPoolsReleaseValidator
Browse files Browse the repository at this point in the history
Summary:
# Context

I had to investigate potential sources of memory leaks for the Instagram Feed implementation. As I couldn't reproduce any specific memory leak, I have built this  `MountItemPoolsReleaseValidator` which inspects views before they are released into the Pool, and looks for usual sources of leaks: uncleaned click/touch/long click listeners and tags.

This will work for any complex primitives/mount specs that may also forget to clean these view properties from nested views of the Primitive.

# What it doesn't cover

This won't detect if this is any custom view, with particular custom listeners. Covering all possible cases in custom views is just "impossible", so this is just a tool to help with the basic cases.

# How to use

Just go to `MountItemsPools` and initialize it as you wish (you can also add regex to exclude some patterns that you have cleared out as "safe").

An example is:

```
  private val mountItemPoolsReleaseValidator: MountItemPoolsReleaseValidator? =
      MountItemPoolsReleaseValidator(
          excludedPatterns =
              setOf(
                  "IgProgressImageView@id/row_feed_photo_imageview->TextView".toRegex(),
                  "com\\.instagram\\.common\\.bloks\\.components\\.BloksRenderComponent".toRegex(),
                  "^com\\.instagram\\.feed\\.ui\\.rows\\.mediaview\\.MediaPreviewPrimitiveComponent(.*)1->IgFrameLayout$"
                      .toRegex()))

```

One example of a "safe" example, was a custom view in IG that set an internal click listener on init, but never cleaned it. That was a safe listener because it wasn't capturing anything particular that could cause a leak.

## Where this has worked

This has helped me to identify already a couple of sources potential sources of leaks:
- D58944182
- D58922987

Reviewed By: jettbow

Differential Revision: D58945023

fbshipit-source-id: e2058053248d0ca9b4fdcdd9464310e567433677
  • Loading branch information
Fabio Carballo authored and facebook-github-bot committed Jun 26, 2024
1 parent 272c321 commit 0e60d1f
Show file tree
Hide file tree
Showing 2 changed files with 179 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.facebook.rendercore

import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.view.children
import com.facebook.kotlin.compilerplugins.dataclassgenerate.annotation.DataClassGenerate
import java.lang.reflect.Field

/**
* Inspects a [View] to understand if it has any view properties that were not cleaned up before the
* item is sent back to the [MountItemsPool].
*
* This should only be used for debugging purposes.
*/
internal class MountItemPoolsReleaseValidator(
private val failOnDetection: Boolean = false,
private val excludedPatterns: Set<Regex> = emptySet(),
/**
* These are fields the client can add for custom fields they want to inspect. If you have a
* custom view you can define a specific extraction that verifies if a listener was properly
* cleaned up for example
*/
extraFields: List<FieldExtractionDefinition> = emptyList()
) {

private val fields =
setOf(
FieldExtractionDefinition("touchListener") {
getListenerFieldFromViewListenerInfo(it, "mOnTouchListener")
},
FieldExtractionDefinition("clickListener") {
getListenerFieldFromViewListenerInfo(it, "mOnClickListener")
},
FieldExtractionDefinition("longClickListener") {
getListenerFieldFromViewListenerInfo(it, "mOnLongClickListener")
},
FieldExtractionDefinition("focusChangeListener") {
getListenerFieldFromViewListenerInfo(it, "mOnFocusChangeListener")
},
FieldExtractionDefinition("scrollChangeListener") {
getListenerFieldFromViewListenerInfo(it, "mOnScrollChangeListener")
},
FieldExtractionDefinition("layoutChangeListeners") {
getListenerFieldFromViewListenerInfo(it, "mOnLayoutChangeListeners")
},
FieldExtractionDefinition("attachStateChangeListeners") {
getListenerFieldFromViewListenerInfo(it, "mOnAttachStateChangeListeners")
},
FieldExtractionDefinition("dragListener") {
getListenerFieldFromViewListenerInfo(it, "mOnDragListener")
},
FieldExtractionDefinition("keyListener") {
getListenerFieldFromViewListenerInfo(it, "mOnKeyListener")
},
FieldExtractionDefinition("contextClickListener") {
getListenerFieldFromViewListenerInfo(it, "mOnContextClickListener")
},
FieldExtractionDefinition("applyWindowInsetsListener") {
getListenerFieldFromViewListenerInfo(it, "mOnApplyWindowInsetsListener")
},
FieldExtractionDefinition("tag") { it.tag },
FieldExtractionDefinition("seekBarListener") {
if (it is SeekBar) {
getFieldFromSeekBar(it)
} else {
null
}
}) + extraFields

fun assertValidRelease(view: View, hierarchyIdentifiers: List<String>) {
if (!BuildConfig.DEBUG) {
return
}

val viewIdResourceName = getReadableResourceName(view)
val viewIdentifier =
"${view.javaClass.simpleName}${if(viewIdResourceName.isNullOrBlank()) "" else "@id/$viewIdResourceName"}"
val currentHierarchy = hierarchyIdentifiers + listOf(viewIdentifier)
if (view is ViewGroup) {
view.children.forEach { child -> assertValidRelease(child, currentHierarchy) }
}

val currentHierarchyIdentifier = currentHierarchy.joinToString("->")

if (excludedPatterns.any {
it.containsMatchIn(currentHierarchyIdentifier) || it.matches(currentHierarchyIdentifier)
}) {
return
}

val unreleasedFields = fields.filter { field -> field.extractor(view) != null }
if (unreleasedFields.isNotEmpty()) {
val result = buildString {
append("Improper release detected: ${currentHierarchyIdentifier}\n")
unreleasedFields.forEach { field -> append("- ${field.id} | ${field.extractor(view)}\n") }

if (view is TextView) {
append("- text=${view.text}\n")
}
append("\n")
}

if (failOnDetection) {
assert(false) { result }
} else {
Log.d(TAG, currentHierarchyIdentifier)
Log.d(TAG, result)
}
}
}

private fun getListenerFieldFromViewListenerInfo(view: View, fieldName: String): Any? {
return try {
val listenerInfoField: Field = View::class.java.getDeclaredField("mListenerInfo")
listenerInfoField.isAccessible = true
val listenerInfo = listenerInfoField.get(view) ?: return null

val listenerInfoGivenField: Field = listenerInfo.javaClass.getDeclaredField(fieldName)
listenerInfoGivenField.isAccessible = true
listenerInfoGivenField.get(listenerInfo)
} catch (e: NoSuchFieldException) {
null
} catch (e: IllegalAccessException) {
null
}
}

private fun getFieldFromSeekBar(view: SeekBar): Any? {
return try {
val listenerInfoField = SeekBar::class.java.getDeclaredField("mOnSeekBarChangeListener")
listenerInfoField.isAccessible = true
val listener = listenerInfoField.get(view) as? SeekBar.OnSeekBarChangeListener
listener
} catch (e: NoSuchFieldException) {
null
} catch (e: IllegalAccessException) {
null
}
}

private fun getReadableResourceName(view: View): String? {
return try {
view.context.resources.getResourceEntryName(view.id)
} catch (e: Exception) {
null
}
}

@DataClassGenerate
data class FieldExtractionDefinition(val id: String, val extractor: (View) -> Any?)
}

private const val TAG = "MountReleaseValidator"
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.core.util.Pools
import java.util.WeakHashMap
Expand All @@ -38,6 +39,8 @@ import javax.annotation.concurrent.GuardedBy
*/
object MountItemsPool {

private val mountItemPoolsReleaseValidator: MountItemPoolsReleaseValidator? = null

/** A factory used to create [MountItemsPool.ItemPool]s. */
fun interface Factory {

Expand Down Expand Up @@ -84,6 +87,10 @@ object MountItemsPool {
@JvmStatic
fun release(context: Context, poolableMountContent: ContentAllocator<*>, mountContent: Any) {
val pool = getOrCreateMountContentPool(context, poolableMountContent)
if (mountItemPoolsReleaseValidator != null && pool != null && mountContent is View) {
mountItemPoolsReleaseValidator.assertValidRelease(
mountContent, listOf(poolableMountContent.getPoolableContentType().name))
}
pool?.release(mountContent)
}

Expand Down

0 comments on commit 0e60d1f

Please sign in to comment.