Skip to content

Commit

Permalink
Fix a potential Thread Safety Violation: Read/Write race
Browse files Browse the repository at this point in the history
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
  • Loading branch information
simpleton authored and facebook-github-bot committed Nov 24, 2022
1 parent 289534f commit cf0a6e8
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions java/com/facebook/soloader/nativeloader/NativeLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public static boolean loadLibrary(String shortName, int flags) {
+ "NativeLoader.init(new SystemDelegate()).");
}
}

return sDelegate.loadLibrary(shortName, flags);
}

Expand Down Expand Up @@ -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;
}

/**
Expand All @@ -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;
}
}

/**
Expand All @@ -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);
}
Expand Down

0 comments on commit cf0a6e8

Please sign in to comment.