Getting a crash in NSTask - macos

I've had a report from the field of a crash at -launch on NSTask.
The code in question is:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/bin/zsh"];
if(ignore)
{
[task setArguments:#[scriptPath, recordingFolder, Argument]];
}
else
{
[task setArguments:#[scriptPath, recordingFolder]];
}
NSPipe *outPipe = [NSPipe pipe];
[task setStandardOutput:outPipe];
NSPipe *errorPipe = [NSPipe pipe];
[task setStandardError:errorPipe];
[task launch];
The scriptPath is a script that is included in the app bundle.
The crash says:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to set posix_spawn_file_actions for fd -1 at index 0 with errno 9'
What could be the cause of this? What file descriptor do the posix_spawn_file_actions refer to? Does it mean that the executable script is wrong or that the outPipe or errPipe are not well formed?
I believe it is referring to the posix_spawn function:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/posix_spawn.2.html
And errno 9 is EBADF (bad file number).

I've got a similar error , after I use below command, it's OK, you can try it.
NSFileHandle *file=[outPipe fileHandleForReading];
[task launch];
....//read file.
//this is the most important.
[file closeFile];

If you are calling this code many different times sequentially, you are running out of file descriptors -- you need to close the pipes after you are done. The correct way to do it is to deallocate NSTask and it will close the file channels. Put the NSTask-related code in an autoreleasepool statement:
#autoreleasepool {
NSTask* task = [NSTask new];
...
[task launch];
...
[task waitUntilDone];
}

For the issue in the question, I suggest that we should put the code of CreateProcess() in an #autoreleasepool block as Apple's doc shows that we should not send -[closeFile] to fileHandleForReading explicitly.
https://developer.apple.com/reference/foundation/nspipe/1414352-filehandleforreading?language=objc
Declaration
#property(readonly, retain) NSFileHandle *fileHandleForReading;
Discussion
The descriptor represented by this object is deleted, and the object
itself is automatically deallocated when the receiver is deallocated.
You use the returned file handle to read from the pipe using
NSFileHandle's read methods—availableData, readDataToEndOfFile, and
readDataOfLength:.
You don’t need to send closeFile to this object or explicitly release
the object after you have finished using it.

Related

Xcode 8 extension executing NSTask

My goal is to create an extension that executes clang-format. My code looks something like this:
- (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocation completionHandler:(void (^)(NSError * _Nullable nilOrError))completionHandler
{
NSError *error = nil;
NSURL *executableURL = [[self class] executableURL];
if (!executableURL)
{
NSString *errorDescription = [NSString stringWithFormat:#"Failed to find clang-format. Ensure it is installed at any of these locations\n%#", [[self class] clangFormatUrls]];
completionHandler([NSError errorWithDomain:SourceEditorCommandErrorDomain
code:1
userInfo:#{NSLocalizedDescriptionKey: errorDescription}]);
return;
}
NSMutableArray *args = [NSMutableArray array];
[args addObject:#"-style=LLVM"];
[args addObject:#"someFile.m"];
NSPipe *outputPipe = [NSPipe pipe];
NSPipe *errorPipe = [NSPipe pipe];
NSTask *task = [[NSTask alloc] init];
task.launchPath = executableURL.path;
task.arguments = args;
task.standardOutput = outputPipe;
task.standardError = errorPipe;
#try
{
[task launch];
}
#catch (NSException *exception)
{
completionHandler([NSError errorWithDomain:SourceEditorCommandErrorDomain
code:2
userInfo:#{NSLocalizedDescriptionKey: [NSString stringWithFormat:#"Failed to run clang-format: %#", exception.reason]}]);
return;
}
[task waitUntilExit];
NSString *output = [[NSString alloc] initWithData:[[outputPipe fileHandleForReading] readDataToEndOfFile]
encoding:NSUTF8StringEncoding];
NSString *errorOutput = [[NSString alloc] initWithData:[[errorPipe fileHandleForReading] readDataToEndOfFile]
encoding:NSUTF8StringEncoding];
[[outputPipe fileHandleForReading] closeFile];
[[errorPipe fileHandleForReading] closeFile];
int status = [task terminationStatus];
if (status == 0)
{
NSLog(#"Success: %#", output);
}
else
{
error = [NSError errorWithDomain:SourceEditorCommandErrorDomain
code:3
userInfo:#{NSLocalizedDescriptionKey: errorOutput}];
}
completionHandler(error);
}
The reason I need that try-catch block is because an exception is thrown when I try to run this code. The exception reason is:
Error: launch path not accessible
The path for my clang-format is /usr/local/bin/clang-format. What I discovered is that it doesn't like me trying to access an application in /usr/local/bin, but /bin is ok (e.g. If I try to execute /bin/ls there is no problem).
Another solution I tried was to run /bin/bash by setting the launch path and arguments like this:
task.launchPath = [[[NSProcessInfo processInfo] environment] objectForKey:#"SHELL"];
task.arguments = #[#"-l", #"-c", #"/usr/local/bin/clang-format -style=LLVM someFile.m"];
This successfully launches the task, but it fails with the following error output:
/bin/bash: /etc/profile: Operation not permitted
/bin/bash: /usr/local/bin/clang-format: Operation not permitted
The first error message is due to trying to call the -l parameter in bash, which tries to log in as the user.
Any idea how I can enable access to those other folders? Is there some kind of sandbox environment setting I need to enable?
I guess that because of the sandboxing this is not possible.
You could bundle the clang-format executable and use it from there.
Personally, I think you are going at it all wrong. Extensions are supposed to be quick (if you watch the video on Xcode extensions he repeats multiple times to get in and get out). And they are severely limited.
However, there is another - the container app may be able to do this processing for your extension without all the hacks. The downside is that you have to pass the buffer to and from the extension.
It’s not easy, but it can be done. Easy peasy way to get your container to run. First, modify the container app’s Info.plist (not the extension Info.plist) so that it has a URL type.
In your extension you can “wake up” the container app by running the following:
let customurl = NSURL.init(string: “yoururlschemehere://")
NSWorkspace.shared().open(customurl as! URL)
As for communication between the two, Apple has a plethora of methods. Me, I’m old-school, so I’m using DistributedNotificationCenter - for the moment.
Although I haven’t tried it, I do not see why the container app should have an issue chatting with clang (I’m using the container app for settings).

Mac OS X: Execute scripts with hooks from an application

Im building an cocoa app that monitors something™ and I am planning to have some hooks for users. So I want to enable the user to put a script (Bash, Ruby, Python you name it) with a specified name (let's say after_event) into the Application Support directory and that script gets executed after a certain event in my code. Ideally I could pass some variables to the script so the script knows what happened.
Any ideas on this?
So problem one is: How do I get the path of the Application Support "the SDK way"? problem two is: How do I execute script with variables like THAT_APPEND="foo"?
Thanks,
Philip
Because sharing is caring here is the method that executes the scripts:
-(void) runScript:(NSString*)scriptName withVariables:(NSDictionary *)variables
{
NSString *appSupportPath = [NSFileManager defaultManager] applicationSupportDirectory];
NSArray *arguments;
NSString* newpath = [NSString stringWithFormat:#"%#/%#",appSupportPath, scriptName];
if ([[NSFileManager defaultManager]fileExistsAtPath:newpath]){
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: newpath];
NSLog(#"Executing hook: %#",newpath);
arguments = [NSArray arrayWithObjects:newpath, nil];
[task setArguments: arguments];
[task setEnvironment:variables];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (#"script returned:\n%#", string);
}
}
}
UPDATE: I updated the code to be more generic. Now NSTask will tell the kernel to execute the script directly so your user can not online use Bash scripts but also python, perl, php whatever she likes. The only thing she needs to use is a Shebang in that file.
The NSFileManager Category can be found here.
Look for NSTask documentation. There's an environment member you can manipulate. Also adding command line parameters in a form -name = value should be trivial.

NSTask Does Not Terminate

I'm trying to use NSTask to run the UNIX 'apropos' command. Here's my code:
NSTask *apropos = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
[apropos setLaunchPath:#"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:#"filename", #"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];
The problem is that this never returns. I also tried using Apple's example code (TaskWrapper) and it returns the output (in three segments) but it never calls the processFinished handler.
Furthermore, the appendOutput: handler receives duplicates. So, for example, if apropos returns this:
1
2
3
4
5
I might receive something like this:
1
2
3
1
2
3
4
5
(grouped into 3 append messages).
I note that Apropos displays the output in a format where it's possible to scroll up and down in the command line instead of just directly outputting the data straight to standard output; how do I read this reliably through NSTask and NSPipe?
I’ve just tested this program and it works fine: the program terminates and /tmp/apropos.txt contains the output of apropos.
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSTask *apropos = [[[NSTask alloc] init] autorelease];
NSPipe *pipe = [[[NSPipe alloc] init] autorelease];
NSFileHandle *readHandle = [pipe fileHandleForReading];
[apropos setLaunchPath:#"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:#"filename", #"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];
NSString *output = [[[NSString alloc]
initWithData:[readHandle readDataToEndOfFile]
encoding:NSUTF8StringEncoding] autorelease];
[output writeToFile:#"/tmp/apropos.txt" atomically:YES
encoding:NSUTF8StringEncoding error:NULL];
[pool drain];
return 0;
}
Are you by any chance using NSLog() to inspect the output? If so, you might need to set a pipe for stdin as explained in this answer of mine to an NSTask related question. It seems that NSLog() sending data to stderr affects NSTask.
With your original code, I would imagine it's because you're not reading the output of the command. The pipes only have a limited buffer size, and if you don't read the output of the task, it can end up hung waiting for the buffer to empty out. I don't know anything about the sample code you tried so I can't help there. As for the last question, apropos only uses the pager when it's connected to a terminal. You're not emulating a terminal, so you don't have to worry. You can prove this by running apropos whatever | cat in the terminal and verifying that the pager is not invoked.

NSTask Launch causing crash

I have an application that can import an XML file through this terminal command :
open /path/to/main\ app.app --args myXML.xml
This works great with no issues. And i have used Applescript to launch this command through shell and it works just as well. Yet when try using Cocoa's NSTask Launcher using this code :
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/open"];
[task setCurrentDirectoryPath:#"/Applications/MainApp/InstallData/App/"];
[task setArguments:[NSArray arrayWithObjects:[(NSURL *)foundApplicationURL path], #"--args", #"ImportP.xml", nil]];
[task launch];
the applications will start up to the initial screen and then crash when either the next button is clicked or when trying to close the window. Ive tried using NSAppleScript with this :
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:#"tell application \"Terminal\" do script \"open /Applications/MainApp/InstallData/App/Main\\\\ App.app\" end tell"];
NSDictionary *errorInfo;
[script executeAndReturnError:&errorInfo];
This will launch the program and it will crash as well and i get this error in my Xcode debug window :
12011-01-04 17:41:28.296 LaunchAppFile[4453:a0f]
Error loading /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: dlopen(/Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types, 262): no suitable image found.
Did find: /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: no matching architecture in universal wrapper
LaunchAppFile: OpenScripting.framework - scripting addition "/Library/ScriptingAdditions/Adobe Unit Types.osax" declares no loadable handlers.
So with research i came up with this :
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:#"do shell script \"arch -i386 osascript /Applications/MainApp/InstallData/App/test.scpt\""];
NSDictionary *errorInfo;
[script executeAndReturnError:&errorInfo];
But this causes the same results as the last command.
Any ideas on what causes this crash?
Check here to fix the adobe errors. I'm not sure that's the problem though. Actually I couldn't get the open command to pass arguments to anything so I couldn't look into your problem.
Give NSTask another try with full paths only:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/open"];
[task setArguments:[NSArray arrayWithObjects:[ #"'/path/to/main app.app'", #"--args", #"/path/to/ImportP.xml", nil]];
[task launch];
Another approach would be to give NSTask the following command line:
sh -c '/usr/bin/open "/path/to/main app.app" --args /path/to/myXML.xml'
...
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/bin/sh"];
NSString *cmd = [NSString stringWithFormat:
#"%# %# %# %#",
#"/usr/bin/open",
#"'/path/to/main app.app'",
#"--args",
#"/path/to/myXML.xml"
];
[task setArguments:[NSArray arrayWithObjects:[ #"-c", cmd, nil]];
[task launch];

Sending an E-Mail with attachments in Cocoa

I have an NSTextView with text & images in it, which is supposed to send both in an e-mail.I know that the message.framework is deprecated,so I came up with the idea to send it via NSTask, since mail is integrated.I came up with the code below, however in the log I get this:
*** -[NSCFDictionary setObject:forKey:]: attempt to insert
nil value (key:
_NSTaskInputFileHandle)
This is the code I am using:
NSError *error;
if([textView writeRTFDToFile:#"/Library/Application Support/log.rtfd" atomically:NO])
{
NSArray *args = [NSArray arrayWithObjects:#"-s", [subject stringValue], [sendto stringValue], nil];
NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:#"/usr/bin/mailx"];
[task setArguments:args];
[task setStandardInput:[NSFileHandle fileHandleForReadingAtPath:#"/Library/Application Support/log.rtfd"]];
[task launch];
[task waitUntilExit];
Can someone tell me what I am doing wrong?
You can also try the Scripting Bridge. See Apple's SBSendEmail example.

Resources