-
Notifications
You must be signed in to change notification settings - Fork 756
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
272c321
commit 0e60d1f
Showing
2 changed files
with
179 additions
and
0 deletions.
There are no files selected for viewing
172 changes: 172 additions & 0 deletions
172
litho-rendercore/src/main/java/com/facebook/rendercore/MountItemPoolsReleaseValidator.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters