2
0

QEMUHelper.m 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //
  2. // Copyright © 2020 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. #import "QEMUHelper.h"
  17. #import "QEMUHelperDelegate.h"
  18. #import <stdio.h>
  19. #import <signal.h>
  20. static const int64_t kProcessTerminateTimeoutSeconds = 1;
  21. @interface QEMUHelper ()
  22. @property (nonatomic) NSMutableArray<NSURL *> *urls;
  23. @property (nonatomic, nullable) NSTask *childTask;
  24. @property (nonatomic, nullable) tokenCallback_t activeToken;
  25. @end
  26. @implementation QEMUHelper
  27. @synthesize environment;
  28. @synthesize currentDirectoryPath;
  29. - (instancetype)init {
  30. if (self = [super init]) {
  31. self.urls = [NSMutableArray array];
  32. }
  33. return self;
  34. }
  35. - (void)dealloc {
  36. for (NSURL *url in self.urls) {
  37. [url stopAccessingSecurityScopedResource];
  38. }
  39. }
  40. - (void)accessDataWithBookmark:(NSData *)bookmark securityScoped:(BOOL)securityScoped completion:(void(^)(BOOL, NSData * _Nullable, NSString * _Nullable))completion {
  41. BOOL stale = NO;
  42. NSError *err;
  43. NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
  44. options:(securityScoped ? NSURLBookmarkResolutionWithSecurityScope : 0)
  45. relativeToURL:nil
  46. bookmarkDataIsStale:&stale
  47. error:&err];
  48. if (!url) {
  49. NSLog(@"Failed to access bookmark data.");
  50. completion(NO, nil, nil);
  51. return;
  52. }
  53. if (stale || !securityScoped) {
  54. bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
  55. includingResourceValuesForKeys:nil
  56. relativeToURL:nil
  57. error:&err];
  58. // if we fail, try again with read-only access
  59. if (!bookmark) {
  60. bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope | NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess
  61. includingResourceValuesForKeys:nil
  62. relativeToURL:nil
  63. error:&err];
  64. }
  65. if (!bookmark) {
  66. NSLog(@"Failed to create new bookmark!");
  67. completion(NO, bookmark, url.path);
  68. return;
  69. }
  70. }
  71. if ([url startAccessingSecurityScopedResource]) {
  72. [self.urls addObject:url];
  73. } else {
  74. NSLog(@"Failed to access security scoped resource for: %@", url);
  75. }
  76. completion(YES, bookmark, url.path);
  77. }
  78. - (void)stopAccessingPath:(nullable NSString *)path {
  79. if (!path) {
  80. return;
  81. }
  82. for (NSURL *url in _urls) {
  83. if ([url.path isEqualToString:path]) {
  84. [url stopAccessingSecurityScopedResource];
  85. [_urls removeObject:url];
  86. return;
  87. }
  88. }
  89. NSLog(@"Cannot find '%@' in existing scoped access.", path);
  90. }
  91. - (void)startQemu:(NSString *)binName standardOutput:(NSFileHandle *)standardOutput standardError:(NSFileHandle *)standardError libraryBookmark:(NSData *)libBookmark argv:(NSArray<NSString *> *)argv completion:(void(^)(BOOL,NSString *))completion {
  92. NSError *err;
  93. NSURL *libraryPath = [NSURL URLByResolvingBookmarkData:libBookmark
  94. options:0
  95. relativeToURL:nil
  96. bookmarkDataIsStale:nil
  97. error:&err];
  98. if (!libraryPath || ![[NSFileManager defaultManager] fileExistsAtPath:libraryPath.path]) {
  99. NSLog(@"Cannot resolve library path: %@", err);
  100. completion(NO, NSLocalizedString(@"Cannot find QEMU support libraries.", @"QEMUHelper"));
  101. return;
  102. }
  103. [self startQemuTask:binName standardOutput:standardOutput standardError:standardError libraryPath:libraryPath argv:argv completion:completion];
  104. }
  105. - (void)startQemuTask:(NSString *)binName standardOutput:(NSFileHandle *)standardOutput standardError:(NSFileHandle *)standardError libraryPath:(NSURL *)libraryPath argv:(NSArray<NSString *> *)argv completion:(void(^)(BOOL,NSString *))completion {
  106. NSError *err;
  107. NSTask *task = [NSTask new];
  108. NSMutableArray<NSString *> *newArgv = [argv mutableCopy];
  109. NSString *path = [libraryPath URLByAppendingPathComponent:binName].path;
  110. __weak typeof(self) _self = self;
  111. [newArgv insertObject:path atIndex:0];
  112. task.executableURL = [[[NSBundle mainBundle] URLForAuxiliaryExecutable:@"QEMULauncher.app"] URLByAppendingPathComponent:@"Contents/MacOS/QEMULauncher"];
  113. task.arguments = newArgv;
  114. task.standardOutput = standardOutput;
  115. task.standardError = standardError;
  116. NSMutableDictionary<NSString *, NSString *> *environment = [NSMutableDictionary dictionary];
  117. environment[@"TMPDIR"] = NSFileManager.defaultManager.temporaryDirectory.path;
  118. if (self.environment) {
  119. [environment addEntriesFromDictionary:self.environment];
  120. }
  121. task.environment = environment;
  122. if (self.currentDirectoryPath) {
  123. task.currentDirectoryURL = [NSURL fileURLWithPath:self.currentDirectoryPath];
  124. }
  125. task.qualityOfService = NSQualityOfServiceUserInitiated;
  126. task.terminationHandler = ^(NSTask *task) {
  127. _self.childTask = nil;
  128. [_self.connection.remoteObjectProxy processHasExited:task.terminationStatus message:nil];
  129. [_self invalidateToken];
  130. };
  131. if (![task launchAndReturnError:&err]) {
  132. NSLog(@"Error starting QEMU: %@", err);
  133. [self invalidateToken];
  134. completion(NO, err.localizedDescription);
  135. } else {
  136. self.childTask = task;
  137. completion(YES, nil);
  138. }
  139. }
  140. - (void)terminate {
  141. NSTask *childTask = self.childTask;
  142. self.childTask = nil;
  143. if (childTask) {
  144. void (^terminationHandler)(NSTask *) = childTask.terminationHandler;
  145. dispatch_semaphore_t terminatedEvent = dispatch_semaphore_create(0);
  146. childTask.terminationHandler = ^(NSTask *task) {
  147. terminationHandler(task);
  148. dispatch_semaphore_signal(terminatedEvent);
  149. };
  150. [childTask terminate];
  151. if (childTask.isRunning && dispatch_semaphore_wait(terminatedEvent, dispatch_time(DISPATCH_TIME_NOW, kProcessTerminateTimeoutSeconds*NSEC_PER_SEC)) != 0) {
  152. NSLog(@"Process %d failed to respond to SIGTERM, sending SIGKILL...", childTask.processIdentifier);
  153. kill(childTask.processIdentifier, SIGKILL);
  154. }
  155. }
  156. [self invalidateToken];
  157. }
  158. - (void)assertActiveWithToken:(tokenCallback_t)token {
  159. @synchronized (self) {
  160. if (self.activeToken) {
  161. self.activeToken(NO);
  162. }
  163. self.activeToken = token;
  164. }
  165. }
  166. - (void)invalidateToken {
  167. @synchronized (self) {
  168. if (self.activeToken) {
  169. self.activeToken(YES);
  170. }
  171. self.activeToken = nil;
  172. }
  173. }
  174. @end