summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/gecko/process/GeckoProcessManager.java
blob: 736c292ff14eb3ad8754b3d999c88851932dbdea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.process;

import android.os.DeadObjectException;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.collection.ArrayMap;
import androidx.collection.ArraySet;
import androidx.collection.SimpleArrayMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.mozilla.gecko.GeckoAppShell;
import org.mozilla.gecko.GeckoNetworkManager;
import org.mozilla.gecko.GeckoThread;
import org.mozilla.gecko.GeckoThread.FileDescriptors;
import org.mozilla.gecko.GeckoThread.ParcelFileDescriptors;
import org.mozilla.gecko.IGeckoEditableChild;
import org.mozilla.gecko.IGeckoEditableParent;
import org.mozilla.gecko.TelemetryUtils;
import org.mozilla.gecko.annotation.WrapForJNI;
import org.mozilla.gecko.gfx.CompositorSurfaceManager;
import org.mozilla.gecko.gfx.ISurfaceAllocator;
import org.mozilla.gecko.gfx.RemoteSurfaceAllocator;
import org.mozilla.gecko.mozglue.JNIObject;
import org.mozilla.gecko.process.ServiceAllocator.PriorityLevel;
import org.mozilla.gecko.util.ThreadUtils;
import org.mozilla.gecko.util.XPCOMEventTarget;
import org.mozilla.geckoview.GeckoResult;

public final class GeckoProcessManager extends IProcessManager.Stub {
  private static final String LOGTAG = "GeckoProcessManager";
  private static final GeckoProcessManager INSTANCE = new GeckoProcessManager();
  private static final int INVALID_PID = 0;

  // This id univocally identifies the current process manager instance
  private final String mInstanceId;

  public static GeckoProcessManager getInstance() {
    return INSTANCE;
  }

  @WrapForJNI(calledFrom = "gecko")
  private static void setEditableChildParent(
      final IGeckoEditableChild child, final IGeckoEditableParent parent) {
    try {
      child.transferParent(parent);
    } catch (final RemoteException e) {
      Log.e(LOGTAG, "Cannot set parent", e);
    }
  }

  @WrapForJNI(stubName = "GetEditableParent", dispatchTo = "gecko")
  private static native void nativeGetEditableParent(
      IGeckoEditableChild child, long contentId, long tabId);

  @Override // IProcessManager
  public void getEditableParent(
      final IGeckoEditableChild child, final long contentId, final long tabId) {
    nativeGetEditableParent(child, contentId, tabId);
  }

  /**
   * Returns the surface allocator interface to be used by child processes to allocate Surfaces. The
   * service bound to the returned interface may live in either the GPU process or parent process.
   */
  @Override // IProcessManager
  public ISurfaceAllocator getSurfaceAllocator() {
    final GeckoResult<Boolean> gpuEnabled = GeckoAppShell.isGpuProcessEnabled();

    try {
      final GeckoResult<ISurfaceAllocator> allocator = new GeckoResult<>();
      if (gpuEnabled.poll(1000)) {
        // The GPU process is enabled, so look it up and ask it for its surface allocator.
        XPCOMEventTarget.runOnLauncherThread(
            () -> {
              final Selector selector = new Selector(GeckoProcessType.GPU);
              final GpuProcessConnection conn =
                  (GpuProcessConnection) INSTANCE.mConnections.getExistingConnection(selector);
              if (conn != null) {
                allocator.complete(conn.getSurfaceAllocator());
              } else {
                // If we cannot find a GPU process, it has probably been killed and not yet
                // restarted. Return null here, and allow the caller to try again later.
                // We definitely do *not* want to return the parent process allocator instead, as
                // that will result in surfaces being allocated in the parent process, which
                // therefore won't be usable when the GPU process is eventually launched.
                allocator.complete(null);
              }
            });
      } else {
        // The GPU process is disabled, so return the parent process allocator instance.
        allocator.complete(RemoteSurfaceAllocator.getInstance(0));
      }
      return allocator.poll(100);
    } catch (final Throwable e) {
      Log.e(LOGTAG, "Error in getSurfaceAllocator", e);
      return null;
    }
  }

  @WrapForJNI
  public static CompositorSurfaceManager getCompositorSurfaceManager() {
    final Selector selector = new Selector(GeckoProcessType.GPU);
    final GpuProcessConnection conn =
        (GpuProcessConnection) INSTANCE.mConnections.getExistingConnection(selector);
    if (conn == null) {
      return null;
    }
    return conn.getCompositorSurfaceManager();
  }

  /** Gecko uses this class to uniquely identify a process managed by GeckoProcessManager. */
  public static final class Selector {
    private final GeckoProcessType mType;
    private final int mPid;

    @WrapForJNI
    private Selector(@NonNull final GeckoProcessType type, final int pid) {
      if (pid == INVALID_PID) {
        throw new RuntimeException("Invalid PID");
      }

      mType = type;
      mPid = pid;
    }

    @WrapForJNI
    private Selector(@NonNull final GeckoProcessType type) {
      mType = type;
      mPid = INVALID_PID;
    }

    public GeckoProcessType getType() {
      return mType;
    }

    public int getPid() {
      return mPid;
    }

    @Override
    public boolean equals(final Object obj) {
      if (obj == null) {
        return false;
      }

      if (obj == ((Object) this)) {
        return true;
      }

      final Selector other = (Selector) obj;
      return mType == other.mType && mPid == other.mPid;
    }

    @Override
    public int hashCode() {
      return Arrays.hashCode(new Object[] {mType, mPid});
    }
  }

  private static final class IncompleteChildConnectionException extends RuntimeException {
    public IncompleteChildConnectionException(@NonNull final String msg) {
      super(msg);
    }
  }

  /**
   * Maintains state pertaining to an individual child process. Inheriting from
   * ServiceAllocator.InstanceInfo enables this class to work with ServiceAllocator.
   */
  private static class ChildConnection extends ServiceAllocator.InstanceInfo {
    private IChildProcess mChild;
    private GeckoResult<IChildProcess> mPendingBind;
    private int mPid;

    protected ChildConnection(
        @NonNull final ServiceAllocator allocator,
        @NonNull final GeckoProcessType type,
        @NonNull final PriorityLevel initialPriority) {
      super(allocator, type, initialPriority);
      mPid = INVALID_PID;
    }

    public int getPid() {
      XPCOMEventTarget.assertOnLauncherThread();
      if (mChild == null) {
        throw new IncompleteChildConnectionException(
            "Calling ChildConnection.getPid() on an incomplete connection");
      }

      return mPid;
    }

    private GeckoResult<IChildProcess> completeFailedBind(
        @NonNull final ServiceAllocator.BindException e) {
      XPCOMEventTarget.assertOnLauncherThread();
      Log.e(LOGTAG, "Failed bind", e);

      if (mPendingBind == null) {
        throw new IllegalStateException("Bind failed with null mPendingBind");
      }

      final GeckoResult<IChildProcess> bindResult = mPendingBind;
      mPendingBind = null;
      unbind().accept(v -> bindResult.completeExceptionally(e));
      return bindResult;
    }

    public GeckoResult<IChildProcess> bind() {
      XPCOMEventTarget.assertOnLauncherThread();

      if (mChild != null) {
        // Already bound
        return GeckoResult.fromValue(mChild);
      }

      if (mPendingBind != null) {
        // Bind in progress
        return mPendingBind;
      }

      mPendingBind = new GeckoResult<>();
      try {
        if (!bindService()) {
          throw new ServiceAllocator.BindException("Cannot connect to process");
        }
      } catch (final ServiceAllocator.BindException e) {
        return completeFailedBind(e);
      }

      return mPendingBind;
    }

    public GeckoResult<Void> unbind() {
      XPCOMEventTarget.assertOnLauncherThread();

      if (mPendingBind != null) {
        // We called unbind() while bind() was still pending completion
        return mPendingBind.then(child -> unbind());
      }

      if (mChild == null) {
        // Not bound in the first place
        return GeckoResult.fromValue(null);
      }

      unbindService();

      return GeckoResult.fromValue(null);
    }

    @Override
    protected void onBinderConnected(final IBinder service) {
      XPCOMEventTarget.assertOnLauncherThread();

      final IChildProcess child = IChildProcess.Stub.asInterface(service);
      try {
        mPid = child.getPid();
        onBinderConnected(child);
      } catch (final DeadObjectException e) {
        unbindService();

        // mPendingBind might be null if a bind was initiated by the system (eg Service Restart)
        if (mPendingBind != null) {
          mPendingBind.completeExceptionally(e);
          mPendingBind = null;
        }

        return;
      } catch (final RemoteException e) {
        throw new RuntimeException(e);
      }

      mChild = child;
      GeckoProcessManager.INSTANCE.mConnections.onBindComplete(this);

      // mPendingBind might be null if a bind was initiated by the system (eg Service Restart)
      if (mPendingBind != null) {
        mPendingBind.complete(mChild);
        mPendingBind = null;
      }
    }

    // Subclasses of ChildConnection can override this method to make any IChildProcess calls
    // specific to their process type immediately after connection.
    protected void onBinderConnected(@NonNull final IChildProcess child) throws RemoteException {}

    @Override
    protected void onReleaseResources() {
      XPCOMEventTarget.assertOnLauncherThread();

      // NB: This must happen *before* resetting mPid!
      GeckoProcessManager.INSTANCE.mConnections.removeConnection(this);

      mChild = null;
      mPid = INVALID_PID;
    }
  }

  private static class NonContentConnection extends ChildConnection {
    public NonContentConnection(
        @NonNull final ServiceAllocator allocator, @NonNull final GeckoProcessType type) {
      super(allocator, type, PriorityLevel.FOREGROUND);
      if (type == GeckoProcessType.CONTENT) {
        throw new AssertionError("Attempt to create a NonContentConnection as CONTENT");
      }
    }

    protected void onAppForeground() {
      setPriorityLevel(PriorityLevel.FOREGROUND);
    }

    protected void onAppBackground() {
      setPriorityLevel(PriorityLevel.IDLE);
    }
  }

  private static final class GpuProcessConnection extends NonContentConnection {
    private CompositorSurfaceManager mCompositorSurfaceManager;
    private ISurfaceAllocator mSurfaceAllocator;

    // Unique ID used to identify each GPU process instance. Will always be non-zero,
    // and unlike the process' pid cannot be the same value for successive instances.
    private int mUniqueGpuProcessId;
    // Static counter used to initialize each instance's mUniqueGpuProcessId
    private static int sUniqueGpuProcessIdCounter = 0;

    public GpuProcessConnection(@NonNull final ServiceAllocator allocator) {
      super(allocator, GeckoProcessType.GPU);

      // Initialize the unique ID ensuring we skip 0 (as that is reserved for parent process
      // allocators).
      if (sUniqueGpuProcessIdCounter == 0) {
        sUniqueGpuProcessIdCounter++;
      }
      mUniqueGpuProcessId = sUniqueGpuProcessIdCounter++;
    }

    @Override
    protected void onBinderConnected(@NonNull final IChildProcess child) throws RemoteException {
      mCompositorSurfaceManager = new CompositorSurfaceManager(child.getCompositorSurfaceManager());
      mSurfaceAllocator = child.getSurfaceAllocator(mUniqueGpuProcessId);
    }

    public CompositorSurfaceManager getCompositorSurfaceManager() {
      return mCompositorSurfaceManager;
    }

    public ISurfaceAllocator getSurfaceAllocator() {
      return mSurfaceAllocator;
    }
  }

  private static final class SocketProcessConnection extends NonContentConnection {
    private boolean mIsForeground = true;
    private boolean mIsNetworkUp = true;

    public SocketProcessConnection(@NonNull final ServiceAllocator allocator) {
      super(allocator, GeckoProcessType.SOCKET);
      GeckoProcessManager.INSTANCE.mConnections.enableNetworkNotifications();
    }

    public void onNetworkStateChange(final boolean isNetworkUp) {
      mIsNetworkUp = isNetworkUp;
      prioritize();
    }

    @Override
    protected void onAppForeground() {
      mIsForeground = true;
      prioritize();
    }

    @Override
    protected void onAppBackground() {
      mIsForeground = false;
      prioritize();
    }

    private static final PriorityLevel[][] sPriorityStates = initPriorityStates();

    private static PriorityLevel[][] initPriorityStates() {
      final PriorityLevel[][] states = new PriorityLevel[2][2];
      // Background, no network
      states[0][0] = PriorityLevel.IDLE;
      // Background, network
      states[0][1] = PriorityLevel.BACKGROUND;
      // Foreground, no network
      states[1][0] = PriorityLevel.IDLE;
      // Foreground, network
      states[1][1] = PriorityLevel.FOREGROUND;
      return states;
    }

    private void prioritize() {
      final PriorityLevel nextPriority =
          sPriorityStates[mIsForeground ? 1 : 0][mIsNetworkUp ? 1 : 0];
      setPriorityLevel(nextPriority);
    }
  }

  private static final class ContentConnection extends ChildConnection {
    private static final String TELEMETRY_PROCESS_LIFETIME_HISTOGRAM_NAME =
        "GV_CONTENT_PROCESS_LIFETIME_MS";

    private TelemetryUtils.UptimeTimer mLifetimeTimer = null;

    public ContentConnection(
        @NonNull final ServiceAllocator allocator, @NonNull final PriorityLevel initialPriority) {
      super(allocator, GeckoProcessType.CONTENT, initialPriority);
    }

    @Override
    protected void onBinderConnected(final IBinder service) {
      mLifetimeTimer = new TelemetryUtils.UptimeTimer(TELEMETRY_PROCESS_LIFETIME_HISTOGRAM_NAME);
      super.onBinderConnected(service);
    }

    @Override
    protected void onReleaseResources() {
      if (mLifetimeTimer != null) {
        mLifetimeTimer.stop();
        mLifetimeTimer = null;
      }

      super.onReleaseResources();
    }
  }

  /** This class manages the state surrounding existing connections and their priorities. */
  private static final class ConnectionManager extends JNIObject {
    // Connections to non-content processes
    private final ArrayMap<GeckoProcessType, NonContentConnection> mNonContentConnections;
    // Mapping of pid to content process
    private final SimpleArrayMap<Integer, ContentConnection> mContentPids;
    // Set of initialized content process connections
    private final ArraySet<ContentConnection> mContentConnections;
    // Set of bound but uninitialized content connections
    private final ArraySet<ContentConnection> mNonStartedContentConnections;
    // Allocator for service IDs
    private final ServiceAllocator mServiceAllocator;
    private boolean mIsObservingNetwork = false;

    public ConnectionManager() {
      mNonContentConnections = new ArrayMap<GeckoProcessType, NonContentConnection>();
      mContentPids = new SimpleArrayMap<Integer, ContentConnection>();
      mContentConnections = new ArraySet<ContentConnection>();
      mNonStartedContentConnections = new ArraySet<ContentConnection>();
      mServiceAllocator = new ServiceAllocator();

      // Attach to native once JNI is ready.
      if (GeckoThread.isStateAtLeast(GeckoThread.State.JNI_READY)) {
        attachTo(this);
      } else {
        GeckoThread.queueNativeCallUntil(
            GeckoThread.State.JNI_READY, ConnectionManager.class, "attachTo", this);
      }
    }

    private void enableNetworkNotifications() {
      if (mIsObservingNetwork) {
        return;
      }

      mIsObservingNetwork = true;

      // Ensure that GeckoNetworkManager is monitoring network events so that we can
      // prioritize the socket process.
      ThreadUtils.runOnUiThread(
          () -> {
            GeckoNetworkManager.getInstance().enableNotifications();
          });

      observeNetworkNotifications();
    }

    @WrapForJNI(dispatchTo = "gecko")
    private static native void attachTo(ConnectionManager instance);

    @WrapForJNI(dispatchTo = "gecko")
    private native void observeNetworkNotifications();

    @WrapForJNI(calledFrom = "gecko")
    private void onBackground() {
      XPCOMEventTarget.runOnLauncherThread(() -> onAppBackgroundInternal());
    }

    @WrapForJNI(calledFrom = "gecko")
    private void onForeground() {
      XPCOMEventTarget.runOnLauncherThread(() -> onAppForegroundInternal());
    }

    @WrapForJNI(calledFrom = "gecko")
    private void onNetworkStateChange(final boolean isUp) {
      XPCOMEventTarget.runOnLauncherThread(() -> onNetworkStateChangeInternal(isUp));
    }

    @Override
    protected native void disposeNative();

    private void onAppBackgroundInternal() {
      XPCOMEventTarget.assertOnLauncherThread();

      for (final NonContentConnection conn : mNonContentConnections.values()) {
        conn.onAppBackground();
      }
    }

    private void onAppForegroundInternal() {
      XPCOMEventTarget.assertOnLauncherThread();

      for (final NonContentConnection conn : mNonContentConnections.values()) {
        conn.onAppForeground();
      }
    }

    private void onNetworkStateChangeInternal(final boolean isUp) {
      XPCOMEventTarget.assertOnLauncherThread();

      final SocketProcessConnection conn =
          (SocketProcessConnection) mNonContentConnections.get(GeckoProcessType.SOCKET);
      if (conn == null) {
        return;
      }

      conn.onNetworkStateChange(isUp);
    }

    private void removeContentConnection(@NonNull final ChildConnection conn) {
      if (!mContentConnections.remove(conn)) {
        throw new RuntimeException("Attempt to remove non-registered connection");
      }
      mNonStartedContentConnections.remove(conn);

      final int pid;

      try {
        pid = conn.getPid();
      } catch (final IncompleteChildConnectionException e) {
        // conn lost its binding before it was able to retrieve its pid. It follows that
        // mContentPids does not have an entry for this connection, so we can just return.
        return;
      }

      if (pid == INVALID_PID) {
        return;
      }

      final ChildConnection removed = mContentPids.remove(Integer.valueOf(pid));
      if (removed != null && removed != conn) {
        throw new RuntimeException(
            "Integrity error - connection mismatch for pid " + Integer.toString(pid));
      }
    }

    public void removeConnection(@NonNull final ChildConnection conn) {
      XPCOMEventTarget.assertOnLauncherThread();

      if (conn.getType() == GeckoProcessType.CONTENT) {
        removeContentConnection(conn);
        return;
      }

      final ChildConnection removed = mNonContentConnections.remove(conn.getType());
      if (removed != conn) {
        throw new RuntimeException(
            "Integrity error - connection mismatch for process type " + conn.getType().toString());
      }
    }

    /** Saves any state information that was acquired upon start completion. */
    public void onBindComplete(@NonNull final ChildConnection conn) {
      if (conn.getType() == GeckoProcessType.CONTENT) {
        final int pid = conn.getPid();
        if (pid == INVALID_PID) {
          throw new AssertionError(
              "PID is invalid even though our caller just successfully retrieved it after binding");
        }

        mContentPids.put(pid, (ContentConnection) conn);
      }
    }

    /** Retrieve the ChildConnection for an already running content process. */
    private ContentConnection getExistingContentConnection(@NonNull final Selector selector) {
      XPCOMEventTarget.assertOnLauncherThread();
      if (selector.getType() != GeckoProcessType.CONTENT) {
        throw new IllegalArgumentException("Selector is not for content!");
      }

      return mContentPids.get(selector.getPid());
    }

    /** Unconditionally create a new content connection for the specified priority. */
    private ContentConnection getNewContentConnection(@NonNull final PriorityLevel newPriority) {
      final ContentConnection result = new ContentConnection(mServiceAllocator, newPriority);
      mContentConnections.add(result);

      return result;
    }

    /** Retrieve the ChildConnection for an already running child process of any type. */
    public ChildConnection getExistingConnection(@NonNull final Selector selector) {
      XPCOMEventTarget.assertOnLauncherThread();

      final GeckoProcessType type = selector.getType();

      if (type == GeckoProcessType.CONTENT) {
        return getExistingContentConnection(selector);
      }

      return mNonContentConnections.get(type);
    }

    /**
     * Retrieve a ChildConnection for a content process for the purposes of starting. If there are
     * any preloaded content processes already running, we will use one of those. Otherwise we will
     * allocate a new ChildConnection.
     */
    private ChildConnection getContentConnectionForStart() {
      XPCOMEventTarget.assertOnLauncherThread();

      if (mNonStartedContentConnections.isEmpty()) {
        return getNewContentConnection(PriorityLevel.FOREGROUND);
      }

      final ChildConnection conn =
          mNonStartedContentConnections.removeAt(mNonStartedContentConnections.size() - 1);
      conn.setPriorityLevel(PriorityLevel.FOREGROUND);
      return conn;
    }

    /** Retrieve or create a new child process for the specified non-content process. */
    private ChildConnection getNonContentConnection(@NonNull final GeckoProcessType type) {
      XPCOMEventTarget.assertOnLauncherThread();
      if (type == GeckoProcessType.CONTENT) {
        throw new IllegalArgumentException("Content processes not supported by this method");
      }

      NonContentConnection connection = mNonContentConnections.get(type);
      if (connection == null) {
        if (type == GeckoProcessType.SOCKET) {
          connection = new SocketProcessConnection(mServiceAllocator);
        } else if (type == GeckoProcessType.GPU) {
          connection = new GpuProcessConnection(mServiceAllocator);
        } else {
          connection = new NonContentConnection(mServiceAllocator, type);
        }

        mNonContentConnections.put(type, connection);
      }

      return connection;
    }

    /** Retrieve a ChildConnection for the purposes of starting a new child process. */
    public ChildConnection getConnectionForStart(@NonNull final GeckoProcessType type) {
      if (type == GeckoProcessType.CONTENT) {
        return getContentConnectionForStart();
      }

      return getNonContentConnection(type);
    }

    /** Retrieve a ChildConnection for the purposes of preloading a new child process. */
    public ChildConnection getConnectionForPreload(@NonNull final GeckoProcessType type) {
      if (type == GeckoProcessType.CONTENT) {
        final ContentConnection conn = getNewContentConnection(PriorityLevel.BACKGROUND);
        mNonStartedContentConnections.add(conn);
        return conn;
      }

      return getNonContentConnection(type);
    }
  }

  private final ConnectionManager mConnections;

  private GeckoProcessManager() {
    mConnections = new ConnectionManager();
    mInstanceId = UUID.randomUUID().toString();
  }

  public void preload(final GeckoProcessType... types) {
    XPCOMEventTarget.launcherThread()
        .execute(
            () -> {
              for (final GeckoProcessType type : types) {
                final ChildConnection connection = mConnections.getConnectionForPreload(type);
                connection.bind();
              }
            });
  }

  public void crashChild(@NonNull final Selector selector) {
    XPCOMEventTarget.launcherThread()
        .execute(
            () -> {
              final ChildConnection conn = mConnections.getExistingConnection(selector);
              if (conn == null) {
                return;
              }

              conn.bind()
                  .accept(
                      proc -> {
                        try {
                          proc.crash();
                        } catch (final RemoteException e) {
                        }
                      });
            });
  }

  @WrapForJNI
  private static void shutdownProcess(final Selector selector) {
    XPCOMEventTarget.assertOnLauncherThread();
    final ChildConnection conn = INSTANCE.mConnections.getExistingConnection(selector);
    if (conn == null) {
      return;
    }

    conn.unbind();
  }

  @WrapForJNI
  private static void setProcessPriority(
      @NonNull final Selector selector,
      @NonNull final PriorityLevel priorityLevel,
      final int relativeImportance) {
    XPCOMEventTarget.runOnLauncherThread(
        () -> {
          final ChildConnection conn = INSTANCE.mConnections.getExistingConnection(selector);
          if (conn == null) {
            return;
          }

          conn.setPriorityLevel(priorityLevel, relativeImportance);
        });
  }

  @WrapForJNI
  private static GeckoResult<Integer> start(
      final GeckoProcessType type,
      final String[] args,
      final int prefsFd,
      final int prefMapFd,
      final int ipcFd,
      final int crashFd) {
    final GeckoResult<Integer> result = new GeckoResult<>();
    final StartInfo info =
        new StartInfo(
            type,
            GeckoThread.InitInfo.builder()
                .args(args)
                .userSerialNumber(System.getenv("MOZ_ANDROID_USER_SERIAL_NUMBER"))
                .extras(GeckoThread.getActiveExtras())
                .flags(filterFlagsForChild(GeckoThread.getActiveFlags()))
                .fds(
                    FileDescriptors.builder()
                        .prefs(prefsFd)
                        .prefMap(prefMapFd)
                        .ipc(ipcFd)
                        .crashReporter(crashFd)
                        .build())
                .build());

    XPCOMEventTarget.runOnLauncherThread(
        () -> {
          INSTANCE
              .start(info)
              .accept(result::complete, result::completeExceptionally)
              .finally_(info.pfds::close);
        });

    return result;
  }

  private static int filterFlagsForChild(final int flags) {
    return flags & GeckoThread.FLAG_ENABLE_NATIVE_CRASHREPORTER;
  }

  private static class StartInfo {
    final GeckoProcessType type;
    final String crashHandler;
    final GeckoThread.InitInfo init;

    final ParcelFileDescriptors pfds;

    private StartInfo(final GeckoProcessType type, final GeckoThread.InitInfo initInfo) {
      this.type = type;
      this.init = initInfo;
      crashHandler =
          GeckoAppShell.getCrashHandlerService() != null
              ? GeckoAppShell.getCrashHandlerService().getName()
              : null;
      // The native side owns the File Descriptors so we cannot call adopt here.
      pfds = ParcelFileDescriptors.from(initInfo.fds);
    }
  }

  private static final int MAX_RETRIES = 3;

  private GeckoResult<Integer> start(final StartInfo info) {
    return start(info, new ArrayList<>());
  }

  private GeckoResult<Integer> retry(
      final StartInfo info, final List<Throwable> retryLog, final Throwable error) {
    retryLog.add(error);

    if (error instanceof StartException) {
      final StartException startError = (StartException) error;
      if (startError.errorCode == IChildProcess.STARTED_BUSY) {
        // This process is owned by a different runtime, so we can't use
        // it. We will keep retrying indefinitely until we find a non-busy process.
        // Note: this strategy is pretty bad, we go through each process in
        // sequence until one works, the multiple runtime case is test-only
        // for now, so that's ok. We can improve on this if we eventually
        // end up needing something fancier.
        return start(info, retryLog);
      }
    }

    // If we couldn't unbind there's something very wrong going on and we bail
    // immediately.
    if (retryLog.size() >= MAX_RETRIES || error instanceof UnbindException) {
      return GeckoResult.fromException(fromRetryLog(retryLog));
    }

    return start(info, retryLog);
  }

  private String serializeLog(final List<Throwable> retryLog) {
    if (retryLog == null || retryLog.size() == 0) {
      return "Empty log.";
    }

    final StringBuilder message = new StringBuilder();

    for (final Throwable error : retryLog) {
      if (error instanceof UnbindException) {
        message.append("Could not unbind: ");
      } else if (error instanceof StartException) {
        message.append("Cannot restart child: ");
      } else {
        message.append("Error while binding: ");
      }
      message.append(error);
      message.append(";");
    }

    return message.toString();
  }

  private RuntimeException fromRetryLog(final List<Throwable> retryLog) {
    return new RuntimeException(serializeLog(retryLog), retryLog.get(retryLog.size() - 1));
  }

  private GeckoResult<Integer> start(final StartInfo info, final List<Throwable> retryLog) {
    return startInternal(info).then(GeckoResult::fromValue, error -> retry(info, retryLog, error));
  }

  private static class StartException extends RuntimeException {
    public final int errorCode;

    public StartException(final int errorCode, final int pid) {
      super("Could not start process, errorCode: " + errorCode + " PID: " + pid);
      this.errorCode = errorCode;
    }
  }

  private GeckoResult<Integer> startInternal(final StartInfo info) {
    XPCOMEventTarget.assertOnLauncherThread();

    final ChildConnection connection = mConnections.getConnectionForStart(info.type);
    return connection
        .bind()
        .map(
            child -> {
              final int result =
                  child.start(
                      this,
                      mInstanceId,
                      info.init.args,
                      info.init.extras,
                      info.init.flags,
                      info.init.userSerialNumber,
                      info.crashHandler,
                      info.pfds.prefs,
                      info.pfds.prefMap,
                      info.pfds.ipc,
                      info.pfds.crashReporter);
              if (result == IChildProcess.STARTED_OK) {
                return connection.getPid();
              } else {
                throw new StartException(result, connection.getPid());
              }
            })
        .then(GeckoResult::fromValue, error -> handleBindError(connection, error));
  }

  private GeckoResult<Integer> handleBindError(
      final ChildConnection connection, final Throwable error) {
    return connection
        .unbind()
        .then(
            unused -> GeckoResult.fromException(error),
            unbindError -> GeckoResult.fromException(new UnbindException(unbindError)));
  }

  private static class UnbindException extends RuntimeException {
    public UnbindException(final Throwable cause) {
      super(cause);
    }
  }
} // GeckoProcessManager