-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
UTMQemuSystem.m
794 lines (737 loc) · 32.1 KB
/
UTMQemuSystem.m
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
//
// Copyright © 2020 osy. All rights reserved.
//
// 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.
//
#import <dlfcn.h>
#import <sys/sysctl.h>
#import <TargetConditionals.h>
#import "UTMQemuSystem.h"
#import "UTMConfiguration.h"
#import "UTMConfiguration+Constants.h"
#import "UTMConfiguration+Display.h"
#import "UTMConfiguration+Drives.h"
#import "UTMConfiguration+Miscellaneous.h"
#import "UTMConfiguration+Networking.h"
#import "UTMConfiguration+Sharing.h"
#import "UTMConfiguration+System.h"
#import "UTMConfigurationPortForward.h"
#import "UTMJailbreak.h"
#import "UTMLogging.h"
typedef struct {
NSInteger cpus;
NSInteger threads;
} CPUCount;
extern NSString *const kUTMErrorDomain;
@interface UTMQemuSystem ()
@property (nonatomic, readonly) NSURL *resourceURL;
@property (nonatomic, readonly) CPUCount emulatedCpuCount;
@property (nonatomic, readonly) BOOL useHypervisor;
@property (nonatomic, readonly) BOOL hasCustomBios;
@property (nonatomic, readonly) BOOL usbSupported;
@property (nonatomic, readonly) NSURL *efiVariablesURL;
@property (nonatomic, readonly) BOOL isGLOn;
@property (nonatomic, readonly) BOOL isSparc;
@end
@implementation UTMQemuSystem {
int (*_qemu_init)(int, const char *[], const char *[]);
void (*_qemu_main_loop)(void);
void (*_qemu_cleanup)(void);
}
static void *start_qemu(void *args) {
UTMQemuSystem *self = (__bridge_transfer UTMQemuSystem *)args;
NSArray<NSString *> *qemuArgv = self.argv;
NSCAssert(self->_qemu_init != NULL, @"Started thread with invalid function.");
NSCAssert(self->_qemu_main_loop != NULL, @"Started thread with invalid function.");
NSCAssert(self->_qemu_cleanup != NULL, @"Started thread with invalid function.");
NSCAssert(qemuArgv, @"Started thread with invalid argv.");
int argc = (int)qemuArgv.count + 1;
const char *argv[argc];
argv[0] = "qemu-system";
for (int i = 0; i < qemuArgv.count; i++) {
argv[i+1] = [qemuArgv[i] UTF8String];
}
const char *envp[] = { NULL };
self->_qemu_init(argc, argv, envp);
self->_qemu_main_loop();
self->_qemu_cleanup();
self.status = 0;
dispatch_semaphore_signal(self.done);
return NULL;
}
static size_t sysctl_read(const char *name) {
size_t len;
unsigned int ncpu = 0;
len = sizeof(ncpu);
sysctlbyname(name, &ncpu, &len, NULL, 0);
return ncpu;
}
- (instancetype)initWithConfiguration:(UTMConfiguration *)configuration imgPath:(nonnull NSURL *)imgPath {
self = [self init];
if (self) {
self.configuration = configuration;
self.imgPath = imgPath;
self.qmpPort = 4444;
self.entry = start_qemu;
}
return self;
}
- (NSArray<NSString *> *)argv {
NSArray<NSString *> *argv = [super argv];
if (argv.count == 0) {
// HACK: when called from QEMU settings page
[self updateArgvWithUserOptions:NO];
}
return [super argv];
}
- (NSURL *)resourceURL {
return [[NSBundle mainBundle] URLForResource:@"qemu" withExtension:nil];
}
- (CPUCount)emulatedCpuCount {
static const __unused CPUCount singleCpu = {
.cpus = 1,
.threads = 1,
};
CPUCount hostCount = {
.cpus = sysctl_read("hw.physicalcpu"),
.threads = sysctl_read("hw.logicalcpu"),
};
NSInteger userCpus = [self.configuration.systemCPUCount integerValue];
if (userCpus > 0 || hostCount.cpus == 0) {
CPUCount userCount = {
.cpus = userCpus,
.threads = userCpus,
};
return userCount; // user override
}
NSString *arch = self.configuration.systemArchitecture;
// SPARC5 defaults to single CPU
if ([arch hasPrefix:@"sparc"]) {
return singleCpu;
}
#if defined(__aarch64__)
CPUCount hostPcoreCount = {
.cpus = sysctl_read("hw.perflevel0.physicalcpu"),
.threads = sysctl_read("hw.perflevel0.logicalcpu"),
};
// in ARM we can only emulate other weak architectures
if ([arch isEqualToString:@"alpha"] ||
[arch isEqualToString:@"arm"] ||
[arch isEqualToString:@"aarch64"] ||
[arch isEqualToString:@"avr"] ||
[arch hasPrefix:@"mips"] ||
[arch hasPrefix:@"ppc"] ||
[arch hasPrefix:@"riscv"] ||
[arch hasPrefix:@"xtensa"]) {
if (self.useOnlyPcores && hostPcoreCount.cpus > 0) {
return hostPcoreCount;
} else {
return hostCount;
}
} else {
return singleCpu;
}
#elif defined(__x86_64__)
// in x86 we can emulate weak on strong
return hostCount;
#else
return singleCpu;
#endif
}
- (void)architectureSpecificConfiguration {
NSString *arch = self.configuration.systemArchitecture;
if ([arch isEqualToString:@"x86_64"] || [arch isEqualToString:@"i386"]) {
[self pushArgv:@"-global"];
[self pushArgv:@"PIIX4_PM.disable_s3=1"]; // applies for pc-i440fx-* types
[self pushArgv:@"-global"];
[self pushArgv:@"ICH9-LPC.disable_s3=1"]; // applies for pc-q35-* types
}
if (self.configuration.systemBootUefi) {
NSString *name = [NSString stringWithFormat:@"edk2-%@-code.fd", arch];
NSURL *path = [self.resourceURL URLByAppendingPathComponent:name];
if (!self.hasCustomBios && [[NSFileManager defaultManager] fileExistsAtPath:path.path]) {
[self pushArgv:@"-drive"];
[self pushArgv:[NSString stringWithFormat:@"if=pflash,format=raw,unit=0,file=%@,readonly=on", path.path]]; // accessDataWithBookmark called already
[self pushArgv:@"-drive"];
[self pushArgv:[NSString stringWithFormat:@"if=pflash,format=raw,unit=1,file=%@", self.efiVariablesURL.path]];
[self accessDataWithBookmark:[self.efiVariablesURL bookmarkDataWithOptions:0
includingResourceValuesForKeys:nil
relativeToURL:nil
error:nil]];
}
}
}
- (NSString *)expandDriveInterface:(NSString *)interface identifier:(NSString *)identifier removable:(BOOL)removable busInterfaceMap:(NSMutableDictionary<NSString *, NSNumber *> *)busInterfaceMap {
NSInteger bootindex = [busInterfaceMap[@"boot"] integerValue];
NSInteger busindex = [busInterfaceMap[interface] integerValue];
if ([interface isEqualToString:@"ide"]) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"%@,bus=ide.%lu,drive=%@,bootindex=%lu", removable ? @"ide-cd" : @"ide-hd", busindex++, identifier, bootindex++]];
} else if ([interface isEqualToString:@"scsi"]) {
NSString *bus;
if (self.isSparc) {
bus = @"scsi";
} else {
bus = @"scsi0";
if (busindex == 0) {
[self pushArgv:@"-device"];
[self pushArgv:@"lsi53c895a,id=scsi0"];
}
}
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"%@,bus=%@.0,channel=0,scsi-id=%lu,drive=%@,bootindex=%lu", removable ? @"scsi-cd" : @"scsi-hd", bus, busindex++, identifier, bootindex++]];
} else if ([interface isEqualToString:@"virtio"]) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"%@,drive=%@,bootindex=%lu", [self.configuration.systemArchitecture isEqualToString:@"s390x"] ? @"virtio-blk-ccw" : @"virtio-blk-pci", identifier, bootindex++]];
} else if ([interface isEqualToString:@"nvme"]) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"nvme,drive=%@,serial=%@,bootindex=%lu", identifier, identifier, bootindex++]];
} else if ([interface isEqualToString:@"usb"]) {
[self pushArgv:@"-device"];
/// use usb 3 bus for virt system, unless using legacy input setting (this mirrors the code in argsForUsb)
bool useUSB3 = !self.configuration.inputLegacy && [self.configuration.systemTarget hasPrefix:@"virt"];
NSString *bus = useUSB3 ? @",bus=usb-bus.0" : @"";
[self pushArgv:[NSString stringWithFormat:@"usb-storage,drive=%@,removable=%@,bootindex=%lu%@", identifier, removable ? @"true" : @"false", bootindex++, bus]];
} else if ([interface isEqualToString:@"floppy"] && [self.configuration.systemTarget hasPrefix:@"q35"]) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"isa-fdc,id=fdc%lu,bootindexA=%lu", busindex, bootindex++]];
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"floppy,unit=0,bus=fdc%lu.0,drive=%@", busindex++, identifier]];
} else {
return interface; // no expand needed
}
busInterfaceMap[@"boot"] = @(bootindex);
busInterfaceMap[interface] = @(busindex);
return @"none";
}
- (void)argsForCpu {
if ([self.configuration.systemCPU isEqualToString:@"default"] && self.useHypervisor) {
// if default and not hypervisor, we don't pass any -cpu argument for x86 and use host for ARM
#if !defined(__x86_64__)
[self pushArgv:@"-cpu"];
[self pushArgv:@"host"];
#endif
} else if (self.configuration.systemCPU.length > 0 && ![self.configuration.systemCPU isEqualToString:@"default"]) {
NSString *cpu = self.configuration.systemCPU;
for (NSString *flag in self.configuration.systemCPUFlags) {
unichar prefix = [flag characterAtIndex:0];
if (prefix != '-' && prefix != '+') {
cpu = [cpu stringByAppendingFormat:@",+%@", flag];
} else {
cpu = [cpu stringByAppendingFormat:@",%@", flag];
}
}
[self pushArgv:@"-cpu"];
[self pushArgv:cpu];
}
[self pushArgv:@"-smp"];
[self pushArgv:[NSString stringWithFormat:@"cpus=%lu,sockets=1,cores=%lu,threads=%lu", self.emulatedCpuCount.threads, self.emulatedCpuCount.cpus, self.emulatedCpuCount.threads / self.emulatedCpuCount.cpus]];
}
- (void)argsForSound {
if (self.configuration.soundEnabled) {
if ([self.configuration.soundCard isEqualToString:@"screamer"]) {
#if !TARGET_OS_IPHONE
// force CoreAudio backend for mac99 which only supports 44100 Hz
[self pushArgv:@"-audiodev"];
[self pushArgv:@"coreaudio,id=audio0"];
// no device setting for screamer
#endif
} else {
[self pushArgv:@"-device"];
[self pushArgv:self.configuration.soundCard];
if ([self.configuration.soundCard containsString:@"hda"]) {
[self pushArgv:@"-device"];
[self pushArgv:@"hda-duplex"];
}
}
}
}
- (void)argsForDrives {
NSMutableDictionary<NSString *, NSNumber *> *busInterfaceMap = [NSMutableDictionary dictionary];
for (NSUInteger i = 0; i < self.configuration.countDrives; i++) {
NSString *path = [self.configuration driveImagePathForIndex:i];
UTMDiskImageType type = [self.configuration driveImageTypeForIndex:i];
BOOL hasImage = ![self.configuration driveRemovableForIndex:i] && path;
NSURL *fullPathURL;
if (hasImage) {
if ([path characterAtIndex:0] == '/') {
fullPathURL = [NSURL fileURLWithPath:path isDirectory:NO];
} else {
fullPathURL = [[self.imgPath URLByAppendingPathComponent:[UTMConfiguration diskImagesDirectory]] URLByAppendingPathComponent:[self.configuration driveImagePathForIndex:i]];
}
[self accessDataWithBookmark:[fullPathURL bookmarkDataWithOptions:0
includingResourceValuesForKeys:nil
relativeToURL:nil
error:nil]];
}
switch (type) {
case UTMDiskImageTypeDisk:
case UTMDiskImageTypeCD: {
NSString *interface = [self.configuration driveInterfaceTypeForIndex:i];
BOOL removable = (type == UTMDiskImageTypeCD) || [self.configuration driveRemovableForIndex:i];
NSString *identifier = [self.configuration driveNameForIndex:i];
NSString *realInterface = [self expandDriveInterface:interface identifier:identifier removable:removable busInterfaceMap:busInterfaceMap];
NSString *drive;
[self pushArgv:@"-drive"];
drive = [NSString stringWithFormat:@"if=%@,media=%@,id=%@", realInterface, removable ? @"cdrom" : @"disk", identifier];
if (hasImage) {
drive = [NSString stringWithFormat:@"%@,file=%@,cache=writethrough", drive, fullPathURL.path];
}
[self pushArgv:drive];
break;
}
case UTMDiskImageTypeBIOS: {
if (hasImage) {
[self pushArgv:@"-bios"];
[self pushArgv:fullPathURL.path];
}
break;
}
case UTMDiskImageTypeKernel: {
if (hasImage) {
[self pushArgv:@"-kernel"];
[self pushArgv:fullPathURL.path];
}
break;
}
case UTMDiskImageTypeInitrd: {
if (hasImage) {
[self pushArgv:@"-initrd"];
[self pushArgv:fullPathURL.path];
}
break;
}
case UTMDiskImageTypeDTB: {
if (hasImage) {
[self pushArgv:@"-dtb"];
[self pushArgv:fullPathURL.path];
}
break;
}
case UTMDiskImageTypeNone: {
break; // ignore this image
}
default: {
UTMLog(@"WARNING: unknown image type %lu, ignoring image %@", type, fullPathURL);
break;
}
}
}
}
- (void)argsForNetwork {
if (self.configuration.networkEnabled) {
if (self.isSparc) {
[self pushArgv:@"-net"];
[self pushArgv:[NSString stringWithFormat:@"nic,model=lance,macaddr=%@,netdev=net0", self.configuration.networkCardMac]];
} else {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"%@,mac=%@,netdev=net0", self.configuration.networkCard, self.configuration.networkCardMac]];
}
[self pushArgv:@"-netdev"];
NSString *device = @"user";
NSMutableString *netstr;
BOOL hasPortForwarding = YES;
if ([self.configuration.networkMode isEqualToString:@"shared"]) {
device = @"vmnet-macos";
hasPortForwarding = NO;
if (self.configuration.networkIsolate) {
netstr = [NSMutableString stringWithString:@"vmnet-macos,mode=host,id=net0"];
} else {
netstr = [NSMutableString stringWithString:@"vmnet-macos,mode=shared,id=net0"];
}
} else if ([self.configuration.networkMode isEqualToString:@"bridged"]) {
hasPortForwarding = NO;
netstr = [NSMutableString stringWithString:@"vmnet-macos,mode=bridged,id=net0"];
if (self.configuration.networkBridgeInterface.length > 0) {
[netstr appendFormat:@",ifname=%@", self.configuration.networkBridgeInterface];
}
} else {
netstr = [NSMutableString stringWithString:@"user,id=net0"];
if (self.configuration.networkIsolate) {
[netstr appendString:@",restrict=on"];
}
}
if (self.configuration.networkAddress.length > 0) {
[netstr appendFormat:@",net=%@", self.configuration.networkAddress];
}
if (self.configuration.networkHost.length > 0) {
[netstr appendFormat:@",host=%@", self.configuration.networkHost];
}
if (self.configuration.networkAddressIPv6.length > 0) {
[netstr appendFormat:@",ipv6-net=%@", self.configuration.networkAddressIPv6];
}
if (self.configuration.networkHostIPv6.length > 0) {
[netstr appendFormat:@",ipv6-host=%@", self.configuration.networkHostIPv6];
}
if (self.configuration.networkHost.length > 0) {
[netstr appendFormat:@",hostname=%@", self.configuration.networkHost];
}
if (self.configuration.networkDhcpStart.length > 0) {
[netstr appendFormat:@",dhcpstart=%@", self.configuration.networkDhcpStart];
}
if (self.configuration.networkDnsServer.length > 0) {
[netstr appendFormat:@",dns=%@", self.configuration.networkDnsServer];
}
if (self.configuration.networkDnsServerIPv6.length > 0) {
[netstr appendFormat:@",ipv6-dns=%@", self.configuration.networkDnsServerIPv6];
}
if (self.configuration.networkDnsSearch.length > 0) {
[netstr appendFormat:@",dnssearch=%@", self.configuration.networkDnsSearch];
}
if (self.configuration.networkDhcpDomain.length > 0) {
[netstr appendFormat:@",domainname=%@", self.configuration.networkDhcpDomain];
}
if (hasPortForwarding) {
for (NSUInteger i = 0; i < [self.configuration countPortForwards]; i++) {
UTMConfigurationPortForward *portForward = [self.configuration portForwardForIndex:i];
[netstr appendFormat:@",hostfwd=%@:%@:%@-%@:%@", portForward.protocol, portForward.hostAddress, portForward.hostPort, portForward.guestAddress, portForward.guestPort];
}
}
[self pushArgv:netstr];
} else {
[self pushArgv:@"-nic"];
[self pushArgv:@"none"];
}
}
- (void)argsForUsb {
// set up USB input devices unless user requested legacy (QEMU default PS/2 input)
if (!self.configuration.inputLegacy) {
if ([self.configuration.systemTarget hasPrefix:@"virt"]) {
[self pushArgv:@"-device"];
[self pushArgv:@"qemu-xhci,id=usb-bus"];
} else {
[self pushArgv:@"-usb"];
}
[self pushArgv:@"-device"];
[self pushArgv:@"usb-tablet,bus=usb-bus.0"];
if (![self.configuration.systemTarget hasPrefix:@"pc"] && ![self.configuration.systemTarget hasPrefix:@"q35"]) {
[self pushArgv:@"-device"];
[self pushArgv:@"usb-mouse,bus=usb-bus.0"];
[self pushArgv:@"-device"];
[self pushArgv:@"usb-kbd,bus=usb-bus.0"];
}
}
#if !defined(WITH_QEMU_TCI)
NSInteger maxDevices = [self.configuration.usbRedirectionMaximumDevices integerValue];
if (self.configuration.usb3Support) {
NSString *controller = @"qemu-xhci";
if ([self.configuration.systemTarget hasPrefix:@"pc"] || [self.configuration.systemTarget hasPrefix:@"q35"]) {
controller = @"nec-usb-xhci"; // Windows 7 doesn't like qemu-xchi
}
for (int j = 0; j < ((maxDevices + 2) / 3); j++) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"%@,id=usb-controller-%d", controller, j]];
}
} else {
for (int j = 0; j < ((maxDevices + 2) / 3); j++) {
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"ich9-usb-ehci1,id=usb-controller-%d", j]];
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"ich9-usb-uhci1,masterbus=usb-controller-%d.0,firstport=0,multifunction=on", j]];
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"ich9-usb-uhci2,masterbus=usb-controller-%d.0,firstport=2,multifunction=on", j]];
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"ich9-usb-uhci3,masterbus=usb-controller-%d.0,firstport=4,multifunction=on", j]];
}
}
// set up usb forwarding
for (int i = 0; i < maxDevices; i++) {
[self pushArgv:@"-chardev"];
[self pushArgv:[NSString stringWithFormat:@"spicevmc,name=usbredir,id=usbredirchardev%d", i]];
[self pushArgv:@"-device"];
[self pushArgv:[NSString stringWithFormat:@"usb-redir,chardev=usbredirchardev%d,id=usbredirdev%d,bus=usb-controller-%d.0", i, i, i / 3]];
}
#endif
}
- (void)argsForSharing {
if (self.configuration.displayConsoleOnly) {
return; // no SPICE for console only
}
if (self.configuration.shareClipboardEnabled || self.configuration.shareDirectoryEnabled) {
[self pushArgv:@"-device"];
[self pushArgv:@"virtio-serial"];
}
if (self.configuration.shareClipboardEnabled) {
[self pushArgv:@"-device"];
[self pushArgv:@"virtserialport,chardev=vdagent,name=com.redhat.spice.0"];
[self pushArgv:@"-chardev"];
[self pushArgv:@"spicevmc,id=vdagent,debug=0,name=vdagent"];
}
if (self.configuration.shareDirectoryEnabled) {
[self pushArgv:@"-device"];
[self pushArgv:@"virtserialport,chardev=charchannel1,id=channel1,name=org.spice-space.webdav.0"];
[self pushArgv:@"-chardev"];
[self pushArgv:@"spiceport,name=org.spice-space.webdav.0,id=charchannel1"];
}
}
- (NSString *)tcgAccelProperties {
NSString *accel = @"tcg";
if (self.configuration.systemForceMulticore) {
accel = [accel stringByAppendingString:@",thread=multi"];
}
NSInteger tb_size = self.configuration.systemMemory.integerValue / 4;
if (self.configuration.systemJitCacheSize.integerValue > 0) {
tb_size = self.configuration.systemJitCacheSize.integerValue;
}
accel = [accel stringByAppendingFormat:@",tb-size=%ld", tb_size];
#if !defined(WITH_QEMU_TCI)
// use mirror mapping when we don't have JIT entitlements
if (!jb_has_jit_entitlement()) {
accel = [accel stringByAppendingString:@",split-wx=on"];
}
#endif
return accel;
}
- (BOOL)useHypervisor {
#if TARGET_OS_IPHONE
return NO;
#else
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
return self.configuration.isTargetArchitectureMatchHost && ![defaults boolForKey:@"NoHypervisor"];
#endif
}
- (BOOL)useOnlyPcores {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL isUnset = ![defaults objectForKey:@"UseOnlyPcores"];
return isUnset || [defaults boolForKey:@"UseOnlyPcores"];
}
- (BOOL)hasCustomBios {
for (NSUInteger i = 0; i < self.configuration.countDrives; i++) {
UTMDiskImageType type = [self.configuration driveImageTypeForIndex:i];
NSString *interface = [self.configuration driveInterfaceTypeForIndex:i];
switch (type) {
case UTMDiskImageTypeDisk:
case UTMDiskImageTypeCD: {
if ([interface isEqualToString:@"pflash"]) {
return YES;
}
break;
}
case UTMDiskImageTypeBIOS:
case UTMDiskImageTypeKernel: {
return YES;
break;
}
default: {
continue;
}
}
}
return NO;
}
- (BOOL)usbSupported {
NSString *arch = self.configuration.systemArchitecture;
NSString *target = self.configuration.systemTarget;
if ([target isEqualToString:@"isapc"]) {
return NO;
}
if ([arch isEqualToString:@"s390x"]) {
return NO;
}
if ([arch hasPrefix:@"sparc"]) {
return NO;
}
return YES;
}
- (NSURL *)efiVariablesURL {
return [[self.imgPath URLByAppendingPathComponent:[UTMConfiguration diskImagesDirectory]] URLByAppendingPathComponent:@"efi_vars.fd"];
}
- (NSString *)machineProperties {
if (self.configuration.systemMachineProperties.length > 0) {
return self.configuration.systemMachineProperties; // use specified properties
}
return @"";
}
- (BOOL)isGLOn {
// GL supported devices have contains GL moniker
return [self.configuration.displayCard containsString:@"-gl-"] ||
[self.configuration.displayCard hasSuffix:@"-gl"];
}
- (BOOL)isSparc {
return [self.configuration.systemArchitecture isEqualToString:@"sparc"];
}
- (void)argsRequired {
[self clearArgv];
[self pushArgv:@"-L"];
[self accessDataWithBookmark:[self.resourceURL bookmarkDataWithOptions:0
includingResourceValuesForKeys:nil
relativeToURL:nil
error:nil]];
[self pushArgv:self.resourceURL.path];
[self pushArgv:@"-S"]; // startup stopped
[self pushArgv:@"-qmp"];
[self pushArgv:[NSString stringWithFormat:@"tcp:127.0.0.1:%lu,server,nowait", self.qmpPort]];
if (self.isSparc) { // SPARC uses -vga
if (!self.configuration.displayConsoleOnly) {
[self pushArgv:@"-vga"];
[self pushArgv:self.configuration.displayCard];
}
} else { // disable -vga and other default devices
// prevent QEMU default devices, which leads to duplicate CD drive (fix #2538)
// see https://github.com/qemu/qemu/blob/6005ee07c380cbde44292f5f6c96e7daa70f4f7d/docs/qdev-device-use.txt#L382
[self pushArgv:@"-nodefaults"];
[self pushArgv:@"-vga"];
[self pushArgv:@"none"];// -vga none, avoid adding duplicate graphics cards
}
if (self.configuration.displayConsoleOnly) {
[self pushArgv:@"-nographic"];
// terminal character device
NSURL* ioFile = [self.configuration terminalInputOutputURL];
[self pushArgv: @"-chardev"];
[self pushArgv: [NSString stringWithFormat: @"pipe,id=term0,path=%@", ioFile.path]];
[self pushArgv: @"-serial"];
[self pushArgv: @"chardev:term0"];
} else {
NSURL *spiceSocketURL = self.configuration.spiceSocketURL;
[self pushArgv:@"-spice"];
[self pushArgv:[NSString stringWithFormat:@"unix=on,addr=%@,disable-ticketing=on,image-compression=off,playback-compression=off,streaming-video=off,gl=%@", spiceSocketURL.path, self.isGLOn ? @"on" : @"off"]];
if (!self.isSparc) { // SPARC uses -vga (above)
[self pushArgv:@"-device"];
[self pushArgv:self.configuration.displayCard];
}
}
}
- (void)argsFromConfiguration {
[self argsForCpu];
[self pushArgv:@"-machine"];
[self pushArgv:[NSString stringWithFormat:@"%@,%@", self.configuration.systemTarget, [self machineProperties]]];
if (self.useHypervisor) {
[self pushArgv:@"-accel"];
[self pushArgv:@"hvf"];
}
[self pushArgv:@"-accel"];
[self pushArgv:[self tcgAccelProperties]];
[self architectureSpecificConfiguration];
// legacy boot order; new bootindex uses drive ordering
[self pushArgv:@"-boot"];
if (self.configuration.systemBootDevice.length > 0 && ![self.configuration.systemBootDevice isEqualToString:@"hdd"]) {
if ([self.configuration.systemBootDevice isEqualToString:@"floppy"]) {
[self pushArgv:@"order=ab"];
} else {
[self pushArgv:@"order=d"];
}
} else {
[self pushArgv:@"menu=on"];
}
[self pushArgv:@"-m"];
[self pushArgv:[self.configuration.systemMemory stringValue]];
[self argsForSound];
[self pushArgv:@"-name"];
[self pushArgv:self.configuration.name];
if (self.usbSupported) {
[self argsForUsb];
}
[self argsForDrives];
[self argsForNetwork];
if (self.snapshot) {
[self pushArgv:@"-loadvm"];
[self pushArgv:self.snapshot];
}
[self argsForSharing];
if (self.configuration.systemUUID.length > 0) {
[self pushArgv:@"-uuid"];
[self pushArgv:self.configuration.systemUUID];
}
// fix windows time issues
[self pushArgv:@"-rtc"];
[self pushArgv:@"base=localtime"];
}
- (void)argsFromUser {
if (self.configuration.systemArguments.count != 0) {
NSArray *addArgs = self.configuration.systemArguments;
// Splits all spaces into their own, except when between quotes.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\"[^\"]+\"|\\+|\\S+)" options:0 error:nil];
for (NSString *arg in addArgs) {
// No need to operate on empty arguments.
if (arg.length == 0) {
continue;
}
NSArray *splitArgsArray = [regex matchesInString:arg
options:0
range:NSMakeRange(0, [arg length])];
for (NSTextCheckingResult *match in splitArgsArray) {
NSRange matchRange = [match rangeAtIndex:1];
NSString *argFragment = [arg substringWithRange:matchRange];
if ([argFragment hasPrefix:@"\""] && [argFragment hasSuffix:@"\""]) {
argFragment = [argFragment substringWithRange:NSMakeRange(1, argFragment.length-2)];
}
[self pushArgv:argFragment];
}
}
}
}
- (BOOL)didLoadDylib:(void *)handle {
_qemu_init = dlsym(handle, "qemu_init");
_qemu_main_loop = dlsym(handle, "qemu_main_loop");
_qemu_cleanup = dlsym(handle, "qemu_cleanup");
return (_qemu_init != NULL) && (_qemu_main_loop != NULL) && (_qemu_cleanup != NULL);
}
- (void)updateArgvWithUserOptions:(BOOL)userOptions {
[self argsRequired];
if (!self.configuration.ignoreAllConfiguration) {
[self argsFromConfiguration];
}
if (userOptions) {
[self argsFromUser];
}
}
- (BOOL)createEfiVariablesIfNeededWithError:(NSError **)error {
NSString *arch = self.configuration.systemArchitecture;
NSFileManager *fileManager = NSFileManager.defaultManager;
NSURL *srcUrl = nil;
if (![fileManager fileExistsAtPath:self.efiVariablesURL.path]) {
if ([arch isEqualToString:@"arm"] || [arch isEqualToString:@"aarch64"]) {
srcUrl = [self.resourceURL URLByAppendingPathComponent:@"edk2-arm-vars.fd"];
} else if ([arch isEqualToString:@"i386"] || [arch isEqualToString:@"x86_64"]) {
srcUrl = [self.resourceURL URLByAppendingPathComponent:@"edk2-i386-vars.fd"];
} else {
if (error) {
*error = [NSError errorWithDomain:kUTMErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"UEFI is not supported with this architecture.", "UTMQemuSystem")}];
}
return NO;
}
return [fileManager copyItemAtURL:srcUrl toURL:self.efiVariablesURL error:error];
}
return YES;
}
- (BOOL)validateOSSupportWithError:(NSError **)error {
if (@available(macOS 11.3, *)) {
return YES;
} else {
if (self.configuration.soundEnabled && self.configuration.displayConsoleOnly) {
*error = [NSError errorWithDomain:kUTMErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"This version of macOS does not support audio in console mode. Please change the VM configuration or upgrade macOS.", "UTMQemuSystem")}];
return NO;
}
if (self.isGLOn && !self.configuration.displayConsoleOnly) {
*error = [NSError errorWithDomain:kUTMErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"This version of macOS does not support GPU acceleration. Please change the VM configuration or upgrade macOS.", "UTMQemuSystem")}];
return NO;
}
}
return YES;
}
- (void)startWithCompletion:(void (^)(BOOL, NSString * _Nonnull))completion {
NSError *err;
if (self.configuration.systemBootUefi) {
if (![self createEfiVariablesIfNeededWithError:&err]) {
completion(NO, err.localizedDescription);
return;
}
}
if (![self validateOSSupportWithError:&err]) {
completion(NO, err.localizedDescription);
return;
}
[self updateArgvWithUserOptions:YES];
[self startQemu:self.configuration.systemArchitecture completion:completion];
}
@end