Repository navigation
Expand file tree
/
Copy pathVirtualMachine.java
More file actions
2803 lines (2568 loc) · 114 KB
/
Copy pathVirtualMachine.java
File metadata and controls
2803 lines (2568 loc) · 114 KB
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2021 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 android.system.virtualmachine;
import static android.os.ParcelFileDescriptor.AutoCloseInputStream;
import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
import static android.system.virtualmachine.VirtualMachineCallback.ERROR_PAYLOAD_CHANGED;
import static android.system.virtualmachine.VirtualMachineCallback.ERROR_PAYLOAD_INVALID_CONFIG;
import static android.system.virtualmachine.VirtualMachineCallback.ERROR_PAYLOAD_VERIFICATION_FAILED;
import static android.system.virtualmachine.VirtualMachineCallback.ERROR_UNKNOWN;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_CRASH;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_HANGUP;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_INFRASTRUCTURE_ERROR;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_KILLED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_REBOOT;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_SHUTDOWN;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_START_FAILED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_UNKNOWN;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_VIRTUALIZATION_SERVICE_DIED;
import static java.util.Objects.requireNonNull;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.WorkerThread;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.system.ErrnoException;
import android.system.OsConstants;
import android.system.virtualizationcommon.DeathReason;
import android.system.virtualizationcommon.ErrorCode;
import android.system.virtualizationcommon.IEncryptedStoreKEK;
import android.system.virtualizationservice.IVirtualMachine;
import android.system.virtualizationservice.IVirtualMachineCallback;
import android.system.virtualizationservice.IVirtualizationService;
import android.system.virtualizationservice.InputDevice;
import android.system.virtualizationservice.PartitionType;
import android.system.virtualizationservice.VirtualMachineAppConfig;
import android.system.virtualizationservice.VirtualMachineRawConfig;
import android.system.virtualizationservice.VirtualMachineState;
import android.util.JsonReader;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import com.android.internal.annotations.GuardedBy;
import libcore.io.IoBridge;
import libcore.io.IoUtils;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;
import java.util.zip.ZipFile;
/**
* Represents an VM instance, with its own configuration and state. Instances are persistent and are
* created or retrieved via {@link VirtualMachineManager}.
*
* <p>The {@link #run} method actually starts up the VM and allows the payload code to execute. It
* will continue until it exits or {@link #stop} is called. Updates on the state of the VM can be
* received using {@link #setCallback}. The app can communicate with the VM using {@link
* #connectToVsockServer} or {@link #connectVsock}.
*
* <p>The payload code running inside the VM has access to a set of native APIs; see the <a
* href="https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/Virtualization/libs/libvm_payload/README.md">README
* file</a> for details.
*
* <p>Each VM has a unique secret, computed from the APK that contains the code running in it, the
* VM configuration, and a random per-instance salt. The secret can be accessed by the payload code
* running inside the VM (using {@code AVmPayload_getVmInstanceSecret}) but is not made available
* outside it.
*
* @hide
*/
@SystemApi
public class VirtualMachine implements AutoCloseable {
/** The permission needed to create or run a virtual machine. */
public static final String MANAGE_VIRTUAL_MACHINE_PERMISSION =
"android.permission.MANAGE_VIRTUAL_MACHINE";
/**
* The permission needed to create a virtual machine with more advanced configuration options.
*/
public static final String USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION =
"android.permission.USE_CUSTOM_VIRTUAL_MACHINE";
/**
* The lowest port number that can be used to communicate with the virtual machine payload.
*
* @see #connectToVsockServer
* @see #connectVsock
*/
@SuppressLint("MinMaxConstant") // Won't change: see man 7 vsock.
public static final long MIN_VSOCK_PORT = 1024;
/**
* The highest port number that can be used to communicate with the virtual machine payload.
*
* @see #connectToVsockServer
* @see #connectVsock
*/
@SuppressLint("MinMaxConstant") // Won't change: see man 7 vsock.
public static final long MAX_VSOCK_PORT = (1L << 32) - 1;
private ParcelFileDescriptor mTouchSock;
private ParcelFileDescriptor mKeySock;
private ParcelFileDescriptor mMouseSock;
private ParcelFileDescriptor mSwitchesSock;
private ParcelFileDescriptor mTrackpadSock;
private enum InputEventType {
TOUCH,
MOUSE,
TRACKPAD
}
private BlockingQueue<Pair<InputEventType, MotionEvent>> mInputEventQueue =
new LinkedBlockingQueue<>();
/**
* Status of a virtual machine
*
* @hide
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(
prefix = "STATUS_",
value = {STATUS_STOPPED, STATUS_RUNNING, STATUS_DELETED})
public @interface Status {}
/** The virtual machine has just been created, or {@link #stop} was called on it. */
public static final int STATUS_STOPPED = 0;
/** The virtual machine is running. */
public static final int STATUS_RUNNING = 1;
@NonNull
private Float touchScale = 1F;
/**
* The virtual machine has been deleted. This is an irreversible state. Once a virtual machine
* is deleted all its secrets are permanently lost, and it cannot be run. A new virtual machine
* with the same name and config may be created, with new and different secrets.
*/
public static final int STATUS_DELETED = 2;
private static final String TAG = "VirtualMachine";
/** Name of the directory under the files directory where all VMs created for the app exist. */
private static final String VM_DIR = "vm";
/** Name of the persisted config file for a VM. */
private static final String CONFIG_FILE = "config.xml";
/** Name of the instance image file for a VM. (Not implemented) */
private static final String INSTANCE_IMAGE_FILE = "instance.img";
/** Name of the file for a VM containing Id. */
private static final String INSTANCE_ID_FILE = "instance_id";
/** Name of the idsig file for a VM */
private static final String IDSIG_FILE = "idsig";
/** Name of the idsig files for extra APKs. */
private static final String EXTRA_IDSIG_FILE_PREFIX = "extra_idsig_";
/** Name of the idsig files for tenants APKs. */
private static final String TENANT_IDSIG_FILE_PREFIX = "tenant_idsig_";
/** Size of the instance image. 10 MB. */
private static final long INSTANCE_FILE_SIZE = 10 * 1024 * 1024;
/** Name of the file backing the encrypted storage */
private static final String ENCRYPTED_STORE_FILE = "storage.img";
/** Name of the file with KEK used to setup encrypted store */
private static final String ENCRYPTED_STORE_KEK_FILE = "encrypted_store_kek.bin";
// Both binders are for virtmgr, and not virtualizationservice
private IBinder.DeathRecipient mVSDeathRecipient;
private IBinder.DeathRecipient mVMDeathRecipient;
/** The package which owns this VM. */
@NonNull private final String mPackageName;
/** Name of this VM within the package. The name should be unique in the package. */
@NonNull private final String mName;
/** Path to the directory containing all the files related to this VM. */
@NonNull private final File mVmRootPath;
/**
* Path to the config file for this VM. The config file is where the configuration is persisted.
*/
@NonNull private final File mConfigFilePath;
/** Path to the instance image file for this VM. */
@NonNull private final File mInstanceFilePath;
/** Path to the idsig file for this VM. */
@NonNull private final File mIdsigFilePath;
/** File that backs the encrypted storage - Will be null if not enabled. */
@Nullable private final File mEncryptedStoreFilePath;
/**
* File that stores KEK used to setup encrypted store.
*
* <p>Is only set iff encrypted store is enabled in the {@link
* VirtualMachineConfig#ENCRYPTED_STORE_MODE_KEK_ON_CE} mode.
*/
@Nullable private final EncryptedStoreKEK mEncryptedStoreKEK;
/** File that contains the Id. This is NULL iff FEATURE_LLPVM is disabled */
@Nullable private final File mInstanceIdPath;
/**
* Unmodifiable list of extra apks. Apks are specified by the vm config, and corresponding
* idsigs are to be generated.
*/
@NonNull private final List<ApkSpec> mExtraApks;
/** Unmodifiable list of tenant apks. */
@NonNull private final List<ApkSpec> mTenantApks;
@NonNull private final Executor mMemoryCallbackExecutor = Executors.newSingleThreadExecutor();
private class MemoryManagementCallbacks implements ComponentCallbacks2 {
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {}
@Override
public void onLowMemory() {}
@Override
public void onTrimMemory(int level) {
final int currentLevel = level;
mMemoryCallbackExecutor.execute(
() -> {
int percent = 10;
if (currentLevel >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
percent = 30;
}
if (currentLevel >= ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) {
percent = 50;
}
setMemoryBalloonByPercent(percent);
Log.d(
TAG,
"onTrimMemory: Completed setMemoryBalloonByPercent on thread: "
+ Thread.currentThread().getName());
});
}
}
private final MemoryManagementCallbacks mMemoryManagementCallbacks;
@NonNull private final Context mContext;
// A note on lock ordering:
// You can take mLock while holding VirtualMachineManager.sCreateLock, but not vice versa.
// We never take any other lock while holding mCallbackLock; therefore you can
// take mCallbackLock while holding any other lock.
/** Lock protecting our mutable state (other than callbacks). */
private final Object mLock = new Object();
/** Lock protecting callbacks. */
private final Object mCallbackLock = new Object();
private final boolean mVmOutputCaptured;
private final boolean mVmConsoleInputSupported;
private final boolean mConnectVmConsole;
private final Executor mConsoleExecutor = Executors.newSingleThreadExecutor();
private ExecutorService mInputEventExecutor;
/** Running instance of virtmgr that hosts VirtualizationService for this VM. */
@GuardedBy("mLock")
@Nullable
private VirtualizationService mVirtualizationService;
/** The configuration that is currently associated with this VM. */
@GuardedBy("mLock")
@NonNull
private VirtualMachineConfig mConfig;
/** Handle to the "running" VM. */
@GuardedBy("mLock")
@Nullable
private IVirtualMachine mVirtualMachine;
/** CID of the "running" VM. */
@GuardedBy("mLock")
private int mCid = -1;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mConsoleOutReader;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mConsoleOutWriter;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mConsoleInReader;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mConsoleInWriter;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mTeeConsoleOutReader;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mTeeConsoleOutWriter;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mPtyFd;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mPtsFd;
@GuardedBy("mLock")
@Nullable
private String mPtsName;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mLogReader;
@GuardedBy("mLock")
@Nullable
private ParcelFileDescriptor mLogWriter;
@GuardedBy("mLock")
private boolean mWasDeleted = false;
@GuardedBy("mLock")
private boolean mStopHandled = false;
/** The registered callback */
@GuardedBy("mCallbackLock")
@Nullable
private VirtualMachineCallback mCallback;
/** The executor on which the callback will be executed */
@GuardedBy("mCallbackLock")
@Nullable
private Executor mCallbackExecutor;
private static class ApkSpec {
public final File apk;
public final File idsig;
ApkSpec(File apk, File idsig) {
this.apk = apk;
this.idsig = idsig;
}
}
static {
System.loadLibrary("virtualmachine_jni");
}
private VirtualMachine(
@NonNull Context context,
@NonNull String name,
@NonNull VirtualMachineConfig config,
@NonNull VirtualizationService service)
throws VirtualMachineException {
mPackageName = context.getPackageName();
mName = requireNonNull(name, "Name must not be null");
mConfig = requireNonNull(config, "Config must not be null");
File thisVmDir = getVmDir(context, mName);
mVmRootPath = thisVmDir;
mConfigFilePath = new File(thisVmDir, CONFIG_FILE);
try {
mInstanceIdPath =
(service.getBinder()
.isFeatureEnabled(IVirtualizationService.FEATURE_LLPVM_CHANGES))
? new File(thisVmDir, INSTANCE_ID_FILE)
: null;
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
mInstanceFilePath = new File(thisVmDir, INSTANCE_IMAGE_FILE);
mIdsigFilePath = new File(thisVmDir, IDSIG_FILE);
mExtraApks = setupExtraApks(context, config, thisVmDir);
mTenantApks = setupTenantApks(context, config, thisVmDir);
mContext = context;
mEncryptedStoreFilePath =
(config.isEncryptedStorageEnabled())
? new File(thisVmDir, ENCRYPTED_STORE_FILE)
: null;
if (config.getEncryptedStoreMode() == VirtualMachineConfig.ENCRYPTED_STORE_MODE_KEK_ON_CE) {
mEncryptedStoreKEK = new EncryptedStoreKEK(context, mName);
} else {
mEncryptedStoreKEK = null;
}
mVmOutputCaptured = config.isVmOutputCaptured();
mVmConsoleInputSupported = config.isVmConsoleInputSupported();
mConnectVmConsole = Build.isDebuggable() && config.isConnectVmConsole();
if (mConnectVmConsole != config.isConnectVmConsole()) {
Log.w(TAG, "Ignored 'connectVmConsole' option on non-debuggable build");
}
VirtualMachineCustomImageConfig customImageConfig;
customImageConfig = config.getCustomImageConfig();
if (customImageConfig == null || customImageConfig.useAutoMemoryBalloon()) {
mMemoryManagementCallbacks = new MemoryManagementCallbacks();
} else {
mMemoryManagementCallbacks = null;
}
}
/**
* Creates a virtual machine from an {@link VirtualMachineDescriptor} object and associates it
* with the given name.
*
* <p>The new virtual machine will be in the same state as the descriptor indicates.
*
* <p>Once a virtual machine is imported it is persisted until it is deleted by calling {@link
* #delete}. The imported virtual machine is in {@link #STATUS_STOPPED} state. To run the VM,
* call {@link #run}.
*/
@GuardedBy("VirtualMachineManager.sCreateLock")
@NonNull
static VirtualMachine fromDescriptor(
@NonNull Context context,
@NonNull String name,
@NonNull VirtualMachineDescriptor vmDescriptor)
throws VirtualMachineException {
File vmDir = createVmDir(context, name);
try {
VirtualMachine vm;
try (vmDescriptor) {
VirtualMachineConfig config = VirtualMachineConfig.from(vmDescriptor.getConfigFd());
VirtualizationService service = VirtualizationService.getInstance();
vm = new VirtualMachine(context, name, config, service);
config.serialize(vm.mConfigFilePath);
try {
vm.mInstanceFilePath.createNewFile();
} catch (IOException e) {
throw new VirtualMachineException("failed to create instance image", e);
}
vm.importInstanceFrom(vmDescriptor.getInstanceImgFd());
// TODO(b/406258175): handle the encrypted store KEK for VM transfer.
if (vmDescriptor.getEncryptedStoreFd() != null) {
try {
vm.mEncryptedStoreFilePath.createNewFile();
} catch (IOException e) {
throw new VirtualMachineException(
"failed to create encrypted storage image", e);
}
vm.importEncryptedStoreFrom(vmDescriptor.getEncryptedStoreFd());
}
if (vm.mInstanceIdPath != null) {
vm.importInstanceIdFrom(vmDescriptor.getInstanceIdFd());
vm.claimInstance(service);
}
}
return vm;
} catch (VirtualMachineException | RuntimeException e) {
// If anything goes wrong, delete any files created so far and the VM's directory
try {
deleteRecursively(vmDir);
} catch (Exception innerException) {
e.addSuppressed(innerException);
}
throw e;
}
}
/**
* Creates a virtual machine with the given name and config. Once a virtual machine is created
* it is persisted until it is deleted by calling {@link #delete}. The created virtual machine
* is in {@link #STATUS_STOPPED} state. To run the VM, call {@link #run}.
*/
@GuardedBy("VirtualMachineManager.sCreateLock")
@NonNull
static VirtualMachine create(
@NonNull Context context, @NonNull String name, @NonNull VirtualMachineConfig config)
throws VirtualMachineException {
File vmDir = createVmDir(context, name);
try {
VirtualizationService virtualizationService = VirtualizationService.getInstance();
VirtualMachine vm = new VirtualMachine(context, name, config, virtualizationService);
try {
vm.mInstanceFilePath.createNewFile();
} catch (IOException e) {
throw new VirtualMachineException("failed to create instance image", e);
}
if (config.isEncryptedStorageEnabled()) {
try {
vm.mEncryptedStoreFilePath.createNewFile();
} catch (IOException e) {
throw new VirtualMachineException(
"failed to create encrypted storage image", e);
}
}
IVirtualizationService service = virtualizationService.getBinder();
if (vm.mInstanceIdPath != null) {
try (FileOutputStream stream = new FileOutputStream(vm.mInstanceIdPath)) {
byte[] id = service.allocateInstanceId();
stream.write(id);
} catch (FileNotFoundException e) {
throw new VirtualMachineException("instance_id file missing", e);
} catch (IOException e) {
throw new VirtualMachineException("failed to persist instance_id", e);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
} catch (ServiceSpecificException | IllegalArgumentException e) {
throw new VirtualMachineException("failed to create instance_id", e);
}
}
try (ParcelFileDescriptor fd =
ParcelFileDescriptor.open(vm.mInstanceFilePath, MODE_READ_WRITE)) {
service.initializeWritablePartition(
fd, INSTANCE_FILE_SIZE, PartitionType.ANDROID_VM_INSTANCE);
} catch (FileNotFoundException e) {
throw new VirtualMachineException("instance image missing", e);
} catch (IOException e) {
throw new VirtualMachineException("failed to initialize instance partition", e);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
} catch (ServiceSpecificException | IllegalArgumentException e) {
throw new VirtualMachineException("failed to create instance partition", e);
}
if (config.isEncryptedStorageEnabled()) {
try (ParcelFileDescriptor fd =
ParcelFileDescriptor.open(vm.mEncryptedStoreFilePath, MODE_READ_WRITE)) {
service.initializeWritablePartition(
fd, config.getEncryptedStorageBytes(), PartitionType.ENCRYPTEDSTORE);
} catch (FileNotFoundException e) {
throw new VirtualMachineException("encrypted storage image missing", e);
} catch (IOException e) {
throw new VirtualMachineException(
"failed to initialize encrypted store partition", e);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
} catch (ServiceSpecificException | IllegalArgumentException e) {
throw new VirtualMachineException(
"failed to create encrypted storage partition", e);
}
}
// persist the config only after we pass all the checks above.
config.serialize(vm.mConfigFilePath);
return vm;
} catch (VirtualMachineException | RuntimeException e) {
// If anything goes wrong, delete any files created so far and the VM's directory
try {
vmInstanceCleanup(context, name);
} catch (Exception innerException) {
e.addSuppressed(innerException);
}
throw e;
}
}
/** Loads a virtual machine that is already created before. */
@GuardedBy("VirtualMachineManager.sCreateLock")
@Nullable
static VirtualMachine load(@NonNull Context context, @NonNull String name)
throws VirtualMachineException {
File thisVmDir = getVmDir(context, name);
if (!thisVmDir.exists()) {
// The VM doesn't exist.
return null;
}
File configFilePath = new File(thisVmDir, CONFIG_FILE);
VirtualMachineConfig config = VirtualMachineConfig.from(configFilePath);
VirtualMachine vm =
new VirtualMachine(context, name, config, VirtualizationService.getInstance());
if (vm.mInstanceIdPath != null && !vm.mInstanceIdPath.exists()) {
throw new VirtualMachineException("instance_id file missing");
}
if (!vm.mInstanceFilePath.exists()) {
throw new VirtualMachineException("instance image missing");
}
if (config.isEncryptedStorageEnabled() && !vm.mEncryptedStoreFilePath.exists()) {
throw new VirtualMachineException("Storage image missing");
}
// TODO(b/406258175): here we need to detect if migration is required.
return vm;
}
@GuardedBy("VirtualMachineManager.sCreateLock")
void delete(Context context, String name) throws VirtualMachineException {
synchronized (mLock) {
checkStopped();
// Once we explicitly delete a VM it must remain permanently in the deleted state;
// if a new VM is created with the same name (and files) that's unrelated.
mWasDeleted = true;
}
vmInstanceCleanup(context, name);
}
// Delete the full VM directory and notify VirtualizationService to remove this
// VM instance for housekeeping.
@GuardedBy("VirtualMachineManager.sCreateLock")
static void vmInstanceCleanup(Context context, String name) throws VirtualMachineException {
File vmDir = getVmDir(context, name);
File ceVmDir = getVmDir(context.createCredentialProtectedStorageContext(), name);
notifyInstanceRemoval(vmDir, VirtualizationService.getInstance());
try {
deleteRecursively(vmDir);
if (ceVmDir.exists() && !vmDir.getCanonicalPath().equals(ceVmDir.getCanonicalPath())) {
deleteRecursively(ceVmDir);
}
} catch (IOException e) {
throw new VirtualMachineException(e);
}
}
private static void notifyInstanceRemoval(
File vmDirectory, @NonNull VirtualizationService service) {
File instanceIdFile = new File(vmDirectory, INSTANCE_ID_FILE);
try {
byte[] instanceId = Files.readAllBytes(instanceIdFile.toPath());
service.getBinder().removeVmInstance(instanceId);
} catch (Exception e) {
// Deliberately ignoring error in removing VM instance. This potentially leads to
// unaccounted instances in the VS' database. But, nothing much can be done by caller.
Log.w(TAG, "Failed to notify VS to remove the VM instance", e);
}
}
// Claim the instance. This notifies the global VS about the ownership of this
// instance_id for housekeeping purpose.
void claimInstance(@NonNull VirtualizationService service) throws VirtualMachineException {
if (mInstanceIdPath != null) {
try {
byte[] instanceId = Files.readAllBytes(mInstanceIdPath.toPath());
service.getBinder().claimVmInstance(instanceId);
} catch (IOException e) {
throw new VirtualMachineException("failed to read instance_id", e);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
}
@GuardedBy("VirtualMachineManager.sCreateLock")
@NonNull
private static File createVmDir(@NonNull Context context, @NonNull String name)
throws VirtualMachineException {
File vmDir = getVmDir(context, name);
try {
// We don't need to undo this even if VM creation fails.
Files.createDirectories(vmDir.getParentFile().toPath());
// The checking of the existence of this directory and the creation of it is done
// atomically. If the directory already exists (i.e. the VM with the same name was
// already created), FileAlreadyExistsException is thrown.
Files.createDirectory(vmDir.toPath());
} catch (FileAlreadyExistsException e) {
throw new VirtualMachineException(
"virtual machine already exists",
e,
VirtualMachineException.CODE_NAME_ALREADY_EXISTS);
} catch (IOException e) {
throw new VirtualMachineException("failed to create directory for VM", e);
}
return vmDir;
}
@NonNull
private static File getVmDir(@NonNull Context context, @NonNull String name) {
if (name.contains(File.separator) || name.equals(".") || name.equals("..")) {
throw new IllegalArgumentException("Invalid VM name: " + name);
}
File vmRoot = new File(context.getDataDir(), VM_DIR);
return new File(vmRoot, name);
}
/**
* Returns the name of this virtual machine. The name is unique in the package and can't be
* changed.
*
* @hide
*/
@SystemApi
@NonNull
public String getName() {
return mName;
}
/**
* Returns the currently selected config of this virtual machine. There can be multiple virtual
* machines sharing the same config. Even in that case, the virtual machines are completely
* isolated from each other; they have different secrets. It is also possible that a virtual
* machine can change its config, which can be done by calling {@link #setConfig}.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
* @hide
*/
@SystemApi
@WorkerThread
@NonNull
public VirtualMachineConfig getConfig() {
synchronized (mLock) {
return mConfig;
}
}
/**
* Returns the current status of this virtual machine.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
* @hide
*/
@SystemApi
@WorkerThread
@Status
public int getStatus() {
IVirtualMachine virtualMachine;
synchronized (mLock) {
if (mWasDeleted) {
return STATUS_DELETED;
}
virtualMachine = mVirtualMachine;
}
int status;
if (virtualMachine == null) {
status = STATUS_STOPPED;
} else {
try {
status = stateToStatus(virtualMachine.getState());
} catch (RemoteException e) {
status = STATUS_STOPPED;
}
}
if (status == STATUS_STOPPED && !mVmRootPath.exists()) {
// A VM can quite happily keep running if its backing files have been deleted.
// But once it stops, it's gone forever.
synchronized (mLock) {
mWasDeleted = true;
}
return STATUS_DELETED;
}
return status;
}
private int stateToStatus(@VirtualMachineState int state) {
switch (state) {
case VirtualMachineState.STARTING:
case VirtualMachineState.STARTED:
case VirtualMachineState.READY:
case VirtualMachineState.FINISHED:
return STATUS_RUNNING;
case VirtualMachineState.NOT_STARTED:
case VirtualMachineState.DEAD:
default:
return STATUS_STOPPED;
}
}
// Throw an appropriate exception if we have a running VM, or the VM has been deleted.
@GuardedBy("mLock")
private void checkStopped() throws VirtualMachineException {
switch (getStatus()) {
case STATUS_STOPPED:
// no-op
return;
case STATUS_RUNNING:
throw new VirtualMachineException(
"VM is not in stopped state",
VirtualMachineException.CODE_VIRTUAL_MACHINE_RUNNING);
case STATUS_DELETED:
throw new VirtualMachineException(
"VM has been deleted",
VirtualMachineException.CODE_VIRTUAL_MACHINE_DELETED);
}
}
private void handleStopped(int cid, @VirtualMachineCallback.StopReason int reason) {
synchronized (mLock) {
// Since we just took the lock, we can't assume the stopped
// notification is for the current VM.
if (mCid == cid) {
if (mStopHandled) {
return;
}
mStopHandled = true;
dropVm();
}
}
executeCallback((cb) -> cb.onStopped(VirtualMachine.this, reason));
}
/**
* This should only be called when we know our VM has stopped; we no longer need to hold a
* reference to it (this allows resources to be GC'd) and we no longer need to be informed of
* memory pressure.
*/
@GuardedBy("mLock")
private void dropVm() {
if (mInputEventExecutor != null) {
mInputEventExecutor.shutdownNow();
mInputEventExecutor = null;
}
if (mMemoryManagementCallbacks != null) {
mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
}
if (mVirtualMachine != null) {
try {
mVirtualMachine.asBinder().unlinkToDeath(mVMDeathRecipient, /* flags= */ 0);
} catch (RuntimeException e) {
Log.w(TAG, "Ignore exception unlinkToDeath() for IVirtualMachine, exception=" + e);
}
mVirtualMachine = null;
mCid = -1;
}
if (mVirtualizationService != null) {
try {
mVirtualizationService
.getBinder()
.asBinder()
.unlinkToDeath(mVSDeathRecipient, /* flags= */ 0);
} catch (RuntimeException e) {
Log.w(
TAG,
"Ignore exception unlinkToDeath() for IVirtualizationService, exception="
+ e);
}
mVirtualizationService = null;
}
}
/** If we have an IVirtualMachine in the running state return it, otherwise throw. */
@GuardedBy("mLock")
private IVirtualMachine getRunningVm() throws VirtualMachineException {
switch (getStatus()) {
case STATUS_STOPPED:
throw new VirtualMachineException(
"VM is not in running state",
VirtualMachineException.CODE_VIRTUAL_MACHINE_STOPPED);
case STATUS_RUNNING:
return mVirtualMachine;
case STATUS_DELETED:
throw new VirtualMachineException(
"VM has been deleted",
VirtualMachineException.CODE_VIRTUAL_MACHINE_DELETED);
default:
// unreachable code. Just make compiler happy.
return null;
}
}
/**
* Registers the callback object to get events from the virtual machine. If a callback was
* already registered, it is replaced with the new one.
*
* @hide
*/
@SystemApi
public void setCallback(
@NonNull @CallbackExecutor Executor executor,
@NonNull VirtualMachineCallback callback) {
synchronized (mCallbackLock) {
mCallback = callback;
mCallbackExecutor = executor;
}
}
/**
* Clears the currently registered callback.
*
* @hide
*/
@SystemApi
public void clearCallback() {
synchronized (mCallbackLock) {
mCallback = null;
mCallbackExecutor = null;
}
}
/** Executes a callback on the callback executor. */
private void executeCallback(Consumer<VirtualMachineCallback> fn) {
final VirtualMachineCallback callback;
final Executor executor;
synchronized (mCallbackLock) {
callback = mCallback;
executor = mCallbackExecutor;
}
if (callback == null || executor == null) {
return;
}
final long restoreToken = Binder.clearCallingIdentity();
try {
executor.execute(() -> fn.accept(callback));
} finally {
Binder.restoreCallingIdentity(restoreToken);
}
}
private android.system.virtualizationservice.VirtualMachineConfig
createVirtualMachineConfigForRawFrom(VirtualMachineConfig vmConfig)
throws IllegalStateException, IOException {
VirtualMachineRawConfig rawConfig = vmConfig.toVsRawConfig();
// Handle input devices here
List<InputDevice> inputDevices = new ArrayList<>();
if (vmConfig.getCustomImageConfig() != null && rawConfig.displayConfig != null) {