Skip to content

Research: Flutter application startup flow and symbol resolution at runtime #23

Open

Description

@kalixtez

Summary

In this research issue I'll explore some of the Dart virtual machine internals (on the Android platform), more specifically, the application startup flow starting from the launching of the application's main activity to the Flutter engine initialization and dynamic symbol resolution in libapp.so. This knowledge is key in order to determine how the AOT code calls VM services that ultimately call Dart native libraries or Flutter libraries (for example, from dart:ui).

Context

  • Flutter 3.41.2

Evidence

I will try to explain how Flutter starts up from the MainActivity launching to the stage where the Flutter engine on libflutter.so is loaded into memory and called, describing how and where libapp.so is loaded into memory, how the Dart virtual machine is initialized by the Flutter engine's shell, how the Flutter engine passes it the information about Dart snapshots, and a few other things. Caution: the process described in the following text is mostly Android-specific, so do not extrapolate this behavior to other platforms. Android on itself is an odd case, given the embedder code is written in the language most commonly used in the platform: Java.

  • The // [...] comments mean that some parts of the function or code block were omitted, as to not lose focus on the more important lines.
  • I'll try to link the source file where the definition of a class is the first time I mention it, I might forget to do this.
  • I'll be re-reading these notes, adding more details and going in-depth about certain aspects of the flow that are potentially important, so the version you are reading now is probably not final (2026-02-28).
  • If I miss anything or you have proposed corrections or improvements to the clarity of the writing, please feel free to let me know.

Embedder

All platforms wishing to launch a Flutter application must first implement an embedder. The embedder, simply put, is a platform-specific bootstrapping code that's in charge of providing the Flutter engine with the supplies it needs in order to get its process started. As I just mentioned, this embedder code is written in Java for the Android platform, and you can find the entirety of its source in Flutter's repository. When you create a new Flutter project, you will notice that Android-specific applications have a have a small portion of Java/Kotlin code that looks like this:

package com.example.research_min_app_flutterdec

import io.flutter.embedding.android.FlutterActivity

class MainActivity : FlutterActivity()

The class's implementation is empty because all of its logic is is on the FlutterActivity class defined in Flutter's source. Normally, one does not need to override anything as this class implements everything the Android Runtime needs to launch the application with a default intent, and getting the Flutter engine to run alongside it. This class, as you might have guessed, is also the entry point into Flutter's embedder for Android, and here's the function called when the class is loaded and executed:

FlutterActivity.java ➥

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) 
  {
    // [...]

    delegate = new FlutterActivityAndFragmentDelegate(this);
    delegate.onAttach(this);

    // [...]
  }

This function will launch the application's splash art, switch views... etc. But the important part is the creation of the delegate instance, which is a member variable of the activity class. Both the embedding of a Flutter view as a whole activity or a Fragment are handled by the delegate of type FlutterActivityAndFragmentDelegate. It contains the main logic for Activity-related handlers such as onResume, onStart, etc... It is called "delegate" precisely because of that. Both FragmentActivity and FlutterActivity call it instead of implementing the logic in their own methods (though here I will only focus on FlutterActivity's flow), you can see that here:

FlutterActivity.java

@Override
  protected void onStart() {
    super.onStart();
    lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START);
    if (stillAttachedForEvent("onStart")) {
      delegate.onStart();
    }
  } 
  // [...]
    @Override
  protected void onSaveInstanceState(Bundle outState) {
    // [...]
  }

Now, in the FlutterActivityAndFragmentDelegate class we'll find multiple important method definitions. But let us take a look at onAttach first since it's being invoked right after the object is constructed. In case you are wondering, the constructor itself doesn't do much at all, it just initializes the class's members:

FlutterActivityAndFragmentDelegate.java

  FlutterActivityAndFragmentDelegate(@NonNull Host host, @Nullable FlutterEngineGroup engineGroup) {
    this.host = host;
    this.isFirstFrameRendered = false;
    this.engineGroup = engineGroup;
  }

For the sake of awareness, keep in mind that host is a member that holds a reference to the FlutterActivity, i.e the activity acting as host of the delegate instance, from which both its constructor and onAttach method were called. Now, the next method to look into right after the constructor is naturally, onAttach. There's a look to unpack from onAttach, but taking a look at one of the very first lines, we come across one of the most important parts of the flow, were the FlutterEngine is initialized for the first time:

FlutterActivityAndFragmentDelegate.java

void onAttach(@NonNull Context context) {
    ensureAlive(); // 1

    if (flutterEngine == null) {
      setUpFlutterEngine(); // 2
    }

    if (host.shouldAttachEngineToActivity()) // 3
    {
      Log.v(TAG, "Attaching FlutterEngine to the Activity that owns this delegate.");
      flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle()); // 4
    }

    final Activity hostActivity = host.getActivity();
    platformPlugin = host.providePlatformPlugin(hostActivity, flutterEngine);
    sensitiveContentPlugin = host.provideSensitiveContentPlugin(hostActivity, flutterEngine);

    host.configureFlutterEngine(flutterEngine); // 5
    isAttached = true;
  }

I included all of the function's body as I'll be covering all functions called here. I've marked each relevant line with a number to more easily describe what they do on a list:

  1. ensureAlive will verify that the host reference isn't null before proceeding, throwing an error if it is.
  2. This is the next part of the flow, so I'll cover this separately.
  3. This function is hardcoded to always return true.
  4. Calls the FlutterEngineConnectionRegistry's attachToActivity method, which activates the PlatformViewController and attaches default ActivityAware plugins to the engine.
  5. Adds and initializes user-defined plugins to the FlutterEngine through runtime inspection (reflection).

Now, setUpFlutterEngine is a bit harder to dissect, given it's the most important function call here by far. As the name suggests, this function creates a FlutterEngine object that is the representation of our current Flutter environment (on the Java side), and whose constructor performs multiple varied tasks. Let us skip over setUpFlutterEngine which just checks whether the FlutterActivity was called with certain intents, and if none matches, falls back to creating a normal FlutterEngine, by calling the createAndRunEngine method in the FlutterEngineGroup class, which in turn calls createEngine, which is just a wrapper to the massive FlutterEngine constructor. At this point, we are nearing the last of Java code that we see in the initialization flow before moving to C++. Let us now see part of what it does:

FlutterEngine.java

  public FlutterEngine(
      @NonNull Context context,
      @Nullable FlutterLoader flutterLoader,
      @NonNull FlutterJNI flutterJNI,
      @NonNull PlatformViewsController platformViewsController,
      @Nullable String[] dartVmArgs,
      boolean automaticallyRegisterPlugins,
      boolean waitForRestorationData,
      @Nullable FlutterEngineGroup group) {

    // [...]

    FlutterInjector injector = FlutterInjector.instance(); // 1

    if (flutterJNI == null) {
      flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI(); //2
    }
    this.flutterJNI = flutterJNI; // 2

    this.dartExecutor = new DartExecutor(flutterJNI, assetManager, engineId); // 3
    this.dartExecutor.onAttachedToJNI(); // 3

    // [...]
    
    accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI); // 4
	// [...]
    textInputChannel = new TextInputChannel(dartExecutor); // 4

    if (flutterLoader == null) {
      flutterLoader = injector.flutterLoader(); // 5
    }

    if (!flutterJNI.isAttached()) {
      flutterLoader.startInitialization(context.getApplicationContext()); // 6
      flutterLoader.ensureInitializationComplete(context, dartVmArgs); // 7
    }

    // [...]

    if (!flutterJNI.isAttached()) {
      attachToJni(); // 8
    }

    this.renderer = new FlutterRenderer(flutterJNI); // 9
    
    // [...]

    this.platformViewsControllerDelegator =
        new PlatformViewsControllerDelegator(platformViewsController, platformViewsController2); // 10

    this.pluginRegistry =
        new FlutterEngineConnectionRegistry(
            context.getApplicationContext(), this, flutterLoader, group); // 11

	// [...]
  }

Notice how despite removing a great portion of the constructor, it remains a formidable piece of code that does quite a lot. Again, I've marked each line with a number that corresponds to the following list's entry that describes what the line does:

  1. A FlutterInjection instance is obtained. This creates a FlutterJNI.Factory and a FlutterLoader instances, as members of the FlutterInjection instance. They are later used in the following steps. The FlutterJNI.Factory instance is used to provide the JNI interface to all objects that will have to contact the engine's native functions.

  2. A FlutterJNI instance is created and set as instance member for the FlutterEngine.

  3. The dartExecutor member is initialized to a new DartExecutor instance, whose constructor gets a reference to the FlutterJNI created in 2., this class, in Dart's developers own words "configures, bootstraps, and starts executing Dart code." a DartMessenger instance and DefaultBinaryMessenger instance are created. The DartMessenger acts as a bi-directional communication tunnel between Dart and Java/Kotlin, and implements the BinaryMessenger and PlatformChannelMessenger interfaces. The former acts as message tunnel going from Android to Dart, the latter serves the same purpose for the opposite communication direction. After the constructor returns, the onAttachedToJNI method is called. This method will in turn initialize the JNIs "platform channel" (also set to the DartMessenger instance), in charge of receiving and processing asynchronous messages from Dart code.

// called by the Dart to send messages to Java/Kotlin
  public void handlePlatformMessage(
      @NonNull final String channel,
      ByteBuffer message,
      final int replyId,
      final long messageData) {
	// [...]
  }

  // called by Dart to reply to messages sent through the binarymessenger
  private void handlePlatformMessageResponse(int replyId, ByteBuffer reply) {
    if (platformMessageHandler != null) {
      platformMessageHandler.handlePlatformMessageResponse(replyId, reply);
    }
  }
  1. Multiple channels are created. These channels can be Dart to Java, Java to Dart or bi-directional. They implement mechanisms to handle common events that might occur during runtime, such as Java notifying keypresses to Dart, or Dart asking Java to play a certain sound with the native API. These channels will use the MethodChannel interface to send and/or receive messages to/from Dart, the receiving is done by registering a handler for when Dart sends a message through the named channel (by calling the aforementioned handlePlatformMessage). The channels might also register a BasicMessageChannel in the case they want to establish a simple mono-directional channel. An example of the usage of a MethodChannel for bidirectional1 communication and BasicMessageChannel for mono-directional communication in NavigationChannel and KeyEventChannel definitions:
public NavigationChannel(@NonNull DartExecutor dartExecutor) {
    this.channel = new MethodChannel(dartExecutor, "flutter/navigation", JSONMethodCodec.INSTANCE);
    channel.setMethodCallHandler(defaultHandler);
  }
  public KeyEventChannel(@NonNull BinaryMessenger binaryMessenger) {
    this.channel =
        new BasicMessageChannel<>(binaryMessenger, "flutter/keyevent", JSONMessageCodec.INSTANCE);
  }
  1. A FlutterLoader instance is obtained. This instance is in charge of the loading of native libraries (libflutter.so) in this case, and multiple other things that will be described in the following entries.

  2. The startInitialization function is called. This function performs a few actions but the most important of them is the loading of the libflutter.so library. It does this by invoking FlutterJNI.loadLibrary (which triggers the execution of JNI_OnLoad) inside a Callable object that's scheduled to run on a separate thread.

  3. The ensureInitializationComplete function is called. This function is massive and likely the largest function in this flow so far, by a long shot. I will try to compress what it does as much as possible, so this function:

    • Waits (blocks) for the completion of the Future task that startInitialization set as result of the callable object.
    • Creates a list of arguments that will be passed to the native FlutterMain::Init2, there are more than 20+ flags, including, for example, the name of the snapshot-containing binary, which by default is libapp.so.
    • Invokes FlutterJNI.Init, which ultimately sets a few global jclass and jfieldID, registers a callback for when the Dart VM is initialzied, and selects the rendering API (OpenGL, Vulkan, etc...).
  4. The attachToJni function will call FlutterJNI.attachToNative, which in turn invokes nativeAttach whose implementation is in C++, AttachJNI2. This function will create a smart pointer reference to an AndroidShellHolder, whose constructor will ultimately invoke Shell::Create and this function is the one that bootstraps the Dart VM inside the Flutter engine! (more on that flow on the second part, given it needs an analysis on its own):

static jlong AttachJNI(JNIEnv* env, jclass clazz, jobject flutterJNI) {
  fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
  std::shared_ptr<PlatformViewAndroidJNI> jni_facade =
      std::make_shared<PlatformViewAndroidJNIImpl>(java_object);
  auto shell_holder = std::make_unique<AndroidShellHolder>(
      FlutterMain::Get().GetSettings(), jni_facade,
      FlutterMain::Get().GetAndroidRenderingAPI());
  if (shell_holder->IsValid()) {
    return reinterpret_cast<jlong>(shell_holder.release());
  } else {
    return 0;
  }
}
  1. The renderer is created. At some point, a Surface will be passed to it (in theory, it should be after calling onCreateView from FlutterActivity.onCreate), after which the connectSurfaceToRenderer method is called, and finally startRenderingToSurface, which does exactly what it says.

  2. The PlatformViewsControllerDelegator is initialized, and two PlatformViewsController passed as arguments. This is used to embed native views to onto the Flutter application, read more about this here if you are curious, but this isn't needed at all to understand Flutter's bootstrap flow.

  3. Finally, the plugin registry FlutterEngineConnectionRegistry is created. The plugin registry is used to register Flutter plugins from the application's code, by calling flutterEngine.getPlugins().add(...), inside the pre-generated registerWith function, which as you might recall, is invoked from configureFlutterEngine.

1. Notice that MethodChannel can be used to both receive and send with handlePlatformMessage and dispatchPlatformMessage functions in FlutterJNI, respectively).
2. Both FlutterMain::Init and AttachJNI functions are made available to Java by JNI_OnLoad, when libflutter.so is loaded.

After this function returns we have an initialized JNI, Dart virtual machine, renderer, and of course, a fresh FlutterEngine that will be used as bridge from the native code to the C++ code in libflutter. Unwinding a bit more, let us remember that we initially were inside FlutterActivity.onCreate->FlutterActivityAndFragmentDelegate.onAttach->FlutterEngine (constructor). After all these functions return, FlutterActivity.onStart -> FlutterActivityAndFragmentDelegate.onStart is called, which in turn calls the last part of our Flutter app initialization flow, the doInitialFlutterViewRun.

FlutterActivityAndFragmentDelegate.java

  private void doInitialFlutterViewRun() {
    // [...]
    
    String initialRoute = host.getInitialRoute(); // 1
    
    // [...]
    @Nullable String libraryUri = host.getDartEntrypointLibraryUri(); // 2
	
	// [...]

    flutterEngine.getNavigationChannel().setInitialRoute(initialRoute); // 3

    String appBundlePathOverride = host.getAppBundlePath();
    if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
      appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath(); // 4
    }

    // Configure the Dart entrypoint and execute it.
    DartExecutor.DartEntrypoint entrypoint =
        libraryUri == null
            ? new DartExecutor.DartEntrypoint(
                appBundlePathOverride, host.getDartEntrypointFunctionName())
            : new DartExecutor.DartEntrypoint(
                appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
    flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs()); // 5
  }

This function will ultimately call executeDartEntrypoint, a function in charge of transferring control to our Dart main function (or the function chosen as entry-point), thus finally completing the initialization process. You see this function is a bit long, so here's the explanation of the relevant steps before the calling of the entry-point:

  1. Flutter can use a named-route based navigation system similar to many other UI frameworks. The initial route (do not mistake for entry-point) is the first screen that Flutter will render by default, / is the default route, if nothing provided.
  2. This obtains the Dart URI for whatever source file the entry-point function is defined at, for example package:myapp/main.dart.
  3. Uses the NavigationChannel (initialized during the FlutterEngine constructor) to tell Flutter to set the initial route.
  4. The app bundle is path is set. This is flutter_assets by default.
  5. A DartEntrypoint instance is created. If libraryUri is null, the entry-point function will be the default value, which is DEFAULT_DART_ENTRYPOINT = 'main', and the library URI will be considered to be the file where the main function is defined. Finally, the executeDartEntrypoint is called passing the DartEntrypoint instance and arguments, which can be accessed by adding a parameter of type List<String> to the entry-point function.

Activity

  1. changed the title [-]research:[/-] [+]Research: Flutter application startup flow and symbol resolution at runtime[/+] on Feb 25, 2026
  2. caverav commented on Mar 13, 2026

    @caverav
    Owner

    Thanks for writing this up. This is useful, and it is aligned with where flutterdec is already trying to improve.

    To make it clear for contribution focus, here is the current state.

    Already covered

    A good part of the problem space described here is already implemented, at least in heuristic form:

    • flutterdec already parses AndroidManifest.xml and extracts launcher, deeplink, and activity signals.
    • Those manifest signals are already fed back into the pipeline as synthetic bootflow hints before decompilation.
    • The adapter layer already emits bootflow-style candidates from recovered names/selectors for things like main, runApp, deeplink handlers, activity/lifecycle handlers, and bootstrap-like helpers.
    • The disassembly prioritization stage already uses those hints to bias capped output toward main, runApp, deeplink, activity, and bootstrap candidates.
    • The reporting side already exposes this through android_manifest, bootflow_discovery, and selected bootflow coverage/hits in report.json.
    • The repo also already has engine-fingerprint for libflutter.so build/version hints and map-symbols for stripped vs unstripped engine symbol recovery.

    So this issue is not identifying a completely missing direction. It is mostly reinforcing an existing one.

    Not covered yet

    Where this issue is still valuable is in the gaps that are not implemented yet:

    • We do not yet statically analyze the Java / APK bytecode side to recover the actual Android embedding wiring.
    • We do not yet reconstruct the concrete MainActivity / FlutterActivity / FlutterActivityAndFragmentDelegate / FlutterEngine startup path from the APK side.
    • JNI/bootstrap awareness is still limited. We can identify bootstrap-like contexts, but we are not yet modeling FlutterJNI, native registration, or the exact handoff path in a deterministic way.
    • Dart entrypoint discovery is still mostly metadata-driven plus heuristic bootflow evidence. It is not yet tied to a stronger model of the Android startup chain you describe here, including the DartExecutor.DartEntrypoint handoff.
    • Engine symbol recovery exists, but it is still mostly an external/manual flow instead of being deeply integrated into normal decompile runs.

    Where research help is most useful

    If you want to keep researching in a way that is likely to turn into code contributions, the highest-value areas are:

    • deterministic recovery of Android embedding startup from APK bytecode, not just manifest signals
    • mapping from Java-side startup artifacts to native/bootstrap evidence that helps identify the real app entrypoint path
    • stronger static identification of FlutterJNI / engine bootstrap transitions
    • ways to feed engine symbol evidence directly into normal decompile prioritization and naming
    • distinguishing app bootstrap logic from framework/bootstrap noise in a way that remains stable on stripped/obfuscated builds
  3. caverav commented on Mar 13, 2026

    @caverav
    Owner

    Quick update here, because a good part of this issue has already turned into code, but it is not fully solved yet.

    The main pieces that landed were:

    There was also related follow-up work around engine symbol ingestion and real-binary regression checks, but the main startup work is in those PRs above.

    So this issue was definitely useful and it already moved the tool forward.

    What flutterdec can do now is:

    • inspect the manifest
    • inspect classes*.dex
    • report Flutter embedding callsites
    • report JNI/bootstrap stages
    • derive startup-backed bootflow hints
    • use those hints to bias capped decompilation toward app-owned startup-adjacent code
    • recover Dart entrypoint metadata when the APK bytecode exposes it in a very direct way

    That last part is the important caveat.

    The current entrypoint recovery is still intentionally narrow. It works when the values are visible through local patterns like direct const-string plus simple same-method register moves around things like:

    • DartEntrypoint.<init>
    • DartExecutor.executeDartEntrypoint
    • FlutterJNI.runBundleAndSnapshotFromLibrary

    That was the safest first step.

    But in real APKs, that is often not enough.

    For example, on LocalSend and Spotube, we now do get real startup evidence. We can see things like Dart execution and JNI attach. The output is not empty anymore. A simplified example of the current report shape looks like this:

    {
      "android_startup": {
        "present": true,
        "bootstrap_chain": {
          "complete": false,
          "source_count": 3,
          "sources": [
            {
              "class_name": "b8.a",
              "method_name": "j",
              "owner_kind": "app",
              "stages": ["dart_entrypoint_execute"]
            },
            {
              "class_name": "io.flutter.embedding.engine.FlutterJNI",
              "method_name": "performNativeAttach",
              "owner_kind": "framework",
              "stages": ["jni_attach"]
            }
          ]
        }
      }
    }

    That is already useful, because it tells us real startup-related app code exists and it helps prioritization.

    But the missing part is also visible: we still often end up without a recovered exact Dart entrypoint, for example with dart_entrypoint_count = 0.

    So the situation right now is that we can often see that Dart execution happens, we can often see startup-related app methods, and we can often separate app-owned startup fragments from framework-owned ones, but we still cannot always say exactly which Android-side method chain leads to which exact Dart entrypoint.

    That is the part from this issue that is still open.

    The current bootstrap_chain reporting helps by making those startup fragments visible in a structured way, but it is still not yet the same thing as a fully stitched end-to-end startup path. In practice it often gives us pieces like:

    • one method that clearly reaches Dart execution
    • another method that clearly performs JNI attach
    • another method that clearly touches loader or engine setup

    without yet connecting all of that into one deterministic startup flow.

    That is why I would say this issue is partially implemented, but not fully completed.

    The main reason is not that the direction was wrong. It is that the hard part is genuinely harder than the first implementation pass.

    A lot of real apps do not keep the interesting values in one local method. Instead they go through:

    • helper methods
    • wrapper objects
    • fields
    • app-specific embedding wrappers
    • method-to-method propagation

    The current implementation avoids guessing in those cases. That was intentional. I would rather report partial startup evidence honestly than invent a main or library name from weak evidence.

    If you want to keep pushing on this issue, the most useful next research areas are:

    • cross-method recovery for DartEntrypoint construction and execution
    • better correlation between activity / delegate / engine / JNI / Dart executor code paths
    • conservative tracking of startup values through helper methods and wrapper objects
    • better identification of app-owned startup wrappers versus framework-owned embedding code

    So overall, a lot of the direction from this issue is already implemented, and the tool is materially better because of it, but deterministic Android-side startup reconstruction and exact Dart entrypoint recovery are still incomplete. The remaining work is mostly about stronger APK bytecode correlation, not adding more loose heuristics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions