1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import <Foundation/Foundation.h>
11 // An executable (iossim) that runs an app in the iOS Simulator.
12 // Run 'iossim -h' for usage information.
14 // For best results, the iOS Simulator application should not be running when
17 // Headers for iPhoneSimulatorRemoteClient and other frameworks used in this
18 // tool are generated by class-dump, via GYP.
19 // (class-dump is available at http://www.codethecode.com/projects/class-dump/)
21 // However, there are some forward declarations required to get things to
24 // TODO(lliabraa): Once all builders are on Xcode 6 this ifdef can be removed
25 // (crbug.com/385030).
26 #if defined(IOSSIM_USE_XCODE_6)
27 @class DVTStackBacktrace;
28 #import "DVTFoundation.h"
29 #endif // IOSSIM_USE_XCODE_6
31 @protocol OS_dispatch_queue
33 @protocol OS_dispatch_source
35 // TODO(lliabraa): Once all builders are on Xcode 6 this ifdef can be removed
36 // (crbug.com/385030).
37 #if defined(IOSSIM_USE_XCODE_6)
38 @protocol OS_xpc_object
44 @class SimServiceConnectionManager;
45 #import "CoreSimulator.h"
46 #endif // IOSSIM_USE_XCODE_6
48 @interface DVTPlatform : NSObject
49 + (BOOL)loadAllPlatformsReturningError:(id*)arg1;
51 @class DTiPhoneSimulatorApplicationSpecifier;
52 @class DTiPhoneSimulatorSession;
53 @class DTiPhoneSimulatorSessionConfig;
54 @class DTiPhoneSimulatorSystemRoot;
55 @class DVTConfinementServiceConnection;
56 @class DVTDispatchLock;
57 @class DVTiPhoneSimulatorMessenger;
58 @class DVTNotificationToken;
60 // The DTiPhoneSimulatorSessionDelegate protocol is referenced
61 // by the iPhoneSimulatorRemoteClient framework, but not defined in the object
62 // file, so it must be defined here before importing the generated
63 // iPhoneSimulatorRemoteClient.h file.
64 @protocol DTiPhoneSimulatorSessionDelegate
65 - (void)session:(DTiPhoneSimulatorSession*)session
66 didEndWithError:(NSError*)error;
67 - (void)session:(DTiPhoneSimulatorSession*)session
68 didStart:(BOOL)started
69 withError:(NSError*)error;
71 #import "DVTiPhoneSimulatorRemoteClient.h"
73 // An undocumented system log key included in messages from launchd. The value
74 // is the PID of the process the message is about (as opposed to launchd's PID).
75 #define ASL_KEY_REF_PID "RefPID"
79 // Name of environment variables that control the user's home directory in the
81 const char* const kUserHomeEnvVariable = "CFFIXED_USER_HOME";
82 const char* const kHomeEnvVariable = "HOME";
84 // Device family codes for iPhone and iPad.
85 const int kIPhoneFamily = 1;
86 const int kIPadFamily = 2;
88 // Max number of seconds to wait for the simulator session to start.
89 // This timeout must allow time to start up iOS Simulator, install the app
90 // and perform any other black magic that is encoded in the
91 // iPhoneSimulatorRemoteClient framework to kick things off. Normal start up
92 // time is only a couple seconds but machine load, disk caches, etc., can all
93 // affect startup time in the wild so the timeout needs to be fairly generous.
94 // If this timeout occurs iossim will likely exit with non-zero status; the
95 // exception being if the app is invoked and completes execution before the
96 // session is started (this case is handled in session:didStart:withError).
97 const NSTimeInterval kDefaultSessionStartTimeoutSeconds = 30;
99 // While the simulated app is running, its stdout is redirected to a file which
100 // is polled by iossim and written to iossim's stdout using the following
102 const NSTimeInterval kOutputPollIntervalSeconds = 0.1;
104 NSString* const kDVTFoundationRelativePath =
105 @"../SharedFrameworks/DVTFoundation.framework";
106 NSString* const kDevToolsFoundationRelativePath =
107 @"../OtherFrameworks/DevToolsFoundation.framework";
108 NSString* const kSimulatorRelativePath =
109 @"Platforms/iPhoneSimulator.platform/Developer/Applications/"
110 @"iPhone Simulator.app";
112 // Simulator Error String Key. This can be found by looking in the Simulator's
113 // Localizable.strings files.
114 NSString* const kSimulatorAppQuitErrorKey = @"The simulated application quit.";
116 const char* gToolName = "iossim";
118 // Exit status codes.
119 const int kExitSuccess = EXIT_SUCCESS;
120 const int kExitFailure = EXIT_FAILURE;
121 const int kExitInvalidArguments = 2;
122 const int kExitInitializationFailure = 3;
123 const int kExitAppFailedToStart = 4;
124 const int kExitAppCrashed = 5;
125 const int kExitUnsupportedXcodeVersion = 6;
127 void LogError(NSString* format, ...) {
129 va_start(list, format);
132 [[[NSString alloc] initWithFormat:format arguments:list] autorelease];
134 fprintf(stderr, "%s: ERROR: %s\n", gToolName, [message UTF8String]);
140 void LogWarning(NSString* format, ...) {
142 va_start(list, format);
145 [[[NSString alloc] initWithFormat:format arguments:list] autorelease];
147 fprintf(stderr, "%s: WARNING: %s\n", gToolName, [message UTF8String]);
153 // Helper to find a class by name and die if it isn't found.
154 Class FindClassByName(NSString* nameOfClass) {
155 Class theClass = NSClassFromString(nameOfClass);
157 LogError(@"Failed to find class %@ at runtime.", nameOfClass);
158 exit(kExitInitializationFailure);
163 // Returns the a NSString containing the stdout from running an NSTask that
164 // launches |toolPath| with th given command line |args|.
165 NSString* GetOutputFromTask(NSString* toolPath, NSArray* args) {
166 NSTask* task = [[[NSTask alloc] init] autorelease];
167 [task setLaunchPath:toolPath];
168 [task setArguments:args];
169 NSPipe* outputPipe = [NSPipe pipe];
170 [task setStandardOutput:outputPipe];
171 NSFileHandle* outputFile = [outputPipe fileHandleForReading];
174 NSData* outputData = [outputFile readDataToEndOfFile];
175 [task waitUntilExit];
176 if ([task isRunning]) {
177 LogError(@"Task '%@ %@' is still running.",
179 [args componentsJoinedByString:@" "]);
181 } else if ([task terminationStatus]) {
182 LogError(@"Task '%@ %@' exited with return code %d.",
184 [args componentsJoinedByString:@" "],
185 [task terminationStatus]);
188 return [[[NSString alloc] initWithData:outputData
189 encoding:NSUTF8StringEncoding] autorelease];
192 // Finds the Xcode version via xcodebuild -version. Output from xcodebuild is
193 // expected to look like:
195 // Build version 5B130a
196 // where <version> is the string returned by this function (e.g. 6.0).
197 NSString* FindXcodeVersion() {
198 NSString* output = GetOutputFromTask(@"/usr/bin/xcodebuild",
200 // Scan past the "Xcode ", then scan the rest of the line into |version|.
201 NSScanner* scanner = [NSScanner scannerWithString:output];
202 BOOL valid = [scanner scanString:@"Xcode " intoString:NULL];
205 [scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet]
206 intoString:&version];
208 LogError(@"Unable to find Xcode version. 'xcodebuild -version' "
209 @"returned \n%@", output);
215 // Returns true if iossim is running with Xcode 6 or later installed on the
217 BOOL IsRunningWithXcode6OrLater() {
218 static NSString* xcodeVersion = FindXcodeVersion();
222 NSArray* components = [xcodeVersion componentsSeparatedByString:@"."];
223 if ([components count] < 1) {
226 NSInteger majorVersion = [[components objectAtIndex:0] integerValue];
227 return majorVersion >= 6;
230 // Prints supported devices and SDKs.
231 void PrintSupportedDevices() {
232 if (IsRunningWithXcode6OrLater()) {
233 #if defined(IOSSIM_USE_XCODE_6)
234 printf("Supported device/SDK combinations:\n");
235 Class simDeviceSetClass = FindClassByName(@"SimDeviceSet");
237 [simDeviceSetClass setForSetPath:[simDeviceSetClass defaultSetPath]];
238 for (id simDevice in [deviceSet availableDevices]) {
239 NSString* deviceInfo =
240 [NSString stringWithFormat:@" -d '%@' -s '%@'\n",
241 [simDevice name], [[simDevice runtime] versionString]];
242 printf("%s", [deviceInfo UTF8String]);
244 #endif // IOSSIM_USE_XCODE_6
246 printf("Supported SDK versions:\n");
247 Class rootClass = FindClassByName(@"DTiPhoneSimulatorSystemRoot");
248 for (id root in [rootClass knownRoots]) {
249 printf(" '%s'\n", [[root sdkVersion] UTF8String]);
251 // This is the list of devices supported on Xcode 5.1.x.
252 printf("Supported devices:\n");
253 printf(" 'iPhone'\n");
254 printf(" 'iPhone Retina (3.5-inch)'\n");
255 printf(" 'iPhone Retina (4-inch)'\n");
256 printf(" 'iPhone Retina (4-inch 64-bit)'\n");
258 printf(" 'iPad Retina'\n");
259 printf(" 'iPad Retina (64-bit)'\n");
264 // A delegate that is called when the simulated app is started or ended in the
266 @interface SimulatorDelegate : NSObject <DTiPhoneSimulatorSessionDelegate> {
268 NSString* stdioPath_;
269 NSString* developerDir_;
270 NSString* simulatorHome_;
271 NSThread* outputThread_;
272 NSBundle* simulatorBundle_;
277 // An implementation that copies the simulated app's stdio to stdout of this
278 // executable. While it would be nice to get stdout and stderr independently
279 // from iOS Simulator, issues like I/O buffering and interleaved output
280 // between iOS Simulator and the app would cause iossim to display things out
281 // of order here. Printing all output to a single file keeps the order correct.
282 // Instances of this classe should be initialized with the location of the
283 // simulated app's output file. When the simulated app starts, a thread is
284 // started which handles copying data from the simulated app's output file to
285 // the stdout of this executable.
286 @implementation SimulatorDelegate
288 // Specifies the file locations of the simulated app's stdout and stderr.
289 - (SimulatorDelegate*)initWithStdioPath:(NSString*)stdioPath
290 developerDir:(NSString*)developerDir
291 simulatorHome:(NSString*)simulatorHome {
294 stdioPath_ = [stdioPath copy];
295 developerDir_ = [developerDir copy];
296 simulatorHome_ = [simulatorHome copy];
303 [stdioPath_ release];
304 [developerDir_ release];
305 [simulatorBundle_ release];
309 // Reads data from the simulated app's output and writes it to stdout. This
310 // method blocks, so it should be called in a separate thread. The iOS
311 // Simulator takes a file path for the simulated app's stdout and stderr, but
312 // this path isn't always available (e.g. when the stdout is Xcode's build
313 // window). As a workaround, iossim creates a temp file to hold output, which
314 // this method reads and copies to stdout.
315 - (void)tailOutputForSession:(DTiPhoneSimulatorSession*)session {
316 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
318 NSFileHandle* simio = [NSFileHandle fileHandleForReadingAtPath:stdioPath_];
319 if (IsRunningWithXcode6OrLater()) {
320 #if defined(IOSSIM_USE_XCODE_6)
321 // With iOS 8 simulators on Xcode 6, the app output is relative to the
322 // simulator's data directory.
323 NSString* versionString =
324 [[[session sessionConfig] simulatedSystemRoot] sdkVersion];
325 NSInteger majorVersion = [[[versionString componentsSeparatedByString:@"."]
326 objectAtIndex:0] intValue];
327 if (majorVersion >= 8) {
328 NSString* dataPath = session.sessionConfig.device.dataPath;
329 NSString* appOutput =
330 [dataPath stringByAppendingPathComponent:stdioPath_];
331 simio = [NSFileHandle fileHandleForReadingAtPath:appOutput];
333 #endif // IOSSIM_USE_XCODE_6
335 NSFileHandle* standardOutput = [NSFileHandle fileHandleWithStandardOutput];
336 // Copy data to stdout/stderr while the app is running.
337 while (appRunning_) {
338 NSAutoreleasePool* innerPool = [[NSAutoreleasePool alloc] init];
339 [standardOutput writeData:[simio readDataToEndOfFile]];
340 [NSThread sleepForTimeInterval:kOutputPollIntervalSeconds];
344 // Once the app is no longer running, copy any data that was written during
345 // the last sleep cycle.
346 [standardOutput writeData:[simio readDataToEndOfFile]];
351 // Fetches a localized error string from the Simulator.
352 - (NSString *)localizedSimulatorErrorString:(NSString*)stringKey {
353 // Lazy load of the simulator bundle.
354 if (simulatorBundle_ == nil) {
355 NSString* simulatorPath = [developerDir_
356 stringByAppendingPathComponent:kSimulatorRelativePath];
357 simulatorBundle_ = [NSBundle bundleWithPath:simulatorPath];
359 NSString *localizedStr =
360 [simulatorBundle_ localizedStringForKey:stringKey
363 if ([localizedStr length])
365 // Failed to get a value, follow Cocoa conventions and use the key as the
370 - (void)session:(DTiPhoneSimulatorSession*)session
371 didStart:(BOOL)started
372 withError:(NSError*)error {
374 // If the test executes very quickly (<30ms), the SimulatorDelegate may not
375 // get the initial session:started:withError: message indicating successful
376 // startup of the simulated app. Instead the delegate will get a
377 // session:started:withError: message after the timeout has elapsed. To
378 // account for this case, check if the simulated app's stdio file was
379 // ever created and if it exists dump it to stdout and return success.
380 NSFileManager* fileManager = [NSFileManager defaultManager];
381 if ([fileManager fileExistsAtPath:stdioPath_]) {
383 [self tailOutputForSession:session];
384 // Note that exiting in this state leaves a process running
385 // (e.g. /.../iPhoneSimulator4.3.sdk/usr/libexec/installd -t 30) that will
386 // prevent future simulator sessions from being started for 30 seconds
387 // unless the iOS Simulator application is killed altogether.
388 [self session:session didEndWithError:nil];
390 // session:didEndWithError should not return (because it exits) so
391 // the execution path should never get here.
395 LogError(@"Simulator failed to start: \"%@\" (%@:%ld)",
396 [error localizedDescription],
397 [error domain], static_cast<long int>([error code]));
398 PrintSupportedDevices();
399 exit(kExitAppFailedToStart);
402 // Start a thread to write contents of outputPath to stdout.
405 [[NSThread alloc] initWithTarget:self
406 selector:@selector(tailOutputForSession:)
408 [outputThread_ start];
411 - (void)session:(DTiPhoneSimulatorSession*)session
412 didEndWithError:(NSError*)error {
414 // Wait for the output thread to finish copying data to stdout.
416 while (![outputThread_ isFinished]) {
417 [NSThread sleepForTimeInterval:kOutputPollIntervalSeconds];
419 [outputThread_ release];
424 // There appears to be a race condition where sometimes the simulator
425 // framework will end with an error, but the error is that the simulated
426 // app cleanly shut down; try to trap this error and don't fail the
428 NSString* localizedDescription = [error localizedDescription];
429 NSString* ignorableErrorStr =
430 [self localizedSimulatorErrorString:kSimulatorAppQuitErrorKey];
431 if ([ignorableErrorStr isEqual:localizedDescription]) {
432 LogWarning(@"Ignoring that Simulator ended with: \"%@\" (%@:%ld)",
433 localizedDescription, [error domain],
434 static_cast<long int>([error code]));
436 LogError(@"Simulator ended with error: \"%@\" (%@:%ld)",
437 localizedDescription, [error domain],
438 static_cast<long int>([error code]));
443 // Try to determine if the simulated app crashed or quit with a non-zero
444 // status code. iOS Simluator handles things a bit differently depending on
445 // the version, so first determine the iOS version being used.
446 BOOL badEntryFound = NO;
447 NSString* versionString =
448 [[[session sessionConfig] simulatedSystemRoot] sdkVersion];
449 NSInteger majorVersion = [[[versionString componentsSeparatedByString:@"."]
450 objectAtIndex:0] intValue];
451 if (majorVersion <= 6) {
452 // In iOS 6 and before, logging from the simulated apps went to the main
453 // system logs, so use ASL to check if the simulated app exited abnormally
454 // by looking for system log messages from launchd that refer to the
455 // simulated app's PID. Limit query to messages in the last minute since
456 // PIDs are cyclical.
457 aslmsg query = asl_new(ASL_TYPE_QUERY);
458 asl_set_query(query, ASL_KEY_SENDER, "launchd",
459 ASL_QUERY_OP_EQUAL | ASL_QUERY_OP_SUBSTRING);
461 if (snprintf(session_id, 20, "%d", [session simulatedApplicationPID]) < 0) {
462 LogError(@"Failed to get [session simulatedApplicationPID]");
465 asl_set_query(query, ASL_KEY_REF_PID, session_id, ASL_QUERY_OP_EQUAL);
466 asl_set_query(query, ASL_KEY_TIME, "-1m", ASL_QUERY_OP_GREATER_EQUAL);
468 // Log any messages found, and take note of any messages that may indicate
469 // the app crashed or did not exit cleanly.
470 aslresponse response = asl_search(NULL, query);
472 while ((entry = aslresponse_next(response)) != NULL) {
473 const char* message = asl_get(entry, ASL_KEY_MSG);
474 LogWarning(@"Console message: %s", message);
475 // Some messages are harmless, so don't trigger a failure for them.
476 if (strstr(message, "The following job tried to hijack the service"))
481 // Otherwise, the iOS Simulator's system logging is sandboxed, so parse the
482 // sandboxed system.log file for known errors.
484 if (IsRunningWithXcode6OrLater()) {
485 #if defined(IOSSIM_USE_XCODE_6)
486 NSString* dataPath = session.sessionConfig.device.dataPath;
488 [dataPath stringByAppendingPathComponent:@"Library/Logs/system.log"];
489 #endif // IOSSIM_USE_XCODE_6
491 NSString* relativePathToSystemLog =
492 [NSString stringWithFormat:
493 @"Library/Logs/iOS Simulator/%@/system.log", versionString];
494 path = [simulatorHome_
495 stringByAppendingPathComponent:relativePathToSystemLog];
497 NSFileManager* fileManager = [NSFileManager defaultManager];
498 if ([fileManager fileExistsAtPath:path]) {
500 [NSString stringWithContentsOfFile:path
501 encoding:NSUTF8StringEncoding
503 NSArray* lines = [content componentsSeparatedByCharactersInSet:
504 [NSCharacterSet newlineCharacterSet]];
505 NSString* simulatedAppPID =
506 [NSString stringWithFormat:@"%d", session.simulatedApplicationPID];
507 for (NSString* line in lines) {
508 NSString* const kErrorString = @"Service exited with abnormal code:";
509 if ([line rangeOfString:kErrorString].location != NSNotFound &&
510 [line rangeOfString:simulatedAppPID].location != NSNotFound) {
511 LogWarning(@"Console message: %@", line);
516 // Remove the log file so subsequent invocations of iossim won't be
517 // looking at stale logs.
518 remove([path fileSystemRepresentation]);
520 LogWarning(@"Unable to find system log at '%@'.", path);
524 // If the query returned any nasty-looking results, iossim should exit with
527 LogError(@"Simulated app crashed or exited with non-zero status");
528 exit(kExitAppCrashed);
536 // Finds the developer dir via xcode-select or the DEVELOPER_DIR environment
538 NSString* FindDeveloperDir() {
539 // Check the env first.
540 NSDictionary* env = [[NSProcessInfo processInfo] environment];
541 NSString* developerDir = [env objectForKey:@"DEVELOPER_DIR"];
542 if ([developerDir length] > 0)
545 // Go look for it via xcode-select.
546 NSString* output = GetOutputFromTask(@"/usr/bin/xcode-select",
547 @[ @"-print-path" ]);
548 output = [output stringByTrimmingCharactersInSet:
549 [NSCharacterSet whitespaceAndNewlineCharacterSet]];
550 if ([output length] == 0)
555 // Loads the Simulator framework from the given developer dir.
556 NSBundle* LoadSimulatorFramework(NSString* developerDir) {
557 // The Simulator framework depends on some of the other Xcode private
558 // frameworks; manually load them first so everything can be linked up.
559 NSString* dvtFoundationPath = [developerDir
560 stringByAppendingPathComponent:kDVTFoundationRelativePath];
561 NSBundle* dvtFoundationBundle =
562 [NSBundle bundleWithPath:dvtFoundationPath];
563 if (![dvtFoundationBundle load])
566 NSString* devToolsFoundationPath = [developerDir
567 stringByAppendingPathComponent:kDevToolsFoundationRelativePath];
568 NSBundle* devToolsFoundationBundle =
569 [NSBundle bundleWithPath:devToolsFoundationPath];
570 if (![devToolsFoundationBundle load])
573 // Prime DVTPlatform.
575 Class DVTPlatformClass = FindClassByName(@"DVTPlatform");
576 if (![DVTPlatformClass loadAllPlatformsReturningError:&error]) {
577 LogError(@"Unable to loadAllPlatformsReturningError. Error: %@",
578 [error localizedDescription]);
582 // The path within the developer dir of the private Simulator frameworks.
583 NSString* simulatorFrameworkRelativePath;
584 if (IsRunningWithXcode6OrLater()) {
585 simulatorFrameworkRelativePath =
586 @"../SharedFrameworks/DVTiPhoneSimulatorRemoteClient.framework";
587 NSString* const kCoreSimulatorRelativePath =
588 @"Library/PrivateFrameworks/CoreSimulator.framework";
589 NSString* coreSimulatorPath = [developerDir
590 stringByAppendingPathComponent:kCoreSimulatorRelativePath];
591 NSBundle* coreSimulatorBundle =
592 [NSBundle bundleWithPath:coreSimulatorPath];
593 if (![coreSimulatorBundle load])
596 simulatorFrameworkRelativePath =
597 @"Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/"
598 @"DVTiPhoneSimulatorRemoteClient.framework";
600 NSString* simBundlePath = [developerDir
601 stringByAppendingPathComponent:simulatorFrameworkRelativePath];
602 NSBundle* simBundle = [NSBundle bundleWithPath:simBundlePath];
603 if (![simBundle load])
608 // Converts the given app path to an application spec, which requires an
610 DTiPhoneSimulatorApplicationSpecifier* BuildAppSpec(NSString* appPath) {
611 Class applicationSpecifierClass =
612 FindClassByName(@"DTiPhoneSimulatorApplicationSpecifier");
613 if (![appPath isAbsolutePath]) {
614 NSString* cwd = [[NSFileManager defaultManager] currentDirectoryPath];
615 appPath = [cwd stringByAppendingPathComponent:appPath];
617 appPath = [appPath stringByStandardizingPath];
618 NSFileManager* fileManager = [NSFileManager defaultManager];
619 if (![fileManager fileExistsAtPath:appPath]) {
620 LogError(@"File not found: %@", appPath);
621 exit(kExitInvalidArguments);
623 return [applicationSpecifierClass specifierWithApplicationPath:appPath];
626 // Returns the system root for the given SDK version. If sdkVersion is nil, the
627 // default system root is returned. Will return nil if the sdkVersion is not
629 DTiPhoneSimulatorSystemRoot* BuildSystemRoot(NSString* sdkVersion) {
630 Class systemRootClass = FindClassByName(@"DTiPhoneSimulatorSystemRoot");
631 DTiPhoneSimulatorSystemRoot* systemRoot = [systemRootClass defaultRoot];
633 systemRoot = [systemRootClass rootWithSDKVersion:sdkVersion];
638 // Builds a config object for starting the specified app.
639 DTiPhoneSimulatorSessionConfig* BuildSessionConfig(
640 DTiPhoneSimulatorApplicationSpecifier* appSpec,
641 DTiPhoneSimulatorSystemRoot* systemRoot,
642 NSString* stdoutPath,
643 NSString* stderrPath,
645 NSDictionary* appEnv,
646 NSNumber* deviceFamily,
647 NSString* deviceName) {
648 Class sessionConfigClass = FindClassByName(@"DTiPhoneSimulatorSessionConfig");
649 DTiPhoneSimulatorSessionConfig* sessionConfig =
650 [[[sessionConfigClass alloc] init] autorelease];
651 sessionConfig.applicationToSimulateOnStart = appSpec;
652 sessionConfig.simulatedSystemRoot = systemRoot;
653 sessionConfig.localizedClientName = @"chromium";
654 sessionConfig.simulatedApplicationStdErrPath = stderrPath;
655 sessionConfig.simulatedApplicationStdOutPath = stdoutPath;
656 sessionConfig.simulatedApplicationLaunchArgs = appArgs;
657 sessionConfig.simulatedApplicationLaunchEnvironment = appEnv;
658 sessionConfig.simulatedDeviceInfoName = deviceName;
659 sessionConfig.simulatedDeviceFamily = deviceFamily;
661 if (IsRunningWithXcode6OrLater()) {
662 #if defined(IOSSIM_USE_XCODE_6)
663 Class simDeviceTypeClass = FindClassByName(@"SimDeviceType");
665 [simDeviceTypeClass supportedDeviceTypesByName][deviceName];
666 Class simRuntimeClass = FindClassByName(@"SimRuntime");
667 NSString* identifier = systemRoot.runtime.identifier;
668 id simRuntime = [simRuntimeClass supportedRuntimesByIdentifier][identifier];
670 // Attempt to use an existing device, but create one if a suitable match
671 // can't be found. For example, if the simulator is running with a
672 // non-default home directory (e.g. via iossim's -u command line arg) then
673 // there won't be any devices so one will have to be created.
674 Class simDeviceSetClass = FindClassByName(@"SimDeviceSet");
676 [simDeviceSetClass setForSetPath:[simDeviceSetClass defaultSetPath]];
678 for (id device in [deviceSet availableDevices]) {
679 if ([device runtime] == simRuntime &&
680 [device deviceType] == simDeviceType) {
686 NSError* error = nil;
687 // n.b. only the device name is necessary because the iOS Simulator menu
688 // already splits devices by runtime version.
689 NSString* name = [NSString stringWithFormat:@"iossim - %@ ", deviceName];
690 simDevice = [deviceSet createDeviceWithType:simDeviceType
695 LogError(@"Failed to create device: %@", error);
696 exit(kExitInitializationFailure);
699 sessionConfig.device = simDevice;
700 #endif // IOSSIM_USE_XCODE_6
702 return sessionConfig;
705 // Builds a simulator session that will use the given delegate.
706 DTiPhoneSimulatorSession* BuildSession(SimulatorDelegate* delegate) {
707 Class sessionClass = FindClassByName(@"DTiPhoneSimulatorSession");
708 DTiPhoneSimulatorSession* session =
709 [[[sessionClass alloc] init] autorelease];
710 session.delegate = delegate;
714 // Creates a temporary directory with a unique name based on the provided
715 // template. The template should not contain any path separators and be suffixed
716 // with X's, which will be substituted with a unique alphanumeric string (see
717 // 'man mkdtemp' for details). The directory will be created as a subdirectory
718 // of NSTemporaryDirectory(). For example, if dirNameTemplate is 'test-XXX',
719 // this method would return something like '/path/to/tempdir/test-3n2'.
721 // Returns the absolute path of the newly-created directory, or nill if unable
722 // to create a unique directory.
723 NSString* CreateTempDirectory(NSString* dirNameTemplate) {
724 NSString* fullPathTemplate =
725 [NSTemporaryDirectory() stringByAppendingPathComponent:dirNameTemplate];
726 char* fullPath = mkdtemp(const_cast<char*>([fullPathTemplate UTF8String]));
727 if (fullPath == NULL)
730 return [NSString stringWithUTF8String:fullPath];
733 // Creates the necessary directory structure under the given user home directory
735 // Returns YES if successful, NO if unable to create the directories.
736 BOOL CreateHomeDirSubDirs(NSString* userHomePath) {
737 NSFileManager* fileManager = [NSFileManager defaultManager];
739 // Create user home and subdirectories.
740 NSArray* subDirsToCreate = [NSArray arrayWithObjects:
743 @"Library/Preferences",
745 for (NSString* subDir in subDirsToCreate) {
746 NSString* path = [userHomePath stringByAppendingPathComponent:subDir];
748 if (![fileManager createDirectoryAtPath:path
749 withIntermediateDirectories:YES
752 LogError(@"Unable to create directory: %@. Error: %@",
753 path, [error localizedDescription]);
761 // Creates the necessary directory structure under the given user home directory
762 // path, then sets the path in the appropriate environment variable.
763 // Returns YES if successful, NO if unable to create or initialize the given
765 BOOL InitializeSimulatorUserHome(NSString* userHomePath) {
766 if (!CreateHomeDirSubDirs(userHomePath))
769 // Update the environment to use the specified directory as the user home
771 // Note: the third param of setenv specifies whether or not to overwrite the
772 // variable's value if it has already been set.
773 if ((setenv(kUserHomeEnvVariable, [userHomePath UTF8String], YES) == -1) ||
774 (setenv(kHomeEnvVariable, [userHomePath UTF8String], YES) == -1)) {
775 LogError(@"Unable to set environment variables for home directory.");
782 // Performs a case-insensitive search to see if |stringToSearch| begins with
783 // |prefixToFind|. Returns true if a match is found.
784 BOOL CaseInsensitivePrefixSearch(NSString* stringToSearch,
785 NSString* prefixToFind) {
786 NSStringCompareOptions options = (NSAnchoredSearch | NSCaseInsensitiveSearch);
787 NSRange range = [stringToSearch rangeOfString:prefixToFind
789 return range.location != NSNotFound;
792 // Prints the usage information to stderr.
794 fprintf(stderr, "Usage: iossim [-d device] [-s sdkVersion] [-u homeDir] "
795 "[-e envKey=value]* [-t startupTimeout] <appPath> [<appArgs>]\n"
796 " where <appPath> is the path to the .app directory and appArgs are any"
797 " arguments to send the simulated app.\n"
800 " -d Specifies the device (must be one of the values from the iOS"
801 " Simulator's Hardware -> Device menu. Defaults to 'iPhone'.\n"
802 " -s Specifies the SDK version to use (e.g '4.3')."
803 " Will use system default if not specified.\n"
804 " -u Specifies a user home directory for the simulator."
805 " Will create a new directory if not specified.\n"
806 " -e Specifies an environment key=value pair that will be"
807 " set in the simulated application's environment.\n"
808 " -t Specifies the session startup timeout (in seconds)."
810 " -l List supported devices and iOS versions.\n",
811 static_cast<int>(kDefaultSessionStartTimeoutSeconds));
815 void EnsureSupportForCurrentXcodeVersion() {
816 if (IsRunningWithXcode6OrLater()) {
817 #if !IOSSIM_USE_XCODE_6
818 LogError(@"Running on Xcode 6, but Xcode 6 support was not compiled in.");
819 exit(kExitUnsupportedXcodeVersion);
820 #endif // IOSSIM_USE_XCODE_6
824 int main(int argc, char* const argv[]) {
825 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
827 EnsureSupportForCurrentXcodeVersion();
829 // basename() may modify the passed in string and it returns a pointer to an
830 // internal buffer. Give it a copy to modify, and copy what it returns.
831 char* worker = strdup(argv[0]);
832 char* toolName = basename(worker);
833 if (toolName != NULL) {
834 toolName = strdup(toolName);
835 if (toolName != NULL)
836 gToolName = toolName;
841 NSString* appPath = nil;
842 NSString* appName = nil;
843 NSString* sdkVersion = nil;
844 NSString* deviceName = IsRunningWithXcode6OrLater() ? @"iPhone 5" : @"iPhone";
845 NSString* simHomePath = nil;
846 NSMutableArray* appArgs = [NSMutableArray array];
847 NSMutableDictionary* appEnv = [NSMutableDictionary dictionary];
848 NSTimeInterval sessionStartTimeout = kDefaultSessionStartTimeoutSeconds;
850 NSString* developerDir = FindDeveloperDir();
852 LogError(@"Unable to find developer directory.");
853 exit(kExitInitializationFailure);
856 NSBundle* simulatorFramework = LoadSimulatorFramework(developerDir);
857 if (!simulatorFramework) {
858 LogError(@"Failed to load the Simulator Framework.");
859 exit(kExitInitializationFailure);
862 // Parse the optional arguments
864 while ((c = getopt(argc, argv, "hs:d:u:e:t:l")) != -1) {
867 sdkVersion = [NSString stringWithUTF8String:optarg];
870 deviceName = [NSString stringWithUTF8String:optarg];
873 simHomePath = [[NSFileManager defaultManager]
874 stringWithFileSystemRepresentation:optarg length:strlen(optarg)];
877 NSString* envLine = [NSString stringWithUTF8String:optarg];
878 NSRange range = [envLine rangeOfString:@"="];
879 if (range.location == NSNotFound) {
880 LogError(@"Invalid key=value argument for -e.");
882 exit(kExitInvalidArguments);
884 NSString* key = [envLine substringToIndex:range.location];
885 NSString* value = [envLine substringFromIndex:(range.location + 1)];
886 [appEnv setObject:value forKey:key];
890 int timeout = atoi(optarg);
892 sessionStartTimeout = static_cast<NSTimeInterval>(timeout);
894 LogError(@"Invalid startup timeout (%s).", optarg);
896 exit(kExitInvalidArguments);
901 PrintSupportedDevices();
909 exit(kExitInvalidArguments);
913 // There should be at least one arg left, specifying the app path. Any
914 // additional args are passed as arguments to the app.
916 appPath = [[NSFileManager defaultManager]
917 stringWithFileSystemRepresentation:argv[optind]
918 length:strlen(argv[optind])];
919 appName = [appPath lastPathComponent];
920 while (++optind < argc) {
921 [appArgs addObject:[NSString stringWithUTF8String:argv[optind]]];
924 LogError(@"Unable to parse command line arguments.");
926 exit(kExitInvalidArguments);
929 // Make sure the app path provided is legit.
930 DTiPhoneSimulatorApplicationSpecifier* appSpec = BuildAppSpec(appPath);
932 LogError(@"Invalid app path: %@", appPath);
933 exit(kExitInitializationFailure);
936 // Make sure the SDK path provided is legit (or nil).
937 DTiPhoneSimulatorSystemRoot* systemRoot = BuildSystemRoot(sdkVersion);
939 LogError(@"Invalid SDK version: %@", sdkVersion);
940 PrintSupportedDevices();
941 exit(kExitInitializationFailure);
944 // Get the paths for stdout and stderr so the simulated app's output will show
945 // up in the caller's stdout/stderr.
946 NSString* outputDir = CreateTempDirectory(@"iossim-XXXXXX");
947 NSString* stdioPath = [outputDir stringByAppendingPathComponent:@"stdio.txt"];
949 // Determine the deviceFamily based on the deviceName
950 NSNumber* deviceFamily = nil;
951 if (IsRunningWithXcode6OrLater()) {
952 #if defined(IOSSIM_USE_XCODE_6)
953 Class simDeviceTypeClass = FindClassByName(@"SimDeviceType");
954 if ([simDeviceTypeClass supportedDeviceTypesByName][deviceName] == nil) {
955 LogError(@"Invalid device name: %@.", deviceName);
956 PrintSupportedDevices();
957 exit(kExitInvalidArguments);
959 #endif // IOSSIM_USE_XCODE_6
961 if (!deviceName || CaseInsensitivePrefixSearch(deviceName, @"iPhone")) {
962 deviceFamily = [NSNumber numberWithInt:kIPhoneFamily];
963 } else if (CaseInsensitivePrefixSearch(deviceName, @"iPad")) {
964 deviceFamily = [NSNumber numberWithInt:kIPadFamily];
967 LogError(@"Invalid device name: %@. Must begin with 'iPhone' or 'iPad'",
969 exit(kExitInvalidArguments);
973 // Set up the user home directory for the simulator only if a non-default
974 // value was specified.
976 if (!InitializeSimulatorUserHome(simHomePath)) {
977 LogError(@"Unable to initialize home directory for simulator: %@",
979 exit(kExitInitializationFailure);
982 simHomePath = NSHomeDirectory();
985 // Create the config and simulator session.
986 DTiPhoneSimulatorSessionConfig* config = BuildSessionConfig(appSpec,
994 SimulatorDelegate* delegate =
995 [[[SimulatorDelegate alloc] initWithStdioPath:stdioPath
996 developerDir:developerDir
997 simulatorHome:simHomePath] autorelease];
998 DTiPhoneSimulatorSession* session = BuildSession(delegate);
1000 // Start the simulator session.
1002 BOOL started = [session requestStartWithConfig:config
1003 timeout:sessionStartTimeout
1006 // Spin the runtime indefinitely. When the delegate gets the message that the
1007 // app has quit it will exit this program.
1009 [[NSRunLoop mainRunLoop] run];
1011 LogError(@"Simulator failed request to start: \"%@\" (%@:%ld)",
1012 [error localizedDescription],
1013 [error domain], static_cast<long int>([error code]));
1016 // Note that this code is only executed if the simulator fails to start
1017 // because once the main run loop is started, only the delegate calling
1018 // exit() will end the program.
1020 return kExitFailure;