Repository: flutter
Issue: FFI: SIGSEGV crash in release mode when handling image data between C++ and Dart, woks in debug mode
Labels: c: crash,platform-android,dependency: dart,will need additional triage

### Steps to reproduce


Clone repository: https://github.com/rmatif/Local-Diffusion
Build and run in debug mode - works correctly
Build release APK: flutter build apk --release --target-platform android-arm64
Install and run release APK
Initialize model and generate an image
Observe crash after image generation completes

Already attempted fixes:

- Added ProGuard rules to preserve FFI classes

<details open><summary>proguard-rules.pro</summary>

```pro
-keep class * extends ffi.Struct {
    *;
}
-keep class * implements ffi.Finalizable {
    *;
}
-keep class ffi_bindings.FFIBindings { # Keep the FFIBindings class itself
    *; # Keep all members
}
-keep class sd_image.SDImage { # Keep the SDImage class
    *; # Keep all members
}
-keep class com.example.local_diffusion.** { # Keep your main app package.  Be more specific if possible.
    *;
}

# If you have specific callback functions that are only called from native code:
-keepclassmembers class ffi_bindings.FFIBindings {
    public static void _staticLogCallback(int, ffi.Pointer, ffi.Pointer); # Example, adjust names
    public static void _staticProgressCallback(int, int, double, ffi.Pointer); # Example, adjust names
}

-keepclassmembers class sd_image.SDImage { # Keep members of SDImage
    public int width; # Keep specific fields accessed from native side (if any direct access)
    public int height;
    public int channel;
    public ffi.Pointer data;
    *; # Keep all members for safety, refine if needed later
}

-keepclassmembers class com.example.local_diffusion.stable_diffusion_processor.StableDiffusionProcessor { # Keep members if needed
    *; # Keep all members for safety, refine if needed later
}

-keep,allowshrinking,allowobfuscation class com.example.local_diffusion.** { # Keep your main app package
    <methods>;
    <fields>;
    <init>(...);
}

-keepattributes Signature
-keepattributes *Annotation*
-keep class dart.ffi.* { *; }
-keep class io.flutter.plugin.platform.* { *; }


```

</details>


- Disabled minification and resource shrinking

<details open><summary>build.gradle</summary>

```gradle
plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
}

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    namespace "com.example.local_diffusion"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.local_diffusion"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            minifyEnabled false 
            shrinkResources false
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

flutter {
    source '../..'
}

dependencies {}


```

</details>

- Modified memory management approach
- The issue appears specific to release mode builds while handling FFI image data transfer







### Expected results

Image should be displayed and saved successfully after generation, same as in debug mode.

### Actual results

App crashes with SIGSEGV (signal 11) after image generation completes

`signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x0000007600aac080
pid: 17513, tid: 18005, name: DartWorker
`

### Code sample

<details open><summary>Code sample</summary>

```dart
if (result.address != 0) {
    final image = result.cast<SDImage>().ref;
    final width = (message['width'] as num).toInt();
    final height = (message['height'] as num).toInt();
    final channels = image.channel;
    final totalBytes = width * height * channels;
    final rgbaBytes = Uint8List(width * height * 4);
    // Crash occurs during image data processing
}

```

</details>


### Screenshots or Video

_No response_

### Logs

_No response_

### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[√] Flutter (Channel stable, 3.27.2, on Microsoft Windows [version 10.0.19045.5371], locale fr-FR)
[√] Windows Version (Installed version of Windows is version 10 or higher)
[!] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/to/windows-android-setup for more details.
[√] Chrome - develop for the web
[X] Visual Studio - develop Windows apps
    X Visual Studio not installed; this is necessary to develop Windows apps.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components     
[√] Android Studio (version 2023.1)
[√] Connected device (4 available)
[√] Network resources

! Doctor found issues in 2 categories.
```

</details>