Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / testing / iossim / iossim.mm
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.
4
5 #import <Foundation/Foundation.h>
6 #include <asl.h>
7 #include <libgen.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10
11 // An executable (iossim) that runs an app in the iOS Simulator.
12 // Run 'iossim -h' for usage information.
13 //
14 // For best results, the iOS Simulator application should not be running when
15 // iossim is invoked.
16 //
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/)
20 //
21 // However, there are some forward declarations required to get things to
22 // compile.
23
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
30
31 @protocol OS_dispatch_queue
32 @end
33 @protocol OS_dispatch_source
34 @end
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
39 @end
40 @protocol SimBridge;
41 @class SimDeviceSet;
42 @class SimDeviceType;
43 @class SimRuntime;
44 @class SimServiceConnectionManager;
45 #import "CoreSimulator.h"
46 #endif  // IOSSIM_USE_XCODE_6
47
48 @interface DVTPlatform : NSObject
49 + (BOOL)loadAllPlatformsReturningError:(id*)arg1;
50 @end
51 @class DTiPhoneSimulatorApplicationSpecifier;
52 @class DTiPhoneSimulatorSession;
53 @class DTiPhoneSimulatorSessionConfig;
54 @class DTiPhoneSimulatorSystemRoot;
55 @class DVTConfinementServiceConnection;
56 @class DVTDispatchLock;
57 @class DVTiPhoneSimulatorMessenger;
58 @class DVTNotificationToken;
59 @class DVTTask;
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;
70 @end
71 #import "DVTiPhoneSimulatorRemoteClient.h"
72
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"
76
77 namespace {
78
79 // Name of environment variables that control the user's home directory in the
80 // simulator.
81 const char* const kUserHomeEnvVariable = "CFFIXED_USER_HOME";
82 const char* const kHomeEnvVariable = "HOME";
83
84 // Device family codes for iPhone and iPad.
85 const int kIPhoneFamily = 1;
86 const int kIPadFamily = 2;
87
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;
98
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
101 // polling interval.
102 const NSTimeInterval kOutputPollIntervalSeconds = 0.1;
103
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";
111
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.";
115
116 const char* gToolName = "iossim";
117
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;
126
127 void LogError(NSString* format, ...) {
128   va_list list;
129   va_start(list, format);
130
131   NSString* message =
132       [[[NSString alloc] initWithFormat:format arguments:list] autorelease];
133
134   fprintf(stderr, "%s: ERROR: %s\n", gToolName, [message UTF8String]);
135   fflush(stderr);
136
137   va_end(list);
138 }
139
140 void LogWarning(NSString* format, ...) {
141   va_list list;
142   va_start(list, format);
143
144   NSString* message =
145       [[[NSString alloc] initWithFormat:format arguments:list] autorelease];
146
147   fprintf(stderr, "%s: WARNING: %s\n", gToolName, [message UTF8String]);
148   fflush(stderr);
149
150   va_end(list);
151 }
152
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);
156   if (!theClass) {
157     LogError(@"Failed to find class %@ at runtime.", nameOfClass);
158     exit(kExitInitializationFailure);
159   }
160   return theClass;
161 }
162
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];
172
173   [task launch];
174   NSData* outputData = [outputFile readDataToEndOfFile];
175   [task waitUntilExit];
176   if ([task isRunning]) {
177     LogError(@"Task '%@ %@' is still running.",
178         toolPath,
179         [args componentsJoinedByString:@" "]);
180     return nil;
181   } else if ([task terminationStatus]) {
182     LogError(@"Task '%@ %@' exited with return code %d.",
183         toolPath,
184         [args componentsJoinedByString:@" "],
185         [task terminationStatus]);
186     return nil;
187   }
188   return [[[NSString alloc] initWithData:outputData
189                                 encoding:NSUTF8StringEncoding] autorelease];
190 }
191
192 // Finds the Xcode version via xcodebuild -version. Output from xcodebuild is
193 // expected to look like:
194 //   Xcode <version>
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",
199                                        @[ @"-version" ]);
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];
203   NSString* version;
204   valid =
205       [scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet]
206                               intoString:&version];
207   if (!valid) {
208     LogError(@"Unable to find Xcode version. 'xcodebuild -version' "
209              @"returned \n%@", output);
210     return nil;
211   }
212   return version;
213 }
214
215 // Returns true if iossim is running with Xcode 6 or later installed on the
216 // host.
217 BOOL IsRunningWithXcode6OrLater() {
218   static NSString* xcodeVersion = FindXcodeVersion();
219   if (!xcodeVersion) {
220     return false;
221   }
222   NSArray* components = [xcodeVersion componentsSeparatedByString:@"."];
223   if ([components count] < 1) {
224     return false;
225   }
226   NSInteger majorVersion = [[components objectAtIndex:0] integerValue];
227   return majorVersion >= 6;
228 }
229
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");
236     id deviceSet =
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]);
243     }
244 #endif  // IOSSIM_USE_XCODE_6
245   } else {
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]);
250     }
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");
257     printf("  'iPad'\n");
258     printf("  'iPad Retina'\n");
259     printf("  'iPad Retina (64-bit)'\n");
260   }
261 }
262 }  // namespace
263
264 // A delegate that is called when the simulated app is started or ended in the
265 // simulator.
266 @interface SimulatorDelegate : NSObject <DTiPhoneSimulatorSessionDelegate> {
267  @private
268   NSString* stdioPath_;
269   NSString* developerDir_;
270   NSString* simulatorHome_;
271   NSThread* outputThread_;
272   NSBundle* simulatorBundle_;
273   BOOL appRunning_;
274 }
275 @end
276
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
287
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 {
292   self = [super init];
293   if (self) {
294     stdioPath_ = [stdioPath copy];
295     developerDir_ = [developerDir copy];
296     simulatorHome_ = [simulatorHome copy];
297   }
298
299   return self;
300 }
301
302 - (void)dealloc {
303   [stdioPath_ release];
304   [developerDir_ release];
305   [simulatorBundle_ release];
306   [super dealloc];
307 }
308
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];
317
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];
332     }
333 #endif  // IOSSIM_USE_XCODE_6
334   }
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];
341     [innerPool drain];
342   }
343
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]];
347
348   [pool drain];
349 }
350
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];
358   }
359   NSString *localizedStr =
360       [simulatorBundle_ localizedStringForKey:stringKey
361                                         value:nil
362                                         table:nil];
363   if ([localizedStr length])
364     return localizedStr;
365   // Failed to get a value, follow Cocoa conventions and use the key as the
366   // string.
367   return stringKey;
368 }
369
370 - (void)session:(DTiPhoneSimulatorSession*)session
371        didStart:(BOOL)started
372       withError:(NSError*)error {
373   if (!started) {
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_]) {
382       appRunning_ = NO;
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];
389
390       // session:didEndWithError should not return (because it exits) so
391       // the execution path should never get here.
392       exit(kExitFailure);
393     }
394
395     LogError(@"Simulator failed to start: \"%@\" (%@:%ld)",
396              [error localizedDescription],
397              [error domain], static_cast<long int>([error code]));
398     PrintSupportedDevices();
399     exit(kExitAppFailedToStart);
400   }
401
402   // Start a thread to write contents of outputPath to stdout.
403   appRunning_ = YES;
404   outputThread_ =
405       [[NSThread alloc] initWithTarget:self
406                               selector:@selector(tailOutputForSession:)
407                                 object:session];
408   [outputThread_ start];
409 }
410
411 - (void)session:(DTiPhoneSimulatorSession*)session
412     didEndWithError:(NSError*)error {
413   appRunning_ = NO;
414   // Wait for the output thread to finish copying data to stdout.
415   if (outputThread_) {
416     while (![outputThread_ isFinished]) {
417       [NSThread sleepForTimeInterval:kOutputPollIntervalSeconds];
418     }
419     [outputThread_ release];
420     outputThread_ = nil;
421   }
422
423   if (error) {
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
427     // simulator run.
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]));
435     } else {
436       LogError(@"Simulator ended with error: \"%@\" (%@:%ld)",
437                localizedDescription, [error domain],
438                static_cast<long int>([error code]));
439       exit(kExitFailure);
440     }
441   }
442
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);
460     char session_id[20];
461     if (snprintf(session_id, 20, "%d", [session simulatedApplicationPID]) < 0) {
462       LogError(@"Failed to get [session simulatedApplicationPID]");
463       exit(kExitFailure);
464     }
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);
467
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);
471     aslmsg entry;
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"))
477         continue;
478       badEntryFound = YES;
479     }
480   } else {
481     // Otherwise, the iOS Simulator's system logging is sandboxed, so parse the
482     // sandboxed system.log file for known errors.
483     NSString* path;
484     if (IsRunningWithXcode6OrLater()) {
485 #if defined(IOSSIM_USE_XCODE_6)
486       NSString* dataPath = session.sessionConfig.device.dataPath;
487       path =
488           [dataPath stringByAppendingPathComponent:@"Library/Logs/system.log"];
489 #endif  // IOSSIM_USE_XCODE_6
490     } else {
491       NSString* relativePathToSystemLog =
492           [NSString stringWithFormat:
493               @"Library/Logs/iOS Simulator/%@/system.log", versionString];
494       path = [simulatorHome_
495           stringByAppendingPathComponent:relativePathToSystemLog];
496     }
497     NSFileManager* fileManager = [NSFileManager defaultManager];
498     if ([fileManager fileExistsAtPath:path]) {
499       NSString* content =
500           [NSString stringWithContentsOfFile:path
501                                     encoding:NSUTF8StringEncoding
502                                        error:NULL];
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);
512           badEntryFound = YES;
513           break;
514         }
515       }
516       // Remove the log file so subsequent invocations of iossim won't be
517       // looking at stale logs.
518       remove([path fileSystemRepresentation]);
519     } else {
520         LogWarning(@"Unable to find system log at '%@'.", path);
521     }
522   }
523
524   // If the query returned any nasty-looking results, iossim should exit with
525   // non-zero status.
526   if (badEntryFound) {
527     LogError(@"Simulated app crashed or exited with non-zero status");
528     exit(kExitAppCrashed);
529   }
530   exit(kExitSuccess);
531 }
532 @end
533
534 namespace {
535
536 // Finds the developer dir via xcode-select or the DEVELOPER_DIR environment
537 // variable.
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)
543     return developerDir;
544
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)
551     output = nil;
552   return output;
553 }
554
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])
564     return nil;
565
566   NSString* devToolsFoundationPath = [developerDir
567       stringByAppendingPathComponent:kDevToolsFoundationRelativePath];
568   NSBundle* devToolsFoundationBundle =
569       [NSBundle bundleWithPath:devToolsFoundationPath];
570   if (![devToolsFoundationBundle load])
571     return nil;
572
573   // Prime DVTPlatform.
574   NSError* error;
575   Class DVTPlatformClass = FindClassByName(@"DVTPlatform");
576   if (![DVTPlatformClass loadAllPlatformsReturningError:&error]) {
577     LogError(@"Unable to loadAllPlatformsReturningError. Error: %@",
578          [error localizedDescription]);
579     return nil;
580   }
581
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])
594       return nil;
595   } else {
596     simulatorFrameworkRelativePath =
597       @"Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/"
598       @"DVTiPhoneSimulatorRemoteClient.framework";
599   }
600   NSString* simBundlePath = [developerDir
601       stringByAppendingPathComponent:simulatorFrameworkRelativePath];
602   NSBundle* simBundle = [NSBundle bundleWithPath:simBundlePath];
603   if (![simBundle load])
604     return nil;
605   return simBundle;
606 }
607
608 // Converts the given app path to an application spec, which requires an
609 // absolute path.
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];
616   }
617   appPath = [appPath stringByStandardizingPath];
618   NSFileManager* fileManager = [NSFileManager defaultManager];
619   if (![fileManager fileExistsAtPath:appPath]) {
620     LogError(@"File not found: %@", appPath);
621     exit(kExitInvalidArguments);
622   }
623   return [applicationSpecifierClass specifierWithApplicationPath:appPath];
624 }
625
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
628 // valid.
629 DTiPhoneSimulatorSystemRoot* BuildSystemRoot(NSString* sdkVersion) {
630   Class systemRootClass = FindClassByName(@"DTiPhoneSimulatorSystemRoot");
631   DTiPhoneSimulatorSystemRoot* systemRoot = [systemRootClass defaultRoot];
632   if (sdkVersion)
633     systemRoot = [systemRootClass rootWithSDKVersion:sdkVersion];
634
635   return systemRoot;
636 }
637
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,
644     NSArray* appArgs,
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;
660
661   if (IsRunningWithXcode6OrLater()) {
662 #if defined(IOSSIM_USE_XCODE_6)
663     Class simDeviceTypeClass = FindClassByName(@"SimDeviceType");
664     id simDeviceType =
665         [simDeviceTypeClass supportedDeviceTypesByName][deviceName];
666     Class simRuntimeClass = FindClassByName(@"SimRuntime");
667     NSString* identifier = systemRoot.runtime.identifier;
668     id simRuntime = [simRuntimeClass supportedRuntimesByIdentifier][identifier];
669
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");
675     id deviceSet =
676         [simDeviceSetClass setForSetPath:[simDeviceSetClass defaultSetPath]];
677     id simDevice = nil;
678     for (id device in [deviceSet availableDevices]) {
679       if ([device runtime] == simRuntime &&
680           [device deviceType] == simDeviceType) {
681         simDevice = device;
682         break;
683       }
684     }
685     if (!simDevice) {
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
691                                           runtime:simRuntime
692                                              name:name
693                                             error:&error];
694       if (error) {
695         LogError(@"Failed to create device: %@", error);
696         exit(kExitInitializationFailure);
697       }
698     }
699     sessionConfig.device = simDevice;
700 #endif  // IOSSIM_USE_XCODE_6
701   }
702   return sessionConfig;
703 }
704
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;
711   return session;
712 }
713
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'.
720 //
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)
728     return nil;
729
730   return [NSString stringWithUTF8String:fullPath];
731 }
732
733 // Creates the necessary directory structure under the given user home directory
734 // path.
735 // Returns YES if successful, NO if unable to create the directories.
736 BOOL CreateHomeDirSubDirs(NSString* userHomePath) {
737   NSFileManager* fileManager = [NSFileManager defaultManager];
738
739   // Create user home and subdirectories.
740   NSArray* subDirsToCreate = [NSArray arrayWithObjects:
741                               @"Documents",
742                               @"Library/Caches",
743                               @"Library/Preferences",
744                               nil];
745   for (NSString* subDir in subDirsToCreate) {
746     NSString* path = [userHomePath stringByAppendingPathComponent:subDir];
747     NSError* error;
748     if (![fileManager createDirectoryAtPath:path
749                 withIntermediateDirectories:YES
750                                  attributes:nil
751                                       error:&error]) {
752       LogError(@"Unable to create directory: %@. Error: %@",
753                path, [error localizedDescription]);
754       return NO;
755     }
756   }
757
758   return YES;
759 }
760
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
764 // directory.
765 BOOL InitializeSimulatorUserHome(NSString* userHomePath) {
766   if (!CreateHomeDirSubDirs(userHomePath))
767     return NO;
768
769   // Update the environment to use the specified directory as the user home
770   // directory.
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.");
776     return NO;
777   }
778
779   return YES;
780 }
781
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
788                                         options:options];
789   return range.location != NSNotFound;
790 }
791
792 // Prints the usage information to stderr.
793 void PrintUsage() {
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"
798       "\n"
799       "Options:\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)."
809       " Defaults to %d.\n"
810       "  -l  List supported devices and iOS versions.\n",
811       static_cast<int>(kDefaultSessionStartTimeoutSeconds));
812 }
813 }  // namespace
814
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
821   }
822 }
823
824 int main(int argc, char* const argv[]) {
825   NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
826
827   EnsureSupportForCurrentXcodeVersion();
828
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;
837   }
838   if (worker != NULL)
839     free(worker);
840
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;
849
850   NSString* developerDir = FindDeveloperDir();
851   if (!developerDir) {
852     LogError(@"Unable to find developer directory.");
853     exit(kExitInitializationFailure);
854   }
855
856   NSBundle* simulatorFramework = LoadSimulatorFramework(developerDir);
857   if (!simulatorFramework) {
858     LogError(@"Failed to load the Simulator Framework.");
859     exit(kExitInitializationFailure);
860   }
861
862   // Parse the optional arguments
863   int c;
864   while ((c = getopt(argc, argv, "hs:d:u:e:t:l")) != -1) {
865     switch (c) {
866       case 's':
867         sdkVersion = [NSString stringWithUTF8String:optarg];
868         break;
869       case 'd':
870         deviceName = [NSString stringWithUTF8String:optarg];
871         break;
872       case 'u':
873         simHomePath = [[NSFileManager defaultManager]
874             stringWithFileSystemRepresentation:optarg length:strlen(optarg)];
875         break;
876       case 'e': {
877         NSString* envLine = [NSString stringWithUTF8String:optarg];
878         NSRange range = [envLine rangeOfString:@"="];
879         if (range.location == NSNotFound) {
880           LogError(@"Invalid key=value argument for -e.");
881           PrintUsage();
882           exit(kExitInvalidArguments);
883         }
884         NSString* key = [envLine substringToIndex:range.location];
885         NSString* value = [envLine substringFromIndex:(range.location + 1)];
886         [appEnv setObject:value forKey:key];
887       }
888         break;
889       case 't': {
890         int timeout = atoi(optarg);
891         if (timeout > 0) {
892           sessionStartTimeout = static_cast<NSTimeInterval>(timeout);
893         } else {
894           LogError(@"Invalid startup timeout (%s).", optarg);
895           PrintUsage();
896           exit(kExitInvalidArguments);
897         }
898       }
899         break;
900       case 'l':
901         PrintSupportedDevices();
902         exit(kExitSuccess);
903         break;
904       case 'h':
905         PrintUsage();
906         exit(kExitSuccess);
907       default:
908         PrintUsage();
909         exit(kExitInvalidArguments);
910     }
911   }
912
913   // There should be at least one arg left, specifying the app path. Any
914   // additional args are passed as arguments to the app.
915   if (optind < argc) {
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]]];
922     }
923   } else {
924     LogError(@"Unable to parse command line arguments.");
925     PrintUsage();
926     exit(kExitInvalidArguments);
927   }
928
929   // Make sure the app path provided is legit.
930   DTiPhoneSimulatorApplicationSpecifier* appSpec = BuildAppSpec(appPath);
931   if (!appSpec) {
932     LogError(@"Invalid app path: %@", appPath);
933     exit(kExitInitializationFailure);
934   }
935
936   // Make sure the SDK path provided is legit (or nil).
937   DTiPhoneSimulatorSystemRoot* systemRoot = BuildSystemRoot(sdkVersion);
938   if (!systemRoot) {
939     LogError(@"Invalid SDK version: %@", sdkVersion);
940     PrintSupportedDevices();
941     exit(kExitInitializationFailure);
942   }
943
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"];
948
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);
958     }
959 #endif  // IOSSIM_USE_XCODE_6
960   } else {
961     if (!deviceName || CaseInsensitivePrefixSearch(deviceName, @"iPhone")) {
962       deviceFamily = [NSNumber numberWithInt:kIPhoneFamily];
963     } else if (CaseInsensitivePrefixSearch(deviceName, @"iPad")) {
964       deviceFamily = [NSNumber numberWithInt:kIPadFamily];
965     }
966     else {
967       LogError(@"Invalid device name: %@. Must begin with 'iPhone' or 'iPad'",
968                deviceName);
969       exit(kExitInvalidArguments);
970     }
971   }
972
973   // Set up the user home directory for the simulator only if a non-default
974   // value was specified.
975   if (simHomePath) {
976     if (!InitializeSimulatorUserHome(simHomePath)) {
977       LogError(@"Unable to initialize home directory for simulator: %@",
978                simHomePath);
979       exit(kExitInitializationFailure);
980     }
981   } else {
982     simHomePath = NSHomeDirectory();
983   }
984
985   // Create the config and simulator session.
986   DTiPhoneSimulatorSessionConfig* config = BuildSessionConfig(appSpec,
987                                                               systemRoot,
988                                                               stdioPath,
989                                                               stdioPath,
990                                                               appArgs,
991                                                               appEnv,
992                                                               deviceFamily,
993                                                               deviceName);
994   SimulatorDelegate* delegate =
995       [[[SimulatorDelegate alloc] initWithStdioPath:stdioPath
996                                        developerDir:developerDir
997                                       simulatorHome:simHomePath] autorelease];
998   DTiPhoneSimulatorSession* session = BuildSession(delegate);
999
1000   // Start the simulator session.
1001   NSError* error;
1002   BOOL started = [session requestStartWithConfig:config
1003                                          timeout:sessionStartTimeout
1004                                            error:&error];
1005
1006   // Spin the runtime indefinitely. When the delegate gets the message that the
1007   // app has quit it will exit this program.
1008   if (started) {
1009     [[NSRunLoop mainRunLoop] run];
1010   } else {
1011     LogError(@"Simulator failed request to start:  \"%@\" (%@:%ld)",
1012              [error localizedDescription],
1013              [error domain], static_cast<long int>([error code]));
1014   }
1015
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.
1019   [pool drain];
1020   return kExitFailure;
1021 }