diff --git a/NTSynchronousTask.m b/NTSynchronousTask.m index 8375a2ec..22b238e3 100644 --- a/NTSynchronousTask.m +++ b/NTSynchronousTask.m @@ -132,59 +132,54 @@ + (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input { - // we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSData* result = nil; - - @try - { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; - - [task run:toolPath directory:currentDirectory withArgs:args input:input]; - - if ([task result] == 0) { - result = [[task output] retain]; + // we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased + @autoreleasepool { + @try { + NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; + + [task run:toolPath directory:currentDirectory withArgs:args input:input]; + + if ([task result] == 0) { + result = [[task output] retain]; + } + + [task release]; } - - [task release]; - } - @catch (NSException *localException) { } - - [pool drain]; + @catch (NSException *localException) { } + + } // retained above - [result autorelease]; - - return result; + return [result autorelease]; } +(int) task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output: (NSData**)outData { + int taskResult = 0; // we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int taskResult = 0; - if (outData) { - *outData = nil; - } - - @try { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; - - [task run:toolPath directory:currentDirectory withArgs:args input:input]; - - taskResult = [task result]; + @autoreleasepool { if (outData) { - *outData = [[task output] retain]; + *outData = nil; } - - [task release]; - } @catch (NSException *localException) { - taskResult = errCppGeneral; + + @try { + NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; + + [task run:toolPath directory:currentDirectory withArgs:args input:input]; + + taskResult = [task result]; + if (outData) { + *outData = [[task output] retain]; + } + + [task release]; + } @catch (NSException *localException) { + taskResult = errCppGeneral; + } + } - - [pool drain]; - // retained above if (outData) { [*outData autorelease]; diff --git a/SUBinaryDeltaTool.m b/SUBinaryDeltaTool.m index 6e0568df..fd44291b 100644 --- a/SUBinaryDeltaTool.m +++ b/SUBinaryDeltaTool.m @@ -31,41 +31,46 @@ extern int bsdiff(int argc, const char **argv); NSString *_toPath; NSString *_resultPath; } +@property (copy) NSString *relativePath; +@property (retain) NSString *resultPath; +@property (retain) NSString *_fromPath; +@property (retain) NSString *_toPath; - (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree; - -- (NSString *)relativePath; -- (NSString *)resultPath; @end @implementation CreateBinaryDeltaOperation +@synthesize relativePath = _relativePath; +@synthesize resultPath = _resultPath; +@synthesize _fromPath = _fromPath; +@synthesize _toPath = _toPath; - (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree { if ((self = [super init])) { - _relativePath = [relativePath copy]; - _fromPath = [[oldTree stringByAppendingPathComponent:relativePath] retain]; - _toPath = [[newTree stringByAppendingPathComponent:relativePath] retain]; + self.relativePath = relativePath; + self._fromPath = [oldTree stringByAppendingPathComponent:relativePath]; + self._toPath = [newTree stringByAppendingPathComponent:relativePath]; } return self; } -- (NSString *)relativePath -{ - return [[_relativePath retain] autorelease]; -} - -- (NSString *)resultPath -{ - return [[_resultPath retain] autorelease]; -} - - (void)main { NSString *temporaryFile = temporaryFilename(@"BinaryDelta"); const char *argv[] = {"/usr/bin/bsdiff", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]}; int result = bsdiff(4, argv); if (!result) - _resultPath = [temporaryFile retain]; + self.resultPath = temporaryFile; +} + +- (void)dealloc +{ + self.relativePath = nil; + self.resultPath = nil; + self._fromPath = nil; + self._toPath = nil; + + [super dealloc]; } @end @@ -127,154 +132,155 @@ static BOOL shouldDeleteThenExtract(NSString *key, NSDictionary* originalInfo, N int main(int argc, char **argv) { - if (argc != 5) { -usage: - fprintf(stderr, "Usage: BinaryDelta [create | apply] before-tree after-tree patch-file\n"); - exit(1); - } - - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSString *command = [NSString stringWithUTF8String:argv[1]]; - NSString *oldPath = stringWithFileSystemRepresentation(argv[2]); - NSString *newPath = stringWithFileSystemRepresentation(argv[3]); - NSString *patchFile = stringWithFileSystemRepresentation(argv[4]); - - if ([command isEqualToString:@"apply"]) { - int result = applyBinaryDelta(oldPath, newPath, patchFile); - [pool drain]; - return result; - } - if (![command isEqualToString:@"create"]) { - [pool drain]; - goto usage; - } - - NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary]; - - const char *sourcePaths[] = {[oldPath fileSystemRepresentation], 0}; - FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); - if (!fts) { - [pool drain]; - perror("fts_open"); - return 1; - } - - fprintf(stderr, "Processing %s...", [oldPath UTF8String]); - FTSENT *ent = 0; - while ((ent = fts_read(fts))) { - if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { - continue; - } - - NSString *key = pathRelativeToDirectory(oldPath, stringWithFileSystemRepresentation(ent->fts_path)); - if (![key length]) { - continue; - } - - NSDictionary *info = infoForFile(ent); - [originalTreeState setObject:info forKey:key]; - } - fts_close(fts); - - NSString *beforeHash = hashOfTree(oldPath); - - NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary]; - for (NSString *key in originalTreeState) - { - [newTreeState setObject:[NSNull null] forKey:key]; - } - - fprintf(stderr, "\nProcessing %s... ", [newPath UTF8String]); - sourcePaths[0] = [newPath fileSystemRepresentation]; - fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); - if (!fts) { - [pool drain]; - perror("fts_open"); - return 1; - } - - - while ((ent = fts_read(fts))) { - if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { - continue; - } - - NSString *key = pathRelativeToDirectory(newPath, stringWithFileSystemRepresentation(ent->fts_path)); - if (![key length]) { - continue; - } - - NSDictionary *info = infoForFile(ent); - NSDictionary *oldInfo = [originalTreeState objectForKey:key]; - - if ([info isEqual:oldInfo]) - [newTreeState removeObjectForKey:key]; - else - [newTreeState setObject:info forKey:key]; - } - fts_close(fts); - - NSString *afterHash = hashOfTree(newPath); - - fprintf(stderr, "\nGenerating delta... "); - - NSString *temporaryFile = temporaryPatchFile(patchFile); - xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE); - xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2"); - xar_subdoc_t attributes = xar_subdoc_new(x, "binary-delta-attributes"); - xar_subdoc_prop_set(attributes, "before-sha1", [beforeHash UTF8String]); - xar_subdoc_prop_set(attributes, "after-sha1", [afterHash UTF8String]); - - NSOperationQueue *deltaQueue = [[NSOperationQueue alloc] init]; - NSMutableArray *deltaOperations = [NSMutableArray array]; - - NSArray *keys = [[newTreeState allKeys] sortedArrayUsingSelector:@selector(compare:)]; - for (NSString* key in keys) { - id value = [newTreeState valueForKey:key]; - - if ([value isEqual:[NSNull null]]) { - xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1); - assert(newFile); - xar_prop_set(newFile, "delete", "true"); - continue; + @autoreleasepool { + if (argc != 5) { + usage: + fprintf(stderr, "Usage: BinaryDelta [create | apply] before-tree after-tree patch-file\n"); + exit(1); } - - NSDictionary *originalInfo = [originalTreeState objectForKey:key]; - NSDictionary *newInfo = [newTreeState objectForKey:key]; - if (shouldSkipDeltaCompression(key, originalInfo, newInfo)) { - NSString *path = [newPath stringByAppendingPathComponent:key]; - xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]); - assert(newFile); - if (shouldDeleteThenExtract(key, originalInfo, newInfo)) { - xar_prop_set(newFile, "delete-then-extract", "true"); - } - } else { - CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key oldTree:oldPath newTree:newPath]; - [deltaQueue addOperation:operation]; - [deltaOperations addObject:operation]; - [operation release]; + + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSString *command = [NSString stringWithUTF8String:argv[1]]; + NSString *oldPath = stringWithFileSystemRepresentation(argv[2]); + NSString *newPath = stringWithFileSystemRepresentation(argv[3]); + NSString *patchFile = stringWithFileSystemRepresentation(argv[4]); + + if ([command isEqualToString:@"apply"]) { + int result = applyBinaryDelta(oldPath, newPath, patchFile); + [pool drain]; + return result; } + if (![command isEqualToString:@"create"]) { + [pool drain]; + goto usage; + } + + NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary]; + + const char *sourcePaths[] = {[oldPath fileSystemRepresentation], 0}; + FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); + if (!fts) { + [pool drain]; + perror("fts_open"); + return 1; + } + + fprintf(stderr, "Processing %s...", [oldPath UTF8String]); + FTSENT *ent = 0; + while ((ent = fts_read(fts))) { + if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { + continue; + } + + NSString *key = pathRelativeToDirectory(oldPath, stringWithFileSystemRepresentation(ent->fts_path)); + if (![key length]) { + continue; + } + + NSDictionary *info = infoForFile(ent); + [originalTreeState setObject:info forKey:key]; + } + fts_close(fts); + + NSString *beforeHash = hashOfTree(oldPath); + + NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary]; + for (NSString *key in originalTreeState) + { + [newTreeState setObject:[NSNull null] forKey:key]; + } + + fprintf(stderr, "\nProcessing %s... ", [newPath UTF8String]); + sourcePaths[0] = [newPath fileSystemRepresentation]; + fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); + if (!fts) { + [pool drain]; + perror("fts_open"); + return 1; + } + + + while ((ent = fts_read(fts))) { + if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { + continue; + } + + NSString *key = pathRelativeToDirectory(newPath, stringWithFileSystemRepresentation(ent->fts_path)); + if (![key length]) { + continue; + } + + NSDictionary *info = infoForFile(ent); + NSDictionary *oldInfo = [originalTreeState objectForKey:key]; + + if ([info isEqual:oldInfo]) + [newTreeState removeObjectForKey:key]; + else + [newTreeState setObject:info forKey:key]; + } + fts_close(fts); + + NSString *afterHash = hashOfTree(newPath); + + fprintf(stderr, "\nGenerating delta... "); + + NSString *temporaryFile = temporaryPatchFile(patchFile); + xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE); + xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2"); + xar_subdoc_t attributes = xar_subdoc_new(x, "binary-delta-attributes"); + xar_subdoc_prop_set(attributes, "before-sha1", [beforeHash UTF8String]); + xar_subdoc_prop_set(attributes, "after-sha1", [afterHash UTF8String]); + + NSOperationQueue *deltaQueue = [[NSOperationQueue alloc] init]; + NSMutableArray *deltaOperations = [NSMutableArray array]; + + NSArray *keys = [[newTreeState allKeys] sortedArrayUsingSelector:@selector(compare:)]; + for (NSString* key in keys) { + id value = [newTreeState valueForKey:key]; + + if ([value isEqual:[NSNull null]]) { + xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1); + assert(newFile); + xar_prop_set(newFile, "delete", "true"); + continue; + } + + NSDictionary *originalInfo = [originalTreeState objectForKey:key]; + NSDictionary *newInfo = [newTreeState objectForKey:key]; + if (shouldSkipDeltaCompression(key, originalInfo, newInfo)) { + NSString *path = [newPath stringByAppendingPathComponent:key]; + xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]); + assert(newFile); + if (shouldDeleteThenExtract(key, originalInfo, newInfo)) { + xar_prop_set(newFile, "delete-then-extract", "true"); + } + } else { + CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key oldTree:oldPath newTree:newPath]; + [deltaQueue addOperation:operation]; + [deltaOperations addObject:operation]; + [operation release]; + } + } + + [deltaQueue waitUntilAllOperationsAreFinished]; + [deltaQueue release]; + + for (CreateBinaryDeltaOperation *operation in deltaOperations) { + NSString *resultPath = [operation resultPath]; + xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]); + assert(newFile); + xar_prop_set(newFile, "binary-delta", "true"); + unlink([resultPath fileSystemRepresentation]); + } + + xar_close(x); + + unlink([patchFile fileSystemRepresentation]); + link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]); + unlink([temporaryFile fileSystemRepresentation]); + fprintf(stderr, "Done!\n"); + + return 0; } - - [deltaQueue waitUntilAllOperationsAreFinished]; - [deltaQueue release]; - - for (CreateBinaryDeltaOperation *operation in deltaOperations) { - NSString *resultPath = [operation resultPath]; - xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]); - assert(newFile); - xar_prop_set(newFile, "binary-delta", "true"); - unlink([resultPath fileSystemRepresentation]); - } - - xar_close(x); - - unlink([patchFile fileSystemRepresentation]); - link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]); - unlink([temporaryFile fileSystemRepresentation]); - fprintf(stderr, "Done!\n"); - - [pool drain]; - return 0; } diff --git a/SUBinaryDeltaUnarchiver.m b/SUBinaryDeltaUnarchiver.m index e7b612ac..2fd73270 100644 --- a/SUBinaryDeltaUnarchiver.m +++ b/SUBinaryDeltaUnarchiver.m @@ -22,22 +22,29 @@ - (void)applyBinaryDelta { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSString *sourcePath = [[updateHost bundle] bundlePath]; - NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; - - int result = applyBinaryDelta(sourcePath, targetPath, archivePath); - if (!result) - [self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO]; - else - [self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO]; - - [pool drain]; + @autoreleasepool { + NSString *sourcePath = [[updateHost bundle] bundlePath]; + NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; + + int result = applyBinaryDelta(sourcePath, targetPath, archivePath); + if (!result) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self notifyDelegateOfSuccess]; + }); + } + else { + dispatch_async(dispatch_get_main_queue(), ^{ + [self notifyDelegateOfFailure]; + }); + } + } } - (void)start { - [NSThread detachNewThreadSelector:@selector(applyBinaryDelta) toTarget:self withObject:nil]; + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self applyBinaryDelta]; + }); } + (void)load diff --git a/SUDiskImageUnarchiver.m b/SUDiskImageUnarchiver.m index c2f6bd9f..38b8f5ad 100644 --- a/SUDiskImageUnarchiver.m +++ b/SUDiskImageUnarchiver.m @@ -22,119 +22,117 @@ // Called on a non-main thread. - (void)extractDMG { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - [self extractDMGWithPassword:nil]; - - [pool release]; + @autoreleasepool { + [self extractDMGWithPassword:nil]; + } } // Called on a non-main thread. - (void)extractDMGWithPassword:(NSString *)password { - - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - BOOL mountedSuccessfully = NO; - - SULog(@"Extracting %@ as a DMG", archivePath); - - // get a unique mount point path - NSString *mountPoint = nil; - FSRef tmpRef; - do - { - // Using NSUUID would make creating UUIDs be done in Cocoa, - // and thus managed under ARC. Sadly, the class is in 10.8 and later. - CFUUIDRef uuid = CFUUIDCreate(NULL); - if (uuid) + @autoreleasepool { + BOOL mountedSuccessfully = NO; + + SULog(@"Extracting %@ as a DMG", archivePath); + + // get a unique mount point path + NSString *mountPoint = nil; + FSRef tmpRef; + do { - NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); - if (uuidString) + // Using NSUUID would make creating UUIDs be done in Cocoa, + // and thus managed under ARC. Sadly, the class is in 10.8 and later. + CFUUIDRef uuid = CFUUIDCreate(NULL); + if (uuid) { - mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString]; + NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); + if (uuidString) + { + mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString]; + } + CFRelease(uuid); } - CFRelease(uuid); } - } - while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); - - NSData *promptData = nil; - promptData = [NSData dataWithBytes:"yes\n" length:4]; - - NSArray* arguments = @[@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"]; - - NSData *output = nil; - NSInteger taskResult = -1; - @try - { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; + while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); - [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; + NSData *promptData = nil; + promptData = [NSData dataWithBytes:"yes\n" length:4]; - taskResult = [task result]; - output = [[[task output] copy] autorelease]; - [task release]; - } - @catch (NSException *localException) - { - goto reportError; - } - - if (taskResult != 0) - { - NSString* resultStr = output ? [[[NSString alloc] initWithData: output encoding: NSUTF8StringEncoding] autorelease] : nil; - SULog( @"hdiutil failed with code: %d data: <<%@>>", taskResult, resultStr ); - goto reportError; - } - mountedSuccessfully = YES; - - // Now that we've mounted it, we need to copy out its contents. - NSFileManager *manager = [[[NSFileManager alloc] init] autorelease]; - NSError *error = nil; - NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; - if (error) - { - SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); - goto reportError; - } - - for (NSString *item in contents) - { - NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; - NSString *toPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; + NSArray* arguments = @[@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"]; - // We skip any files in the DMG which are not readable. - if (![manager isReadableFileAtPath:fromPath]) { - continue; - } - - SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); - - if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) + NSData *output = nil; + NSInteger taskResult = -1; + @try + { + NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; + + [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; + + taskResult = [task result]; + output = [[[task output] copy] autorelease]; + [task release]; + } + @catch (NSException *localException) { - SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); goto reportError; } + + if (taskResult != 0) + { + NSString* resultStr = output ? [[[NSString alloc] initWithData: output encoding: NSUTF8StringEncoding] autorelease] : nil; + SULog( @"hdiutil failed with code: %d data: <<%@>>", taskResult, resultStr ); + goto reportError; + } + mountedSuccessfully = YES; + + // Now that we've mounted it, we need to copy out its contents. + NSFileManager *manager = [[[NSFileManager alloc] init] autorelease]; + NSError *error = nil; + NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; + if (error) + { + SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); + goto reportError; + } + + for (NSString *item in contents) + { + NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; + NSString *toPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; + + // We skip any files in the DMG which are not readable. + if (![manager isReadableFileAtPath:fromPath]) { + continue; + } + + SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); + + if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) + { + SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); + goto reportError; + } + } + + [self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO]; + goto finally; + + reportError: + [self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO]; + + finally: + if (mountedSuccessfully) + [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; + else + SULog(@"Can't mount DMG %@",archivePath); } - - [self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO]; - goto finally; - -reportError: - [self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO]; - -finally: - if (mountedSuccessfully) - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; - else - SULog(@"Can't mount DMG %@",archivePath); - [pool drain]; } - (void)start { - [NSThread detachNewThreadSelector:@selector(extractDMG) toTarget:self withObject:nil]; + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self extractDMG]; + }); } + (void)load diff --git a/SUPackageInstaller.m b/SUPackageInstaller.m index 8d9f163c..1994aba2 100644 --- a/SUPackageInstaller.m +++ b/SUPackageInstaller.m @@ -25,15 +25,13 @@ NSString *SUPackageInstallerInstallationPathKey = @"SUPackageInstallerInstallati + (void)performInstallationWithInfo:(NSDictionary *)info { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSTask *installer = [NSTask launchedTaskWithLaunchPath:info[SUPackageInstallerCommandKey] arguments:info[SUPackageInstallerArgumentsKey]]; - [installer waitUntilExit]; - - // Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine. - [self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:info waitUntilDone:NO]; - - [pool drain]; + @autoreleasepool { + NSTask *installer = [NSTask launchedTaskWithLaunchPath:info[SUPackageInstallerCommandKey] arguments:info[SUPackageInstallerArgumentsKey]]; + [installer waitUntilExit]; + + // Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine. + [self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:info waitUntilDone:NO]; + } } + (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id )comparator @@ -58,8 +56,11 @@ NSString *SUPackageInstallerInstallationPathKey = @"SUPackageInstallerInstallati NSDictionary *info = @{SUPackageInstallerCommandKey: command, SUPackageInstallerArgumentsKey: args, SUPackageInstallerHostKey: host, SUPackageInstallerDelegateKey: delegate, SUPackageInstallerInstallationPathKey: installationPath}; if (synchronously) [self performInstallationWithInfo:info]; - else - [NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:self withObject:info]; + else { + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self performInstallationWithInfo:info]; + }); + } } } diff --git a/SUPipedUnarchiver.m b/SUPipedUnarchiver.m index 51530ece..63f50032 100644 --- a/SUPipedUnarchiver.m +++ b/SUPipedUnarchiver.m @@ -45,62 +45,60 @@ - (void)extractArchivePipingDataToCommand:(NSString *)command { // *** GETS CALLED ON NON-MAIN THREAD!!! - - - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - FILE *fp = NULL, *cmdFP = NULL; - char *oldDestinationString = NULL; - - SULog(@"Extracting %@ using '%@'",archivePath,command); - - // Get the file size. - NSNumber *fs = [[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:nil][NSFileSize]; - if (fs == nil) goto reportError; - - // Thank you, Allan Odgaard! - // (who wrote the following extraction alg.) - fp = fopen([archivePath fileSystemRepresentation], "r"); - if (!fp) goto reportError; - - oldDestinationString = getenv("DESTINATION"); - setenv("DESTINATION", [[archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], 1); - cmdFP = popen([command fileSystemRepresentation], "w"); - size_t written; - if (!cmdFP) goto reportError; - - char buf[32*1024]; - size_t len; - while((len = fread(buf, 1, 32*1024, fp))) - { - written = fwrite(buf, 1, len, cmdFP); - if( written < len ) + @autoreleasepool { + FILE *fp = NULL, *cmdFP = NULL; + char *oldDestinationString = NULL; + + SULog(@"Extracting %@ using '%@'",archivePath,command); + + // Get the file size. + NSNumber *fs = [[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:nil][NSFileSize]; + if (fs == nil) goto reportError; + + // Thank you, Allan Odgaard! + // (who wrote the following extraction alg.) + fp = fopen([archivePath fileSystemRepresentation], "r"); + if (!fp) goto reportError; + + oldDestinationString = getenv("DESTINATION"); + setenv("DESTINATION", [[archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], 1); + cmdFP = popen([command fileSystemRepresentation], "w"); + size_t written; + if (!cmdFP) goto reportError; + + char buf[32*1024]; + size_t len; + while((len = fread(buf, 1, 32*1024, fp))) { - pclose(cmdFP); + written = fwrite(buf, 1, len, cmdFP); + if( written < len ) + { + pclose(cmdFP); + goto reportError; + } + + [self performSelectorOnMainThread:@selector(notifyDelegateOfExtractedLength:) withObject:@(len) waitUntilDone:NO]; + } + pclose(cmdFP); + + if (ferror(fp)) { goto reportError; } - - [self performSelectorOnMainThread:@selector(notifyDelegateOfExtractedLength:) withObject:@(len) waitUntilDone:NO]; + + [self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO]; + goto finally; + + reportError: + [self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO]; + + finally: + if (fp) + fclose(fp); + if (oldDestinationString) + setenv("DESTINATION", oldDestinationString, 1); + else + unsetenv("DESTINATION"); } - pclose(cmdFP); - - if (ferror(fp)) { - goto reportError; - } - - [self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO]; - goto finally; - -reportError: - [self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO]; - -finally: - if (fp) - fclose(fp); - if (oldDestinationString) - setenv("DESTINATION", oldDestinationString, 1); - else - unsetenv("DESTINATION"); - [pool release]; } - (void)extractTAR diff --git a/SUPlainInstaller.m b/SUPlainInstaller.m index 47065c3b..12f3c5be 100644 --- a/SUPlainInstaller.m +++ b/SUPlainInstaller.m @@ -33,29 +33,27 @@ static NSString * const SUInstallerInstallationPathKey = @"SUInstallerInstallati { // *** GETS CALLED ON NON-MAIN THREAD! - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSError *error = nil; - - NSString * oldPath = [info[SUInstallerHostKey] bundlePath]; - NSString * installationPath = info[SUInstallerInstallationPathKey]; - BOOL result = [self copyPathWithAuthentication:info[SUInstallerPathKey] overPath: installationPath temporaryName:info[SUInstallerTempNameKey] error:&error]; - - if( result ) - { - BOOL haveOld = [[NSFileManager defaultManager] fileExistsAtPath: oldPath]; - BOOL differentFromNew = ![oldPath isEqualToString: installationPath]; - if( haveOld && differentFromNew ) - [self _movePathToTrash: oldPath]; // On success, trash old copy if there's still one due to renaming. + @autoreleasepool { + NSError *error = nil; + + NSString * oldPath = [info[SUInstallerHostKey] bundlePath]; + NSString * installationPath = info[SUInstallerInstallationPathKey]; + BOOL result = [self copyPathWithAuthentication:info[SUInstallerPathKey] overPath: installationPath temporaryName:info[SUInstallerTempNameKey] error:&error]; + + if( result ) + { + BOOL haveOld = [[NSFileManager defaultManager] fileExistsAtPath: oldPath]; + BOOL differentFromNew = ![oldPath isEqualToString: installationPath]; + if( haveOld && differentFromNew ) + [self _movePathToTrash: oldPath]; // On success, trash old copy if there's still one due to renaming. + } + NSMutableDictionary *mutableInfo = [[info mutableCopy] autorelease]; + mutableInfo[SUInstallerResultKey] = @(result); + mutableInfo[SUInstallerInstallationPathKey] = installationPath; + if (!result && error) + mutableInfo[SUInstallerErrorKey] = error; + [self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:mutableInfo waitUntilDone:NO]; } - NSMutableDictionary *mutableInfo = [[info mutableCopy] autorelease]; - mutableInfo[SUInstallerResultKey] = @(result); - mutableInfo[SUInstallerInstallationPathKey] = installationPath; - if (!result && error) - mutableInfo[SUInstallerErrorKey] = error; - [self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:mutableInfo waitUntilDone:NO]; - - [pool drain]; } + (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id )comparator @@ -76,8 +74,11 @@ static NSString * const SUInstallerInstallationPathKey = @"SUInstallerInstallati NSDictionary *info = @{SUInstallerPathKey: path, SUInstallerTargetPathKey: targetPath, SUInstallerTempNameKey: tempName, SUInstallerHostKey: host, SUInstallerDelegateKey: delegate, SUInstallerInstallationPathKey: installationPath}; if (synchronously) [self performInstallationWithInfo:info]; - else - [NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:self withObject:info]; + else { + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self performInstallationWithInfo:info]; + }); + } } @end diff --git a/SUUpdater.m b/SUUpdater.m index 88e2a7a8..e9191bd4 100644 --- a/SUUpdater.m +++ b/SUUpdater.m @@ -243,50 +243,50 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault -(void) checkForUpdatesInBgReachabilityCheckWithDriver: (SUUpdateDriver*)inDriver /* RUNS ON ITS OWN THREAD */ { - NS_DURING + @try { // This method *must* be called on its own thread. SCNetworkReachabilityCheckByName // can block, and it can be waiting a long time on slow networks, and we // wouldn't want to beachball the main thread for a background operation. // We could use asynchronous reachability callbacks, but those aren't // reliable enough and can 'get lost' sometimes, which we don't want. - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - SCNetworkConnectionFlags flags = 0; - BOOL isNetworkReachable = YES; - - // Don't perform automatic checks on unconnected laptops or dial-up connections that aren't online: - NSMutableDictionary* theDict = [NSMutableDictionary dictionary]; - [self performSelectorOnMainThread: @selector(putFeedURLIntoDictionary:) withObject: theDict waitUntilDone: YES]; // Get feed URL on main thread, it's not safe to call elsewhere. - - const char *hostname = [[theDict[@"feedURL"] host] cStringUsingEncoding: NSUTF8StringEncoding]; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostname); - Boolean reachabilityResult = NO; - // If the feed's using a file:// URL, we won't be able to use reachability. - if (reachability != NULL) { - SCNetworkReachabilityGetFlags(reachability, &flags); - CFRelease(reachability); - } - - if( reachabilityResult ) - { - BOOL reachable = (flags & kSCNetworkFlagsReachable) == kSCNetworkFlagsReachable; - BOOL automatic = (flags & kSCNetworkFlagsConnectionAutomatic) == kSCNetworkFlagsConnectionAutomatic; - BOOL local = (flags & kSCNetworkFlagsIsLocalAddress) == kSCNetworkFlagsIsLocalAddress; + @autoreleasepool { + SCNetworkConnectionFlags flags = 0; + BOOL isNetworkReachable = YES; - //NSLog(@"reachable = %s, automatic = %s, local = %s", (reachable?"YES":"NO"), (automatic?"YES":"NO"), (local?"YES":"NO")); + // Don't perform automatic checks on unconnected laptops or dial-up connections that aren't online: + NSMutableDictionary* theDict = [NSMutableDictionary dictionary]; + [self performSelectorOnMainThread: @selector(putFeedURLIntoDictionary:) withObject: theDict waitUntilDone: YES]; // Get feed URL on main thread, it's not safe to call elsewhere. + + const char *hostname = [[theDict[@"feedURL"] host] cStringUsingEncoding: NSUTF8StringEncoding]; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostname); + Boolean reachabilityResult = NO; + // If the feed's using a file:// URL, we won't be able to use reachability. + if (reachability != NULL) { + SCNetworkReachabilityGetFlags(reachability, &flags); + CFRelease(reachability); + } + + if( reachabilityResult ) + { + BOOL reachable = (flags & kSCNetworkFlagsReachable) == kSCNetworkFlagsReachable; + BOOL automatic = (flags & kSCNetworkFlagsConnectionAutomatic) == kSCNetworkFlagsConnectionAutomatic; + BOOL local = (flags & kSCNetworkFlagsIsLocalAddress) == kSCNetworkFlagsIsLocalAddress; + + //NSLog(@"reachable = %s, automatic = %s, local = %s", (reachable?"YES":"NO"), (automatic?"YES":"NO"), (local?"YES":"NO")); + + if( !(reachable || automatic || local) ) + isNetworkReachable = NO; + } + + // If the network's not reachable, we pass a nil driver into checkForUpdatesWithDriver, which will then reschedule the next update so we try again later. + [self performSelectorOnMainThread: @selector(checkForUpdatesWithDriver:) withObject: isNetworkReachable ? inDriver : nil waitUntilDone: NO]; - if( !(reachable || automatic || local) ) - isNetworkReachable = NO; } - - // If the network's not reachable, we pass a nil driver into checkForUpdatesWithDriver, which will then reschedule the next update so we try again later. - [self performSelectorOnMainThread: @selector(checkForUpdatesWithDriver:) withObject: isNetworkReachable ? inDriver : nil waitUntilDone: NO]; - - [pool release]; - NS_HANDLER + } @catch (NSException *localException) { SULog(@"UNCAUGHT EXCEPTION IN UPDATE CHECK TIMER: %@",[localException reason]); // Don't propagate the exception beyond here. In Carbon apps that would trash the stack. - NS_ENDHANDLER + } } @@ -297,7 +297,9 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault // hour or so: SUUpdateDriver * theUpdateDriver = [[[([self automaticallyDownloadsUpdates] ? [SUAutomaticUpdateDriver class] : [SUScheduledUpdateDriver class]) alloc] initWithUpdater:self] autorelease]; - [NSThread detachNewThreadSelector: @selector(checkForUpdatesInBgReachabilityCheckWithDriver:) toTarget: self withObject: theUpdateDriver]; + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self checkForUpdatesInBgReachabilityCheckWithDriver:theUpdateDriver]; + }); } diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 69b7c136..067d768c 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -266,7 +266,7 @@ 5D06E8E00FD68CC7005AE3F6 /* SUBinaryDeltaApply.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaApply.m; sourceTree = ""; }; 5D06E8E10FD68CC7005AE3F6 /* SUBinaryDeltaCommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUBinaryDeltaCommon.h; sourceTree = ""; }; 5D06E8E20FD68CC7005AE3F6 /* SUBinaryDeltaCommon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaCommon.m; sourceTree = ""; }; - 5D06E8E30FD68CC7005AE3F6 /* SUBinaryDeltaTool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaTool.m; sourceTree = ""; }; + 5D06E8E30FD68CC7005AE3F6 /* SUBinaryDeltaTool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaTool.m; sourceTree = ""; usesTabs = 0; }; 5D06E8F10FD68D21005AE3F6 /* ConfigBinaryDelta.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigBinaryDelta.xcconfig; sourceTree = ""; }; 5D06E8F20FD68D21005AE3F6 /* ConfigBinaryDeltaDebug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigBinaryDeltaDebug.xcconfig; sourceTree = ""; }; 5D06E8F30FD68D21005AE3F6 /* ConfigBinaryDeltaRelease.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigBinaryDeltaRelease.xcconfig; sourceTree = ""; }; diff --git a/finish_installation.m b/finish_installation.m index 5e00eeed..90186f0f 100644 --- a/finish_installation.m +++ b/finish_installation.m @@ -178,42 +178,41 @@ int main (int argc, const char * argv[]) return EXIT_FAILURE; } - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - //ProcessSerialNumber psn = { 0, kCurrentProcess }; - //TransformProcessType( &psn, kProcessTransformToForegroundApplication ); + @autoreleasepool { + //ProcessSerialNumber psn = { 0, kCurrentProcess }; + //TransformProcessType( &psn, kProcessTransformToForegroundApplication ); + +#if 0 // Cmdline tool + NSString* selfPath = nil; + if (argv[0][0] == '/') { + selfPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]; + } + else + { + selfPath = [[NSFileManager defaultManager] currentDirectoryPath]; + selfPath = [selfPath stringByAppendingPathComponent: [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]]; + } +#else + NSString* selfPath = [[NSBundle mainBundle] bundlePath]; +#endif + + BOOL shouldShowUI = (argc > 6) ? atoi(argv[6]) : 1; + if (shouldShowUI) + { + [[NSApplication sharedApplication] activateIgnoringOtherApps: YES]; + } + + [NSApplication sharedApplication]; + [[[TerminationListener alloc] initWithHostPath: (argc > 1) ? argv[1] : NULL + executablePath: (argc > 2) ? argv[2] : NULL + parentProcessId: (argc > 3) ? atoi(argv[3]) : 0 + folderPath: (argc > 4) ? argv[4] : NULL + shouldRelaunch: (argc > 5) ? atoi(argv[5]) : 1 + shouldShowUI: shouldShowUI + selfPath: selfPath] autorelease]; + [[NSApplication sharedApplication] run]; - #if 0 // Cmdline tool - NSString* selfPath = nil; - if (argv[0][0] == '/') { - selfPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]; } - else - { - selfPath = [[NSFileManager defaultManager] currentDirectoryPath]; - selfPath = [selfPath stringByAppendingPathComponent: [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]]; - } - #else - NSString* selfPath = [[NSBundle mainBundle] bundlePath]; - #endif - - BOOL shouldShowUI = (argc > 6) ? atoi(argv[6]) : 1; - if (shouldShowUI) - { - [[NSApplication sharedApplication] activateIgnoringOtherApps: YES]; - } - - [NSApplication sharedApplication]; - [[[TerminationListener alloc] initWithHostPath: (argc > 1) ? argv[1] : NULL - executablePath: (argc > 2) ? argv[2] : NULL - parentProcessId: (argc > 3) ? atoi(argv[3]) : 0 - folderPath: (argc > 4) ? argv[4] : NULL - shouldRelaunch: (argc > 5) ? atoi(argv[5]) : 1 - shouldShowUI: shouldShowUI - selfPath: selfPath] autorelease]; - [[NSApplication sharedApplication] run]; - - [pool drain]; return EXIT_SUCCESS; }