From cf0a6e80187366de4135290709c4c209bc020875 Mon Sep 17 00:00:00 2001 From: Sim Sun Date: Wed, 23 Nov 2022 18:46:02 -0800 Subject: [PATCH] Fix a potential Thread Safety Violation: Read/Write race Summary: Non-private method `SoLoader.loadLibrary(...)` indirectly reads without synchronization from `nativeloader.NativeLoader.sDelegate`. Potentially races with write in method `SoLoader.init(...)`. Reviewed By: charles011 Differential Revision: D41509137 fbshipit-source-id: 66fb99673fa30ea2a72fa5d59d792825f90306d5 --- .../soloader/nativeloader/NativeLoader.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/java/com/facebook/soloader/nativeloader/NativeLoader.java b/java/com/facebook/soloader/nativeloader/NativeLoader.java index 04f2d6d..ec33b2b 100644 --- a/java/com/facebook/soloader/nativeloader/NativeLoader.java +++ b/java/com/facebook/soloader/nativeloader/NativeLoader.java @@ -48,6 +48,7 @@ public static boolean loadLibrary(String shortName, int flags) { + "NativeLoader.init(new SystemDelegate())."); } } + return sDelegate.loadLibrary(shortName, flags); } @@ -95,11 +96,13 @@ public static int getSoSourcesVersion() { * * @param delegate Delegate to use for all {@code loadLibrary} calls. */ - public static synchronized void init(NativeLoaderDelegate delegate) { - if (sDelegate != null) { - throw new IllegalStateException("Cannot re-initialize NativeLoader."); + public static void init(NativeLoaderDelegate delegate) { + synchronized (NativeLoader.class) { + if (sDelegate != null) { + throw new IllegalStateException("Cannot re-initialize NativeLoader."); + } + sDelegate = delegate; } - sDelegate = delegate; } /** @@ -110,8 +113,10 @@ public static synchronized void init(NativeLoaderDelegate delegate) { * * @return True if {@link #init(NativeLoaderDelegate)} has been called. */ - public static synchronized boolean isInitialized() { - return sDelegate != null; + public static boolean isInitialized() { + synchronized (NativeLoader.class) { + return sDelegate != null; + } } /** @@ -121,7 +126,7 @@ public static synchronized boolean isInitialized() { * * @param delegate the NativeLoaderDelegate */ - public static synchronized void initIfUninitialized(NativeLoaderDelegate delegate) { + public static void initIfUninitialized(NativeLoaderDelegate delegate) { if (!isInitialized()) { init(delegate); }