summaryrefslogtreecommitdiff
path: root/fakeadbserver/src/main/java/com/android/fakeadbserver/FakeAdbServer.java
blob: 3b48e0eef10f5ab0ea16a0d97d58c069076a2ed4 (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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.fakeadbserver;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.annotations.concurrency.GuardedBy;
import com.android.fakeadbserver.devicecommandhandlers.AbbCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.AbbExecCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.DeviceCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.FakeSyncCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.JdwpCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.ReverseForwardCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.TrackAppCommandHandler;
import com.android.fakeadbserver.devicecommandhandlers.TrackJdwpCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.FeaturesCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.ForwardCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.GetDevPathCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.GetSerialNoCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.GetStateCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.HostCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.HostFeaturesCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.KillCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.KillForwardAllCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.KillForwardCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.ListDevicesCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.ListForwardCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.MdnsCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.NetworkConnectCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.NetworkDisconnectCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.PairCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.TrackDevicesCommandHandler;
import com.android.fakeadbserver.hostcommandhandlers.VersionCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.ActivityManagerCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.CatCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.CmdCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.DumpsysCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.EchoCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.GetPropCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.LogcatCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.PackageManagerCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.PingCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.RmCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.SetPropCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.ShellProtocolEchoCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.StatCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.WindowManagerCommandHandler;
import com.android.fakeadbserver.shellcommandhandlers.WriteNoStopCommandHandler;
import com.android.fakeadbserver.statechangehubs.DeviceStateChangeHub;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/** See {@code FakeAdbServerTest#testInteractiveServer()} for example usage. */
public final class FakeAdbServer implements AutoCloseable {

    private final ServerSocketChannel mServerSocket;

    private InetSocketAddress mServerSocketLocalAddress;

    /**
     * The {@link CommandHandler}s have internal state. To allow for reentrancy, instead of using a
     * pre-allocated {@link CommandHandler} object, the constructor is passed in and a new object is
     * created as-needed.
     */
    private final Map<String, Supplier<HostCommandHandler>> mHostCommandHandlers = new HashMap<>();

    private final List<DeviceCommandHandler> mHandlers = new ArrayList<>();

    private final Map<String, DeviceState> mDevices = new HashMap<>();

    // Device ip address to DeviceState. Device may or may not currently be connected to adb.
    private final Map<String, DeviceState> mNetworkDevices = new HashMap<>();

    private final Set<MdnsService> mMdnsServices = new HashSet<>();

    private final DeviceStateChangeHub mDeviceChangeHub = new DeviceStateChangeHub();

    private final AtomicInteger mLastTransportId = new AtomicInteger();

    // This is the executor for accepting incoming connections as well as handling the execution of
    // the commands over the connection. There is one task for accepting connections, and multiple
    // tasks to handle the execution of the commands.
    private final ExecutorService mThreadPoolExecutor =
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder()
                            .setNameFormat("fake-adb-server-connection-pool-%d")
                            .build());

    private Future<?> mConnectionHandlerTask = null;

    // All "external" server controls are synchronized through a central executor, much like the EDT
    // thread in Swing.
    private final ExecutorService mMainServerThreadExecutor = Executors.newSingleThreadExecutor();

    private volatile boolean mServerKeepAccepting = false;

    @GuardedBy("this")
    private volatile Future<?> mStopRequestTask = null;

    private Set<String> mFeatures;
    private static final Set<String> DEFAULT_FEATURES =
            Collections.unmodifiableSet(
                    new HashSet<>(
                            Arrays.asList(
                                    "push_sync",
                                    "fixed_push_mkdir",
                                    "shell_v2",
                                    "apex",
                                    "stat_v2",
                                    "cmd",
                                    "abb",
                                    "abb_exec")));


    private FakeAdbServer() throws IOException {
        this(DEFAULT_FEATURES);
    }

    private FakeAdbServer(Set<String> features) throws IOException {
        mServerSocket = ServerSocketChannel.open();
        mFeatures = features;
    }

    public void start() throws IOException {
        assert mConnectionHandlerTask == null; // Do not reuse the server.

        mServerSocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
        mServerSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        mServerSocketLocalAddress = (InetSocketAddress) mServerSocket.getLocalAddress();
        mServerKeepAccepting = true;

        mConnectionHandlerTask =
                mThreadPoolExecutor.submit(
                        () -> {
                            while (mServerKeepAccepting) {
                                try {
                                    // Socket can not be closed in finally block, because a separate
                                    // thread will
                                    // read from the socket. Closing the socket leads to a race
                                    // condition.
                                    //noinspection SocketOpenedButNotSafelyClosed
                                    SocketChannel socket = mServerSocket.accept();
                                    ConnectionHandler handler = new ConnectionHandler(this, socket);
                                    mThreadPoolExecutor.execute(handler);
                                } catch (IOException ignored) {
                                    // close() is called in a separate thread, and will cause
                                    // accept() to throw an
                                    // exception if closed here.
                                }
                            }
                        });
    }

    @NonNull
    public InetAddress getInetAddress() {
        return mServerSocketLocalAddress.getAddress();
    }

    public int getPort() {
        return mServerSocketLocalAddress.getPort();
    }

    /** This method allows for the caller thread to wait until the server shuts down. */
    public boolean awaitServerTermination() throws InterruptedException {
        return awaitServerTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
    }

    public boolean awaitServerTermination(long time, TimeUnit unit) throws InterruptedException {
        return mMainServerThreadExecutor.awaitTermination(time, unit)
                && mThreadPoolExecutor.awaitTermination(time, unit);
    }

    /**
     * Stops the server. This method records the first stop request and all subsequent ones will get
     * that value. This ensures no task submissions are attempted after {@link
     * #mMainServerThreadExecutor} is shut down.
     *
     * @return a {@link Future} if the caller needs to wait until the server is stopped.
     */
    public synchronized Future<?> stop() {
        if (mStopRequestTask == null) {
            mStopRequestTask =
                    mMainServerThreadExecutor.submit(
                            () -> {
                                if (!mServerKeepAccepting) {
                                    return;
                                }
                                mServerKeepAccepting = false;

                                mDeviceChangeHub.stop();
                                mDevices.forEach((id, device) -> device.stop());

                                mConnectionHandlerTask.cancel(true);
                                try {
                                    mServerSocket.close();
                                } catch (IOException ignored) {
                                }

                                // Note: Use "shutdownNow()" to ensure threads of long running tasks
                                // are interrupted, as opposed
                                // to merely waiting for the tasks to finish. This is because
                                // mThreadPoolExecutor is used to
                                // run CommandHandler implementations, and some of them (e.g.
                                // TrackJdwpCommandHandler) wait
                                // indefinitely on queues and expect to be interrupted as a signal
                                // to terminate.
                                mThreadPoolExecutor.shutdownNow();
                                mMainServerThreadExecutor.shutdown();
                            });
        }
        return mStopRequestTask;
    }

    @Override
    public void close() throws Exception {
        try {
            stop().get();
        } catch (InterruptedException ignored) {
            // Catch InterruptedException as specified by JavaDoc.
        } catch (RejectedExecutionException ignored) {
            // The server has already been closed once
        }
    }

    /**
     * Grabs the DeviceStateChangeHub from the server. This should only be used for implementations
     * for handlers that inherit from {@link CommandHandler}. The purpose of the hub is to propagate
     * server events to existing connections with the server.
     *
     * <p>For example, if {@link #connectDevice(DeviceState)} is called, an event will be sent
     * through the {@link DeviceStateChangeHub} to all open connections waiting on
     * host:track-devices messages.
     */
    @NonNull
    public DeviceStateChangeHub getDeviceChangeHub() {
        return mDeviceChangeHub;
    }

    /**
     * Connects a device to the ADB server. Must be called on the EDT/main thread.
     *
     * @param deviceId           is the unique device ID of the device
     * @param manufacturer       is the manufacturer name of the device
     * @param deviceModel        is the model name of the device
     * @param release            is the Android OS version of the device
     * @param sdk                is the SDK version of the device
     * @param cpuAbi             is the ABI of the device CPU
     * @param properties         is the device properties
     * @param hostConnectionType is the simulated connection type to the device @return the future
     * @return a future to allow synchronization of the side effects of the call
     */
    public Future<DeviceState> connectDevice(
            @NonNull String deviceId,
            @NonNull String manufacturer,
            @NonNull String deviceModel,
            @NonNull String release,
            @NonNull String sdk,
            @NonNull String cpuAbi,
            @NonNull Map<String, String> properties,
            @NonNull DeviceState.HostConnectionType hostConnectionType) {
        DeviceState device =
                new DeviceState(
                        this,
                        deviceId,
                        manufacturer,
                        deviceModel,
                        release,
                        sdk,
                        cpuAbi,
                        properties,
                        hostConnectionType,
                        newTransportId());
        return connectDevice(device);
    }

    @NonNull
    private Future<DeviceState> connectDevice(@NonNull DeviceState device) {
        String deviceId = device.getDeviceId();
        if (mConnectionHandlerTask == null) {
            assert !mDevices.containsKey(deviceId);
            mDevices.put(deviceId, device);
            return Futures.immediateFuture(device);
        } else {
            return mMainServerThreadExecutor.submit(
                    () -> {
                        assert !mDevices.containsKey(deviceId);
                        mDevices.put(deviceId, device);
                        mDeviceChangeHub.deviceListChanged(mDevices.values());
                        return device;
                    });
        }
    }

    public Future<DeviceState> connectDevice(
            @NonNull String deviceId,
            @NonNull String manufacturer,
            @NonNull String deviceModel,
            @NonNull String release,
            @NonNull String sdk,
            @NonNull DeviceState.HostConnectionType hostConnectionType) {
        return connectDevice(
                deviceId,
                manufacturer,
                deviceModel,
                release,
                sdk,
                "x86_64",
                Collections.emptyMap(),
                hostConnectionType);
    }

    void addDevice(DeviceStateConfig deviceConfig) {
        DeviceState device = new DeviceState(this, this.newTransportId(), deviceConfig);
        this.mDevices.put(device.getDeviceId(), device);
    }

    public void registerNetworkDevice(
            @NonNull String address,
            @NonNull String deviceId,
            @NonNull String manufacturer,
            @NonNull String deviceModel,
            @NonNull String release,
            @NonNull String sdk,
            @NonNull DeviceState.HostConnectionType hostConnectionType) {
        DeviceState device =
                new DeviceState(
                        this,
                        deviceId,
                        manufacturer,
                        deviceModel,
                        release,
                        sdk,
                        "x86_64",
                        Collections.emptyMap(),
                        hostConnectionType,
                        newTransportId());
        mNetworkDevices.put(address, device);
    }

    public @NonNull Future<DeviceState> connectNetworkDevice(String address) {
        DeviceState device = mNetworkDevices.get(address);
        if (device != null) {
            return connectDevice(device);
        } else {
            return Futures.immediateFailedFuture(new Exception("Device " + address + " not found"));
        }
    }

    public @NonNull Future<?> disconnectNetworkDevice(String address) {
        DeviceState device = mNetworkDevices.get(address);
        if (device != null) {
            return disconnectDevice(device.getDeviceId());
        } else {
            // The real adb will disconnect ongoing sessions, but this is an edge case.
            return Futures.immediateFuture(null);
        }
    }

    public Future<?> addMdnsService(@NonNull MdnsService service) {
        if (mConnectionHandlerTask == null) {
            assert !mMdnsServices.contains(service);
            mMdnsServices.add(service);
            return Futures.immediateFuture(null);
        } else {
            return mMainServerThreadExecutor.submit(
                    () -> {
                        assert !mMdnsServices.contains(service);
                        mMdnsServices.add(service);
                        return null;
                    });
        }
    }

    @NonNull
    public Future<?> removeMdnsService(@NonNull MdnsService service) {
        if (mConnectionHandlerTask == null) {
            mMdnsServices.remove(service);
            return Futures.immediateFuture(null);
        } else {
            return mMainServerThreadExecutor.submit(
                    () -> {
                        mMdnsServices.remove(service);
                        return null;
                    });
        }
    }

    /**
     * Thread-safely gets a copy of the mDNS service list. This is useful for asynchronous handlers.
     */
    @NonNull
    public Future<List<MdnsService>> getMdnsServicesCopy() {
        return mMainServerThreadExecutor.submit(() -> new ArrayList<>(mMdnsServices));
    }

    private int newTransportId() {
        return mLastTransportId.incrementAndGet();
    }

    /**
     * Removes a device from the ADB server. Must be called on the EDT/main thread.
     *
     * @param deviceId is the unique device ID of the device
     * @return a future to allow synchronization of the side effects of the call
     */
    public Future<?> disconnectDevice(@NonNull String deviceId) {
        return mMainServerThreadExecutor.submit(
                () -> {
                    assert mDevices.containsKey(deviceId);
                    DeviceState removedDevice = mDevices.remove(deviceId);
                    if (removedDevice != null) {
                        removedDevice.stop();
                    }
                    mDeviceChangeHub.deviceListChanged(mDevices.values());
                });
    }

    /**
     * Thread-safely gets a copy of the device list. This is useful for asynchronous handlers.
     */
    @NonNull
    public Future<List<DeviceState>> getDeviceListCopy() {
        return mMainServerThreadExecutor.submit(() -> new ArrayList<>(mDevices.values()));
    }

    public HostCommandHandler getHostCommandHandler(String command) {
        Supplier<HostCommandHandler> supplier = mHostCommandHandlers.get(command);
        if (supplier != null) {
            return supplier.get();
        }
        return null;
    }

    public List<DeviceCommandHandler> getHandlers() {
        return mHandlers;
    }

    @NonNull
    public FakeAdbServerConfig getCurrentConfig() {
        FakeAdbServerConfig config = new FakeAdbServerConfig();

        config.getHostHandlers().putAll(mHostCommandHandlers);
        config.getDeviceHandlers().addAll(mHandlers);
        config.getMdnsServices().addAll(mMdnsServices);
        mDevices.forEach(
                (serial, device) -> {
                    DeviceStateConfig deviceConfig = device.getConfig();
                    config.getDevices().add(deviceConfig);
                });

        return config;
    }

    public static final class Builder {

        @NonNull private final FakeAdbServer mServer;

        @Nullable private FakeAdbServerConfig mConfig;

        public Builder() throws IOException {
            mServer = new FakeAdbServer();
        }

        /** Used to restore a {@link FakeAdbServer} instance from a previously running instance */
        public Builder setConfig(@NonNull FakeAdbServerConfig config) {
            mConfig = config;
            return this;
        }

        /**
         * Sets the handler for a specific host ADB command. This only needs to be called if the
         * test author requires additional functionality that is not provided by the default {@link
         * CommandHandler}s.
         *
         * @param command            The ADB protocol string of the command.
         * @param handlerConstructor The constructor for the handler.
         */
        @NonNull
        public Builder setHostCommandHandler(
                @NonNull String command, @NonNull Supplier<HostCommandHandler> handlerConstructor) {
            mServer.mHostCommandHandlers.put(command, handlerConstructor);
            return this;
        }

        /**
         * Adds the handler for a device command. Handlers added last take priority over existing
         * handlers.
         */
        @NonNull
        public Builder addDeviceHandler(@NonNull DeviceCommandHandler handler) {
            mServer.mHandlers.add(0, handler);
            return this;
        }

        /**
         * Installs the default set of host command handlers. The user may override any command
         * handler.
         */
        @NonNull
        public Builder installDefaultCommandHandlers() {
            setHostCommandHandler(KillCommandHandler.COMMAND, KillCommandHandler::new);
            setHostCommandHandler(
                    ListDevicesCommandHandler.COMMAND, ListDevicesCommandHandler::new);
            setHostCommandHandler(
                    ListDevicesCommandHandler.LONG_COMMAND, () -> new ListDevicesCommandHandler(true));
            setHostCommandHandler(
                    TrackDevicesCommandHandler.COMMAND, TrackDevicesCommandHandler::new);
            setHostCommandHandler(
                    TrackDevicesCommandHandler.LONG_COMMAND,
                    () -> new TrackDevicesCommandHandler(true));
            setHostCommandHandler(ForwardCommandHandler.COMMAND, ForwardCommandHandler::new);
            setHostCommandHandler(KillForwardCommandHandler.COMMAND,
                    KillForwardCommandHandler::new);
            setHostCommandHandler(
                    KillForwardAllCommandHandler.COMMAND, KillForwardAllCommandHandler::new);
            setHostCommandHandler(
                    ListForwardCommandHandler.COMMAND, ListForwardCommandHandler::new);
            setHostCommandHandler(FeaturesCommandHandler.COMMAND, FeaturesCommandHandler::new);
            setHostCommandHandler(
                    HostFeaturesCommandHandler.COMMAND, HostFeaturesCommandHandler::new);
            setHostCommandHandler(VersionCommandHandler.COMMAND, VersionCommandHandler::new);
            setHostCommandHandler(MdnsCommandHandler.COMMAND, MdnsCommandHandler::new);
            setHostCommandHandler(PairCommandHandler.COMMAND, PairCommandHandler::new);
            setHostCommandHandler(GetStateCommandHandler.COMMAND, GetStateCommandHandler::new);
            setHostCommandHandler(GetSerialNoCommandHandler.COMMAND, GetSerialNoCommandHandler::new);
            setHostCommandHandler(GetDevPathCommandHandler.COMMAND, GetDevPathCommandHandler::new);
            setHostCommandHandler(
                    NetworkConnectCommandHandler.COMMAND, NetworkConnectCommandHandler::new);
            setHostCommandHandler(
                    NetworkDisconnectCommandHandler.COMMAND, NetworkDisconnectCommandHandler::new);

            addDeviceHandler(new TrackJdwpCommandHandler());
            addDeviceHandler(new TrackAppCommandHandler());
            addDeviceHandler(new FakeSyncCommandHandler());
            addDeviceHandler(new ReverseForwardCommandHandler());

            addDeviceHandler(new PingCommandHandler(ShellProtocolType.EXEC));
            addDeviceHandler(new RmCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new LogcatCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new GetPropCommandHandler(ShellProtocolType.EXEC));
            addDeviceHandler(new GetPropCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new GetPropCommandHandler(ShellProtocolType.SHELL_V2));
            addDeviceHandler(new SetPropCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new WriteNoStopCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new PackageManagerCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new WindowManagerCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new CmdCommandHandler(ShellProtocolType.EXEC));
            addDeviceHandler(new CmdCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new DumpsysCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new CatCommandHandler(ShellProtocolType.EXEC));
            addDeviceHandler(new CatCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new CatCommandHandler(ShellProtocolType.SHELL_V2));
            addDeviceHandler(new EchoCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new ShellProtocolEchoCommandHandler());
            addDeviceHandler(new AbbCommandHandler());
            addDeviceHandler(new AbbExecCommandHandler());
            addDeviceHandler(new ActivityManagerCommandHandler(ShellProtocolType.SHELL));
            addDeviceHandler(new ActivityManagerCommandHandler(ShellProtocolType.SHELL_V2));
            addDeviceHandler(new JdwpCommandHandler());
            addDeviceHandler(new StatCommandHandler(ShellProtocolType.SHELL));

            return this;
        }

        @NonNull
        public FakeAdbServer build() {
            if (mConfig != null) {
                mConfig.getHostHandlers().forEach(this::setHostCommandHandler);
                mConfig.getDeviceHandlers().forEach(this::addDeviceHandler);
                mConfig.getDevices().forEach(mServer::addDevice);
                mConfig.getMdnsServices().forEach(mServer::addMdnsService);
            }
            return mServer;
        }

        public void setFeatures(@NonNull Set<String> features) {
            mServer.setFeatures(features);
        }
    }

    public Set<String> getFeatures() {
        return mFeatures;
    }

    public void setFeatures(Set<String> features) {
        mFeatures = features;
    }
}