From 71cfb04dfc2058f1040eb3f890efb6ee0efc18b4 Mon Sep 17 00:00:00 2001 From: Motomu Utsumi Date: Mon, 8 Jul 2024 12:10:48 +0900 Subject: [PATCH] Add lock to update mCache from the constructor Without lock, it's not guaranteed that the methods see values populated by the constructor Bug: 349952743 Test: TH (cherry picked from https://android-review.googlesource.com/q/commit:053f9e63e5271be6bb5f10992141cd3c273971b4) Merged-In: I5c98766a22047f49ad3338bfe620d3b8f4ef477e Change-Id: I5c98766a22047f49ad3338bfe620d3b8f4ef477e --- .../android/net/module/util/SingleWriterBpfMap.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/staticlibs/device/com/android/net/module/util/SingleWriterBpfMap.java b/staticlibs/device/com/android/net/module/util/SingleWriterBpfMap.java index cd6bfec294..a638cc4151 100644 --- a/staticlibs/device/com/android/net/module/util/SingleWriterBpfMap.java +++ b/staticlibs/device/com/android/net/module/util/SingleWriterBpfMap.java @@ -19,6 +19,7 @@ import android.os.Build; import android.system.ErrnoException; import android.util.Pair; +import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; @@ -60,6 +61,7 @@ import java.util.NoSuchElementException; public class SingleWriterBpfMap extends BpfMap { // HashMap instead of ArrayMap because it performs better on larger maps, and many maps used in // our code can contain hundreds of items. + @GuardedBy("this") private final HashMap mCache = new HashMap<>(); // This should only ever be called (hence private) once for a given 'path'. @@ -72,10 +74,12 @@ public class SingleWriterBpfMap extends BpfM super(path, BPF_F_RDWR_EXCLUSIVE, key, value); // Populate cache with the current map contents. - K currentKey = super.getFirstKey(); - while (currentKey != null) { - mCache.put(currentKey, super.getValue(currentKey)); - currentKey = super.getNextKey(currentKey); + synchronized (this) { + K currentKey = super.getFirstKey(); + while (currentKey != null) { + mCache.put(currentKey, super.getValue(currentKey)); + currentKey = super.getNextKey(currentKey); + } } }