-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVirtualMachineConfig.java
More file actions
1552 lines (1422 loc) · 60.6 KB
/
Copy pathVirtualMachineConfig.java
File metadata and controls
1552 lines (1422 loc) · 60.6 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 java.util.Objects.requireNonNull;
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.StringDef;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.os.PersistableBundle;
import android.sysprop.HypervisorProperties;
import android.system.virtualizationservice.AssignedDevices;
import android.system.virtualizationservice.CpuOptions;
import android.system.virtualizationservice.CustomMemoryBackingFile;
import android.system.virtualizationservice.DiskImage;
import android.system.virtualizationservice.Partition;
import android.system.virtualizationservice.SharedPath;
import android.system.virtualizationservice.UsbConfig;
import android.system.virtualizationservice.VirtualMachineAppConfig;
import android.system.virtualizationservice.VirtualMachinePayloadConfig;
import android.system.virtualizationservice.VirtualMachineRawConfig;
import android.text.TextUtils;
import android.util.Log;
import com.android.system.virtualmachine.flags.Flags;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.zip.ZipFile;
/**
* Represents a configuration of a virtual machine. A configuration consists of hardware
* configurations like the number of CPUs and the size of RAM, and software configurations like the
* payload to run on the virtual machine.
*
* @hide
*/
@SystemApi
public final class VirtualMachineConfig {
private static final String TAG = "VirtualMachineConfig";
private static String[] EMPTY_STRING_ARRAY = {};
private static final String U_BOOT_PREBUILT_PATH_ARM = "/apex/com.android.virt/etc/u-boot.bin";
private static final String U_BOOT_PREBUILT_PATH_X86 = "/apex/com.android.virt/etc/u-boot.rom";
// These define the schema of the config file persisted on disk.
// Please bump up the version number when adding a new key.
private static final int VERSION = 10;
private static final String KEY_VERSION = "version";
private static final String KEY_PACKAGENAME = "packageName";
private static final String KEY_APKPATH = "apkPath";
private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
private static final String KEY_CUSTOMIMAGECONFIG = "customImageConfig";
private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
private static final String KEY_DEBUGLEVEL = "debugLevel";
private static final String KEY_PROTECTED_VM = "protectedVm";
private static final String KEY_MEMORY_BYTES = "memoryBytes";
private static final String KEY_CPU_TOPOLOGY = "cpuTopology";
private static final String KEY_CONSOLE_INPUT_DEVICE = "consoleInputDevice";
private static final String KEY_ENCRYPTED_STORAGE_BYTES = "encryptedStorageBytes";
private static final String KEY_VM_OUTPUT_CAPTURED = "vmOutputCaptured";
private static final String KEY_VM_CONSOLE_INPUT_SUPPORTED = "vmConsoleInputSupported";
private static final String KEY_CONNECT_VM_CONSOLE = "connectVmConsole";
private static final String KEY_VENDOR_DISK_IMAGE_PATH = "vendorDiskImagePath";
private static final String KEY_OS = "os";
private static final String KEY_EXTRA_APKS = "extraApks";
private static final String KEY_SHOULD_BOOST_UCLAMP = "shouldBoostUclamp";
private static final String KEY_SHOULD_USE_HUGEPAGES = "shouldUseHugepages";
private static final String KEY_ENCRYPTED_STORE_MODE = "encryptedStoreMode";
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef(
prefix = "DEBUG_LEVEL_",
value = {DEBUG_LEVEL_NONE, DEBUG_LEVEL_FULL})
public @interface DebugLevel {}
/**
* Not debuggable at all. No log is exported from the VM. Debugger can't be attached to the app
* process running in the VM. This is the default level.
*
* @hide
*/
@SystemApi public static final int DEBUG_LEVEL_NONE = 0;
/**
* Fully debuggable. All logs (both logcat and kernel message) are exported. All processes
* running in the VM can be attached to the debugger. Rooting is possible.
*
* @hide
*/
@SystemApi public static final int DEBUG_LEVEL_FULL = 1;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef(
prefix = "CPU_TOPOLOGY_",
value = {
CPU_TOPOLOGY_ONE_CPU,
CPU_TOPOLOGY_MATCH_HOST,
})
public @interface CpuTopology {}
/**
* Run VM with 1 vCPU. This is the default option, usually the fastest to boot and consuming the
* least amount of resources. Typically the best option for small or ephemeral workloads.
*
* @hide
*/
@SystemApi public static final int CPU_TOPOLOGY_ONE_CPU = 0;
/**
* Run VM with vCPU topology matching the physical CPU topology of the host. Usually takes
* longer to boot and consumes more resources compared to a single vCPU. Typically a good option
* for long-running workloads that benefit from parallel execution.
*
* @hide
*/
@SystemApi public static final int CPU_TOPOLOGY_MATCH_HOST = 1;
/** Name of a package whose primary APK contains the VM payload. */
@Nullable private final String mPackageName;
/** Absolute path to the APK file containing the VM payload. */
@Nullable private final String mApkPath;
private final List<String> mExtraApks;
@DebugLevel private final int mDebugLevel;
/** Whether to run the VM in protected mode, so the host can't access its memory. */
private final boolean mProtectedVm;
/**
* The amount of RAM to give the VM, in bytes. If this is 0 or negative the default will be
* used.
*/
private final long mMemoryBytes;
/** CPU topology configuration of the VM. */
@CpuTopology private final int mCpuTopology;
/** The serial device for VM console input. */
@Nullable private final String mConsoleInputDevice;
/** Path within the APK to the payload config file that defines software aspects of the VM. */
@Nullable private final String mPayloadConfigPath;
/** Name of the payload binary file within the APK that will be executed within the VM. */
@Nullable private final String mPayloadBinaryName;
/** The custom image config file to launch the custom VM. */
@Nullable private final VirtualMachineCustomImageConfig mCustomImageConfig;
/** The size of storage in bytes. 0 indicates that encryptedStorage is not required */
private final long mEncryptedStorageBytes;
/** Whether the app can read console and log output. */
private final boolean mVmOutputCaptured;
/** Whether the app can write console input to the VM */
private final boolean mVmConsoleInputSupported;
/** Whether to connect the VM console to a host console. */
private final boolean mConnectVmConsole;
@Nullable private final File mVendorDiskImage;
/** OS name of the VM using payload binaries. */
@NonNull @OsName private final String mOs;
private final boolean mShouldBoostUclamp;
private final boolean mShouldUseHugepages;
@EncryptedStoreMode private final int mEncryptedStoreMode;
/**
* Name of the {@code <property>} of the {@code AndroidManifest.xml} to specify which encrypted
* store mode is used for the VM. If the property is not specified in the {@code
* AndroidManifest.xml} then a {@link #ENCRYPTED_STORE_MODE_DEFAULT} is used.
*
* <p>In most cases you don't want to specify this property and use the default encrypted store
* mode.
*
* <p>If {@link #ENCRYPTED_STORE_MODE_KEK_ON_CE} is chosen (by setting value of the property to
* the {@code 1} in the manifest), then KEK used to set the encrypted store of the VM will be
* stored on the app's CE storage. This also means that encrypted store won't be set up during
* the VM boot. Instead, payload is expected to signal {@code microdroid_manager} when it's ok
* to setup encrypted store by setting the {@code microdroid_manager.encrypted_store.setup}
* sysprop to {@code true}.
*/
private static final String ENCRYPTED_STORE_MODE_PROP_NAME =
"android.system.virtualmachine.ENCRYPTED_STORE_MODE";
/**
* Default mode of encrypted store used by most of the VMs.
*
* @hide
*/
public static final int ENCRYPTED_STORE_MODE_DEFAULT = 0;
/**
* A mode of encrypted store where the KEK used for the set up is stored on the CE storage of
* the app.
*
* @hide
*/
public static final int ENCRYPTED_STORE_MODE_KEK_ON_CE = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef(
prefix = "ENCRYPTED_STORE_MODE_",
value = {ENCRYPTED_STORE_MODE_DEFAULT, ENCRYPTED_STORE_MODE_KEK_ON_CE})
private @interface EncryptedStoreMode {}
@Retention(RetentionPolicy.SOURCE)
@StringDef(
prefix = "MICRODROID",
value = {MICRODROID})
private @interface OsName {}
/**
* OS name of microdroid using microdroid kernel.
*
* @see Builder#setOs
* @hide
*/
@TestApi
@OsName
public static final String MICRODROID = "microdroid";
private VirtualMachineConfig(
@Nullable String packageName,
@Nullable String apkPath,
List<String> extraApks,
@Nullable String payloadConfigPath,
@Nullable String payloadBinaryName,
@Nullable VirtualMachineCustomImageConfig customImageConfig,
@DebugLevel int debugLevel,
boolean protectedVm,
long memoryBytes,
@CpuTopology int cpuTopology,
@Nullable String consoleInputDevice,
long encryptedStorageBytes,
boolean vmOutputCaptured,
boolean vmConsoleInputSupported,
boolean connectVmConsole,
@Nullable File vendorDiskImage,
@NonNull @OsName String os,
boolean shouldBoostUclamp,
boolean shouldUseHugepages,
@EncryptedStoreMode int encryptedStoreMode) {
// This is only called from Builder.build(); the builder handles parameter validation.
mPackageName = packageName;
mApkPath = apkPath;
mExtraApks =
extraApks.isEmpty()
? Collections.emptyList()
: Collections.unmodifiableList(
Arrays.asList(extraApks.toArray(new String[0])));
mPayloadConfigPath = payloadConfigPath;
mPayloadBinaryName = payloadBinaryName;
mCustomImageConfig = customImageConfig;
mDebugLevel = debugLevel;
mProtectedVm = protectedVm;
mMemoryBytes = memoryBytes;
mCpuTopology = cpuTopology;
mConsoleInputDevice = consoleInputDevice;
mEncryptedStorageBytes = encryptedStorageBytes;
mVmOutputCaptured = vmOutputCaptured;
mVmConsoleInputSupported = vmConsoleInputSupported;
mConnectVmConsole = connectVmConsole;
mVendorDiskImage = vendorDiskImage;
mOs = os;
mShouldBoostUclamp = shouldBoostUclamp;
mShouldUseHugepages = shouldUseHugepages;
mEncryptedStoreMode = encryptedStoreMode;
}
/** Loads a config from a file. */
@NonNull
static VirtualMachineConfig from(@NonNull File file) throws VirtualMachineException {
try (FileInputStream input = new FileInputStream(file)) {
return fromInputStream(input);
} catch (IOException e) {
// Please don't change this error message unless b/437160991 is fixed. Clients depend on
// this error message as a temporary fix for b/433697078.
throw new VirtualMachineException(
"Failed to read VM config from file",
e,
VirtualMachineException.CODE_CONFIG_FILE_CORRUPTED);
}
}
/** Loads a config from a {@link ParcelFileDescriptor}. */
@NonNull
static VirtualMachineConfig from(@NonNull ParcelFileDescriptor fd)
throws VirtualMachineException {
try (AutoCloseInputStream input = new AutoCloseInputStream(fd)) {
return fromInputStream(input);
} catch (IOException e) {
throw new VirtualMachineException(
"failed to read VM config from file descriptor",
e,
VirtualMachineException.CODE_CONFIG_FILE_CORRUPTED);
}
}
/** Loads a config from a stream, for example a file. */
@NonNull
private static VirtualMachineConfig fromInputStream(@NonNull InputStream input)
throws IOException, VirtualMachineException {
PersistableBundle b = PersistableBundle.readFromStream(input);
try {
return fromPersistableBundle(b);
} catch (NullPointerException | IllegalArgumentException | IllegalStateException e) {
// Please don't change this error message unless b/437160991 is fixed. Clients depend on
// this error message as a temporary fix for b/433697078.
throw new VirtualMachineException(
"Persisted VM config is invalid",
e,
VirtualMachineException.CODE_CONFIG_FILE_CORRUPTED);
}
}
@NonNull
private static VirtualMachineConfig fromPersistableBundle(PersistableBundle b) {
int version = b.getInt(KEY_VERSION);
if (version > VERSION) {
throw new IllegalArgumentException(
"Version " + version + " too high; current is " + VERSION);
}
String packageName = b.getString(KEY_PACKAGENAME);
Builder builder = new Builder(packageName);
String apkPath = b.getString(KEY_APKPATH);
if (apkPath != null) {
builder.setApkPath(apkPath);
}
String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
String payloadBinaryName = b.getString(KEY_PAYLOADBINARYNAME);
PersistableBundle customImageConfigBundle = b.getPersistableBundle(KEY_CUSTOMIMAGECONFIG);
if (customImageConfigBundle != null) {
builder.setCustomImageConfig(
VirtualMachineCustomImageConfig.from(customImageConfigBundle));
} else if (payloadConfigPath != null) {
builder.setPayloadConfigPath(payloadConfigPath);
} else {
builder.setPayloadBinaryName(payloadBinaryName);
}
@DebugLevel int debugLevel = b.getInt(KEY_DEBUGLEVEL);
if (debugLevel != DEBUG_LEVEL_NONE && debugLevel != DEBUG_LEVEL_FULL) {
throw new IllegalArgumentException("Invalid debugLevel: " + debugLevel);
}
builder.setDebugLevel(debugLevel);
builder.setProtectedVm(b.getBoolean(KEY_PROTECTED_VM));
long memoryBytes = b.getLong(KEY_MEMORY_BYTES);
if (memoryBytes != 0) {
builder.setMemoryBytes(memoryBytes);
}
builder.setCpuTopology(b.getInt(KEY_CPU_TOPOLOGY));
String consoleInputDevice = b.getString(KEY_CONSOLE_INPUT_DEVICE);
if (consoleInputDevice != null) {
builder.setConsoleInputDevice(consoleInputDevice);
}
long encryptedStorageBytes = b.getLong(KEY_ENCRYPTED_STORAGE_BYTES);
if (encryptedStorageBytes != 0) {
builder.setEncryptedStorageBytes(encryptedStorageBytes);
}
builder.setVmOutputCaptured(b.getBoolean(KEY_VM_OUTPUT_CAPTURED));
builder.setVmConsoleInputSupported(b.getBoolean(KEY_VM_CONSOLE_INPUT_SUPPORTED));
builder.setConnectVmConsole(b.getBoolean(KEY_CONNECT_VM_CONSOLE));
String vendorDiskImagePath = b.getString(KEY_VENDOR_DISK_IMAGE_PATH);
if (vendorDiskImagePath != null) {
builder.setVendorDiskImage(new File(vendorDiskImagePath));
}
builder.setOs(b.getString(KEY_OS));
String[] extraApks = b.getStringArray(KEY_EXTRA_APKS);
if (extraApks != null) {
for (String extraApk : extraApks) {
builder.addExtraApk(extraApk);
}
}
builder.setShouldBoostUclamp(b.getBoolean(KEY_SHOULD_BOOST_UCLAMP));
builder.setShouldUseHugepages(b.getBoolean(KEY_SHOULD_USE_HUGEPAGES));
builder.setEncryptedStoreMode(
b.getInt(KEY_ENCRYPTED_STORE_MODE, ENCRYPTED_STORE_MODE_DEFAULT));
return builder.build();
}
/** Persists this config to a file. */
void serialize(@NonNull File file) throws VirtualMachineException {
// To prevent serialization failure from leaving the config file in an invalid state,
// serialize it to a temp file, and then rename it to the requrested file when the
// serialization is done successfully.
File tempFile = null;
try {
// Must be in the same filesystem as the target path, otherwise the move will fail.
tempFile = File.createTempFile("vm_config", null, file.getParentFile());
} catch (IOException e) {
throw new VirtualMachineException("failed to create temporary VM config file", e);
}
try (FileOutputStream output = new FileOutputStream(tempFile)) {
serializeOutputStream(output);
Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new VirtualMachineException("failed to write VM config", e);
} finally {
tempFile.delete();
}
}
/** Persists this config to a stream, for example a file. */
private void serializeOutputStream(@NonNull OutputStream output) throws IOException {
PersistableBundle b = new PersistableBundle();
b.putInt(KEY_VERSION, VERSION);
if (mPackageName != null) {
b.putString(KEY_PACKAGENAME, mPackageName);
}
if (mApkPath != null) {
b.putString(KEY_APKPATH, mApkPath);
}
b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
if (mCustomImageConfig != null) {
b.putPersistableBundle(KEY_CUSTOMIMAGECONFIG, mCustomImageConfig.toPersistableBundle());
}
b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
b.putInt(KEY_CPU_TOPOLOGY, mCpuTopology);
if (mConsoleInputDevice != null) {
b.putString(KEY_CONSOLE_INPUT_DEVICE, mConsoleInputDevice);
}
if (mMemoryBytes > 0) {
b.putLong(KEY_MEMORY_BYTES, mMemoryBytes);
}
if (mEncryptedStorageBytes > 0) {
b.putLong(KEY_ENCRYPTED_STORAGE_BYTES, mEncryptedStorageBytes);
}
b.putBoolean(KEY_VM_OUTPUT_CAPTURED, mVmOutputCaptured);
b.putBoolean(KEY_VM_CONSOLE_INPUT_SUPPORTED, mVmConsoleInputSupported);
b.putBoolean(KEY_CONNECT_VM_CONSOLE, mConnectVmConsole);
if (mVendorDiskImage != null) {
b.putString(KEY_VENDOR_DISK_IMAGE_PATH, mVendorDiskImage.getAbsolutePath());
}
b.putString(KEY_OS, mOs);
if (!mExtraApks.isEmpty()) {
String[] extraApks = mExtraApks.toArray(new String[0]);
b.putStringArray(KEY_EXTRA_APKS, extraApks);
}
b.putBoolean(KEY_SHOULD_BOOST_UCLAMP, mShouldBoostUclamp);
b.putBoolean(KEY_SHOULD_USE_HUGEPAGES, mShouldUseHugepages);
b.putInt(KEY_ENCRYPTED_STORE_MODE, mEncryptedStoreMode);
b.writeToStream(output);
}
/**
* Returns the absolute path of the APK which should contain the binary payload that will
* execute within the VM. Returns null if no specific path has been set.
*
* @hide
*/
@SystemApi
@Nullable
public String getApkPath() {
return mApkPath;
}
/**
* Returns the package names of any extra APKs that have been requested for the VM. They are
* returned in the order in which they were added via {@link Builder#addExtraApk}.
*
* @hide
*/
@TestApi
@NonNull
public List<String> getExtraApks() {
return mExtraApks;
}
/**
* Returns the path within the APK to the payload config file that defines software aspects of
* the VM.
*
* @hide
*/
@TestApi
@Nullable
public String getPayloadConfigPath() {
return mPayloadConfigPath;
}
/**
* Returns the custom image config to launch the custom VM.
*
* @hide
*/
@Nullable
public VirtualMachineCustomImageConfig getCustomImageConfig() {
return mCustomImageConfig;
}
/**
* Returns the name of the payload binary file, in the {@code lib/<ABI>} directory of the APK,
* that will be executed within the VM.
*
* @hide
*/
@SystemApi
@Nullable
public String getPayloadBinaryName() {
return mPayloadBinaryName;
}
/**
* Returns the debug level for the VM.
*
* @hide
*/
@SystemApi
@DebugLevel
public int getDebugLevel() {
return mDebugLevel;
}
/**
* Returns whether the VM's memory will be protected from the host.
*
* @hide
*/
@SystemApi
public boolean isProtectedVm() {
return mProtectedVm;
}
/**
* Returns the amount of RAM that will be made available to the VM, or 0 if the default size
* will be used.
*
* @hide
*/
@SystemApi
@IntRange(from = 0)
public long getMemoryBytes() {
return mMemoryBytes;
}
/**
* Returns the CPU topology configuration of the VM.
*
* @hide
*/
@SystemApi
@CpuTopology
public int getCpuTopology() {
return mCpuTopology;
}
/**
* Returns whether encrypted storage is enabled or not.
*
* @hide
*/
@SystemApi
public boolean isEncryptedStorageEnabled() {
return mEncryptedStorageBytes > 0;
}
/**
* Returns mode encrypted store is set up with
*
* @hide
*/
@EncryptedStoreMode
public int getEncryptedStoreMode() {
return mEncryptedStoreMode;
}
/**
* Returns the size of encrypted storage (in bytes) available in the VM, or 0 if encrypted
* storage is not enabled
*
* @hide
*/
@SystemApi
@IntRange(from = 0)
public long getEncryptedStorageBytes() {
return mEncryptedStorageBytes;
}
/**
* Returns whether the app can read the VM console or log output. If not, the VM output is
* automatically forwarded to the host logcat.
*
* @see Builder#setVmOutputCaptured
* @hide
*/
@SystemApi
public boolean isVmOutputCaptured() {
return mVmOutputCaptured;
}
/**
* Returns whether the app can write to the VM console.
*
* @see Builder#setVmConsoleInputSupported
* @hide
*/
@TestApi
public boolean isVmConsoleInputSupported() {
return mVmConsoleInputSupported;
}
/**
* Returns whether to connect the VM console to a host console.
*
* @see Builder#setConnectVmConsole
* @hide
*/
public boolean isConnectVmConsole() {
return mConnectVmConsole;
}
/**
* Returns the OS of the VM.
*
* @see Builder#setOs
* @hide
*/
@TestApi
@NonNull
@OsName
public String getOs() {
return mOs;
}
/**
* Returns whether this VM enabled the hint to use transparent huge pages.
*
* @see Builder#setShouldUseHugepages
* @hide
*/
@SystemApi
@FlaggedApi(Flags.FLAG_PROMOTE_SET_SHOULD_USE_HUGEPAGES_TO_SYSTEM_API)
public boolean shouldUseHugepages() {
return mShouldUseHugepages;
}
/**
* Tests if this config is compatible with other config. Being compatible means that the configs
* can be interchangeably used for the same virtual machine; they do not change the VM identity
* or secrets. Such changes include varying the number of CPUs or the size of the RAM. Changes
* that would alter the identity of the VM (e.g. using a different payload or changing the debug
* mode) are considered incompatible.
*
* @see VirtualMachine#setConfig
* @hide
*/
@SystemApi
public boolean isCompatibleWith(@NonNull VirtualMachineConfig other) {
if (this == other) {
return true;
}
return this.mDebugLevel == other.mDebugLevel
&& this.mProtectedVm == other.mProtectedVm
&& this.mVmOutputCaptured == other.mVmOutputCaptured
&& this.mVmConsoleInputSupported == other.mVmConsoleInputSupported
&& this.mConnectVmConsole == other.mConnectVmConsole
&& (this.mVendorDiskImage == null) == (other.mVendorDiskImage == null)
&& Objects.equals(this.mConsoleInputDevice, other.mConsoleInputDevice)
&& Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
&& Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
&& Objects.equals(this.mPackageName, other.mPackageName)
&& Objects.equals(this.mOs, other.mOs)
&& Objects.equals(this.mExtraApks, other.mExtraApks)
&& this.mEncryptedStoreMode == other.mEncryptedStoreMode;
}
private ParcelFileDescriptor openOrNull(File file, int mode) {
try {
return ParcelFileDescriptor.open(file, mode);
} catch (FileNotFoundException e) {
Log.d(TAG, "cannot open", e);
return null;
}
}
private void startCrosvmVirtiofs(
String sharedPath,
int host_uid,
int guest_uid,
int guest_gid,
String tagName,
int mask,
String socketPath)
throws IOException {
String ugidMapValue =
String.format("%d %d %d %d %d /", guest_uid, guest_gid, host_uid, host_uid, mask);
String cfgArg = String.format("ugid_map='%s'", ugidMapValue);
ProcessBuilder pb =
new ProcessBuilder(
"/apex/com.android.virt/bin/crosvm",
"device",
"fs",
"--socket=" + socketPath,
"--tag=" + tagName,
"--shared-dir=" + sharedPath,
"--cfg",
cfgArg,
"--disable-sandbox",
"--skip-pivot-root=true");
pb.start();
}
VirtualMachineRawConfig toVsRawConfig() throws IllegalStateException, IOException {
VirtualMachineRawConfig config = new VirtualMachineRawConfig();
VirtualMachineCustomImageConfig customImageConfig = getCustomImageConfig();
requireNonNull(customImageConfig);
config.name = Optional.ofNullable(customImageConfig.getName()).orElse("");
config.instanceId = new byte[64];
config.osName = Optional.ofNullable(customImageConfig.getOsName()).orElse("");
config.kernel =
Optional.ofNullable(customImageConfig.getKernelPath())
.map(
(path) -> {
try {
return ParcelFileDescriptor.open(
new File(path), MODE_READ_ONLY);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
})
.orElse(null);
config.initrd =
Optional.ofNullable(customImageConfig.getInitrdPath())
.map((path) -> openOrNull(new File(path), MODE_READ_ONLY))
.orElse(null);
config.bootloader =
Optional.ofNullable(customImageConfig.getBootloaderPath())
.map((path) -> openOrNull(new File(path), MODE_READ_ONLY))
.orElse(null);
if (config.kernel == null && config.bootloader == null) {
if (Arrays.stream(Build.SUPPORTED_ABIS).anyMatch("x86_64"::equals)) {
config.bootloader = openOrNull(new File(U_BOOT_PREBUILT_PATH_X86), MODE_READ_ONLY);
} else {
config.bootloader = openOrNull(new File(U_BOOT_PREBUILT_PATH_ARM), MODE_READ_ONLY);
}
}
config.params =
Optional.ofNullable(customImageConfig.getParams())
.map((params) -> TextUtils.join(" ", params))
.orElse("");
config.disks =
new DiskImage
[Optional.ofNullable(customImageConfig.getDisks())
.map(arr -> arr.length)
.orElse(0)];
for (int i = 0; i < config.disks.length; i++) {
config.disks[i] = new DiskImage();
config.disks[i].writable = customImageConfig.getDisks()[i].isWritable();
String diskImagePath = customImageConfig.getDisks()[i].getImagePath();
if (diskImagePath != null) {
config.disks[i].image =
ParcelFileDescriptor.open(
new File(diskImagePath),
config.disks[i].writable ? MODE_READ_WRITE : MODE_READ_ONLY);
}
List<Partition> partitions = new ArrayList<>();
for (VirtualMachineCustomImageConfig.Partition p :
customImageConfig.getDisks()[i].getPartitions()) {
Partition part = new Partition();
part.label = p.name;
part.image =
ParcelFileDescriptor.open(
new File(p.imagePath),
p.writable ? MODE_READ_WRITE : MODE_READ_ONLY);
part.writable = p.writable;
part.guid = TextUtils.isEmpty(p.guid) ? null : p.guid;
partitions.add(part);
}
config.disks[i].partitions = partitions.toArray(new Partition[0]);
}
config.sharedPaths =
new SharedPath
[Optional.ofNullable(customImageConfig.getSharedPaths())
.map(arr -> arr.length)
.orElse(0)];
for (int i = 0; i < config.sharedPaths.length; i++) {
config.sharedPaths[i] = customImageConfig.getSharedPaths()[i].toParcelable();
if (config.sharedPaths[i].appDomain) {
try {
String socketPath = customImageConfig.getSharedPaths()[i].getSocketPath();
startCrosvmVirtiofs(
config.sharedPaths[i].sharedPath,
config.sharedPaths[i].hostUid,
config.sharedPaths[i].guestUid,
config.sharedPaths[i].guestGid,
config.sharedPaths[i].tag,
config.sharedPaths[i].mask,
socketPath);
long startTime = System.currentTimeMillis();
long deadline = startTime + 5000;
// TODO: use socketpair instead of crosvm creating the named sockets.
while (!Files.exists(Path.of(socketPath))
&& System.currentTimeMillis() < deadline) {
Thread.sleep(200);
}
if (!Files.exists(Path.of(socketPath))) {
throw new IOException("Timeout waiting for socket: " + socketPath);
}
LocalSocket socket = new LocalSocket();
socket.connect(
new LocalSocketAddress(
socketPath, LocalSocketAddress.Namespace.FILESYSTEM));
config.sharedPaths[i].socketFd =
ParcelFileDescriptor.dup(socket.getFileDescriptor());
} catch (IOException | InterruptedException e) {
Log.e(TAG, "startCrosvmVirtiofs failed", e);
throw new RuntimeException(e);
}
}
}
config.displayConfig =
Optional.ofNullable(customImageConfig.getDisplayConfig())
.map(dc -> dc.toParcelable())
.orElse(null);
config.gpuConfig =
Optional.ofNullable(customImageConfig.getGpuConfig())
.map(dc -> dc.toParcelable())
.orElse(null);
config.protectedVm = this.mProtectedVm;
config.memoryMib = bytesToMebiBytes(mMemoryBytes);
switch (this.mCpuTopology) {
case CPU_TOPOLOGY_MATCH_HOST:
config.cpuOptions = new CpuOptions();
config.cpuOptions.cpuTopology = CpuOptions.CpuTopology.matchHost(true);
break;
default:
config.cpuOptions = new CpuOptions();
config.cpuOptions.cpuTopology = CpuOptions.CpuTopology.cpuCount(1);
break;
}
config.consoleInputDevice = mConsoleInputDevice;
config.devices = AssignedDevices.devices(EMPTY_STRING_ARRAY);
config.platformVersion = "~1.0";
config.audioConfig =
Optional.ofNullable(customImageConfig.getAudioConfig())
.map(ac -> ac.toParcelable())
.orElse(null);
config.balloon = customImageConfig.useAutoMemoryBalloon();
config.usbConfig =
Optional.ofNullable(customImageConfig.getUsbConfig())
.map(
uc -> {
UsbConfig usbConfig = new UsbConfig();
usbConfig.controller = uc.getUsbController();
return usbConfig;
})
.orElse(null);
config.teeServices = EMPTY_STRING_ARRAY;
config.customMemoryBackingFiles = new CustomMemoryBackingFile[0];
config.hostServices = EMPTY_STRING_ARRAY;
return config;
}
/**
* Converts this config object into the parcelable type used when creating a VM via the
* virtualization service. Notice that the files are not passed as paths, but as file
* descriptors because the service doesn't accept paths as it might not have permission to open
* app-owned files and that could be abused to run a VM with software that the calling
* application doesn't own.
*/
VirtualMachineAppConfig toVsConfig(@NonNull PackageManager packageManager)
throws VirtualMachineException {
VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
String apkPath = (mApkPath != null) ? mApkPath : findPayloadApk(packageManager);
try {
vsConfig.apk = ParcelFileDescriptor.open(new File(apkPath), MODE_READ_ONLY);
} catch (FileNotFoundException e) {
throw new VirtualMachineException(
"Failed to open APK", e, VirtualMachineException.CODE_PAYLOAD_CONFIG_MALFORMED);
}
if (mPayloadBinaryName != null) {
VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
payloadConfig.payloadBinaryName = mPayloadBinaryName;
payloadConfig.extraApks = Collections.emptyList();
vsConfig.payload = VirtualMachineAppConfig.Payload.payloadConfig(payloadConfig);
} else {
vsConfig.payload = VirtualMachineAppConfig.Payload.configPath(mPayloadConfigPath);
}
vsConfig.osName = mOs;
switch (mDebugLevel) {
case DEBUG_LEVEL_FULL:
vsConfig.debugLevel = VirtualMachineAppConfig.DebugLevel.FULL;
break;
default:
vsConfig.debugLevel = VirtualMachineAppConfig.DebugLevel.NONE;
break;
}
vsConfig.protectedVm = mProtectedVm;
vsConfig.memoryMib = bytesToMebiBytes(mMemoryBytes);
switch (mCpuTopology) {
case CPU_TOPOLOGY_MATCH_HOST:
vsConfig.cpuOptions = new CpuOptions();
vsConfig.cpuOptions.cpuTopology = CpuOptions.CpuTopology.matchHost(true);
break;
default:
vsConfig.cpuOptions = new CpuOptions();
vsConfig.cpuOptions.cpuTopology = CpuOptions.CpuTopology.cpuCount(1);
break;
}
if (mVendorDiskImage != null) {
VirtualMachineAppConfig.CustomConfig customConfig =
new VirtualMachineAppConfig.CustomConfig();
customConfig.devices = EMPTY_STRING_ARRAY;
customConfig.extraKernelCmdlineParams = EMPTY_STRING_ARRAY;
customConfig.teeServices = EMPTY_STRING_ARRAY;
try {
customConfig.vendorImage =
ParcelFileDescriptor.open(mVendorDiskImage, MODE_READ_ONLY);
} catch (FileNotFoundException e) {
throw new VirtualMachineException(
"Failed to open vendor disk image " + mVendorDiskImage.getAbsolutePath(),
e,
VirtualMachineException.CODE_PAYLOAD_CONFIG_MALFORMED);
}
vsConfig.customConfig = customConfig;
}
vsConfig.boostUclamp = mShouldBoostUclamp;
vsConfig.hugePages = mShouldUseHugepages;
vsConfig.hostServices = EMPTY_STRING_ARRAY;