Skip to content

Commit

Permalink
Added additional builder method receiving arguments for using jsc or …
Browse files Browse the repository at this point in the history
…hermes to correctly decide which DSO to load at app startup. (#33952)

Summary:
The current implementation of **getDefaultJSExecutorFactory** relies solely on try catch to load the correct .so file for jsc or hermes based on the project configuration.
Relying solely on try catch block and loading jsc even when project is using hermes can lead to launch time crashes especially in monorepo architectures and hybrid apps using both native android and react native.
So we can make use of an additional **ReactInstanceManager :: setJsEngineAsHermes** method that accepts a Boolean argument from the host app while building ReactInstanceManager which can tell which library to load at startup in **ReactInstanceManagerBuilder** which will now have an enhanced getDefaultJSExecutorFactory method that will combine the old logic with the new one to load the dso files.

The code snippet in **ReactInstanceManager** for adding a new setter method:

```
  /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }
```

The code snippet for the new logic in **ReactInstanceManagerBuilder**:

1) Setting up the new logic:
Adding a new enum class :
```
  public enum JSInterpreter {
    OLD_LOGIC,
    JSC,
    HERMES
  }
```

A setter getting boolean value telling whether to use hermes or not and calling a private setter to update the enum variable.
```
 /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }
```

2) Modifying the getDefaultJSExecutorFactory method to incorporate the new logic with the old one:

```
   private JavaScriptExecutorFactory getDefaultJSExecutorFactory(
    String appName, String deviceName, Context applicationContext) {

    // Relying solely on try catch block and loading jsc even when
    // project is using hermes can lead to launch-time crashes especially in
    // monorepo architectures and hybrid apps using both native android
    // and react native.
    // So we can use the value of enableHermes received by the constructor
    // to decide which library to load at launch

    // if nothing is specified, use old loading method
    // else load the required engine
    if (jsEngine == JSInterpreter.OLD_LOGIC) {
      try {
        // If JSC is included, use it as normal
        initializeSoLoaderIfNecessary(applicationContext);
        JSCExecutor.loadLibrary();
        return new JSCExecutorFactory(appName, deviceName);
      } catch (UnsatisfiedLinkError jscE) {
        if (jscE.getMessage().contains("__cxa_bad_typeid")) {
          throw jscE;
        }
        HermesExecutor.loadLibrary();
        return new HermesExecutorFactory();
      }
    } else if (jsEngine == JSInterpreter.HERMES) {
      HermesExecutor.loadLibrary();
      return new HermesExecutorFactory();
    } else {
      JSCExecutor.loadLibrary();
      return new JSCExecutorFactory(appName, deviceName);
    }
  }
```

### **Suggested changes in any Android App's MainApplication that extends ReactApplication to take advantage of this fix**
```
builder = ReactInstanceManager.builder()
                .setApplication(this)
                .setJsEngineAsHermes(BuildConfig.HERMES_ENABLED)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
```

where HERMES_ENABLED is a buildConfigField based on the enableHermes flag in build.gradle:

`def enableHermes = project.ext.react.get("enableHermes", true)
`
and then

```
defaultConfig{
if(enableHermes) {
            buildConfigField("boolean", "HERMES_ENABLED", "true")
        }
        else{
            buildConfigField("boolean", "HERMES_ENABLED", "false")
        }
}
```

Our app was facing a similar issue as listed in this list:  **https://github.com/facebook/react-native/issues?q=is%3Aissue+is%3Aopen+DSO**. Which was react-native trying to load jsc even when our project used hermes when a debug build was deployed on a device using android studio play button.

This change can possibly solve many of the issues listed in the list as it solved ours.

## Changelog

[GENERAL] [ADDED] - An enum JSInterpreter  in com.facebook.react package:
```
/**
 * An enum that specifies the JS Engine to be used in the app
 * Old Logic uses the legacy code
 * JSC/HERMES loads the respective engine using the revamped logic
 */
public enum JSInterpreter {
  OLD_LOGIC,
  JSC,
  HERMES
}
```

[GENERAL] [ADDED] - An enum variable storing the default value of Js Engine loading mechanism in ReactInstanceManagerBuilder:

```
   private JSInterpreter  jsEngine = JSInterpreter.OLD_LOGIC;
```

[GENERAL] [ADDED] - A new setter method and a helper method to set the js engine in ReactInstanceManagerBuilder:
```
  /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }

```

[GENERAL] [ADDED] - Modified **getDefaultJSExecutorFactory** method

```
private JavaScriptExecutorFactory getDefaultJSExecutorFactory(
    String appName, String deviceName, Context applicationContext) {

    // Relying solely on try catch block and loading jsc even when
    // project is using hermes can lead to launch-time crashes especially in
    // monorepo architectures and hybrid apps using both native android
    // and react native.
    // So we can use the value of enableHermes received by the constructor
    // to decide which library to load at launch

    // if nothing is specified, use old loading method
    // else load the required engine
    if (jsEngine == JSInterpreter.OLD_LOGIC) {
      try {
        // If JSC is included, use it as normal
        initializeSoLoaderIfNecessary(applicationContext);
        JSCExecutor.loadLibrary();
        return new JSCExecutorFactory(appName, deviceName);
      } catch (UnsatisfiedLinkError jscE) {
        if (jscE.getMessage().contains("__cxa_bad_typeid")) {
          throw jscE;
        }
        HermesExecutor.loadLibrary();
        return new HermesExecutorFactory();
      }
    } else if (jsEngine == JSInterpreter.HERMES) {
      HermesExecutor.loadLibrary();
      return new HermesExecutorFactory();
    } else {
      JSCExecutor.loadLibrary();
      return new JSCExecutorFactory(appName, deviceName);
    }
  }
```

Pull Request resolved: #33952

Test Plan:
The testing for this change might be tricky but can be done by following the reproduction steps in the issues related to DSO loading here: https://github.com/facebook/react-native/issues?q=is%3Aissue+is%3Aopen+DSO

Generally, the app will not crash anymore on deploying debug using android studio if we are removing libjsc and its related libraries in **packagingOptions** in build.gradle and using hermes in the project.
It can be like:
```
packagingOptions {
        if (enableHermes) {
            exclude "**/libjsc*.so"
        }
    }
```

Reviewed By: lunaleaps

Differential Revision: D37191981

Pulled By: cortinico

fbshipit-source-id: c528ead126939f1d788af7523f3798ed2a14f36e
  • Loading branch information
KunalFarmah98 authored and facebook-github-bot committed Jun 23, 2022
1 parent fa814d4 commit 87cfd38
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 30 deletions.
18 changes: 18 additions & 0 deletions ReactAndroid/src/main/java/com/facebook/react/JSInterpreter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

package com.facebook.react;

/**
* An enum that specifies the JS Engine to be used in the app Old Logic uses the legacy code
* JSC/HERMES loads the respective engine using the revamped logic
*/
public enum JSInterpreter {
OLD_LOGIC,
JSC,
HERMES
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public class ReactInstanceManagerBuilder {
private @Nullable Map<String, RequestHandler> mCustomPackagerCommandHandlers;
private @Nullable ReactPackageTurboModuleManagerDelegate.Builder mTMMDelegateBuilder;
private @Nullable SurfaceDelegateFactory mSurfaceDelegateFactory;
private JSInterpreter jsInterpreter = JSInterpreter.OLD_LOGIC;

/* package protected */ ReactInstanceManagerBuilder() {}

Expand Down Expand Up @@ -125,6 +126,31 @@ public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader jsBundleLoad
return this;
}

/**
* Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call Uses the enum {@link
* JSInterpreter}
*
* @param jsInterpreter
*/
private void setJSEngine(JSInterpreter jsInterpreter) {
this.jsInterpreter = jsInterpreter;
}

/**
* Utility setter to set the required JSEngine as HERMES or JSC Defaults to OLD_LOGIC if not
* called by the host app
*
* @param hermesEnabled hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
*/
public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled) {
if (hermesEnabled) {
setJSEngine(JSInterpreter.HERMES);
} else {
setJSEngine(JSInterpreter.JSC);
}
return this;
}

/**
* Path to your app's main module on Metro. This is used when reloading JS during development. All
* paths are relative to the root folder the packager is serving files from. Examples: {@code
Expand Down Expand Up @@ -345,41 +371,35 @@ public ReactInstanceManager build() {

private JavaScriptExecutorFactory getDefaultJSExecutorFactory(
String appName, String deviceName, Context applicationContext) {
try {
// If JSC is included, use it as normal
initializeSoLoaderIfNecessary(applicationContext);
JSCExecutor.loadLibrary();
return new JSCExecutorFactory(appName, deviceName);
} catch (UnsatisfiedLinkError jscE) {
// https://github.com/facebook/hermes/issues/78 shows that
// people who aren't trying to use Hermes are having issues.
// https://github.com/facebook/react-native/issues/25923#issuecomment-554295179
// includes the actual JSC error in at least one case.
//
// So, if "__cxa_bad_typeid" shows up in the jscE exception
// message, then we will assume that's the failure and just
// throw now.

if (jscE.getMessage().contains("__cxa_bad_typeid")) {
throw jscE;
}

// Otherwise use Hermes
// Relying solely on try catch block and loading jsc even when
// project is using hermes can lead to launch-time crashes especially in
// monorepo architectures and hybrid apps using both native android
// and react native.
// So we can use the value of enableHermes received by the constructor
// to decide which library to load at launch

// if nothing is specified, use old loading method
// else load the required engine
if (jsInterpreter == JSInterpreter.OLD_LOGIC) {
try {
// If JSC is included, use it as normal
initializeSoLoaderIfNecessary(applicationContext);
JSCExecutor.loadLibrary();
return new JSCExecutorFactory(appName, deviceName);
} catch (UnsatisfiedLinkError jscE) {
if (jscE.getMessage().contains("__cxa_bad_typeid")) {
throw jscE;
}
HermesExecutor.loadLibrary();
return new HermesExecutorFactory();
} catch (UnsatisfiedLinkError hermesE) {
// If we get here, either this is a JSC build, and of course
// Hermes failed (since it's not in the APK), or it's a Hermes
// build, and Hermes had a problem.

// We suspect this is a JSC issue (it's the default), so we
// will throw that exception, but we will print hermesE first,
// since it could be a Hermes issue and we don't want to
// swallow that.
hermesE.printStackTrace();
throw jscE;
}
} else if (jsInterpreter == JSInterpreter.HERMES) {
HermesExecutor.loadLibrary();
return new HermesExecutorFactory();
} else {
JSCExecutor.loadLibrary();
return new JSCExecutorFactory(appName, deviceName);
}
}
}

2 comments on commit 87cfd38

@SparshaSaha
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@KunalFarmah98 is this fix being cherry picked to 0.68?

@cortinico
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope is not

Please sign in to comment.