strcpy causing EXC_BAD_ACCESS? - objective-c

I am making a command-line tool using Xcode 4.
I get the EXC_BAD_ACCESS error on the line with strcpy:
char *invalidOption = NULL;
strcpy(invalidOption, argv[2]);
argv[1] is -v (a "valid" option) and argv[2] is -z (an "invalid" option).
I then need to change "invalidOption" for display reasons (printing the "error" message).
Any ideas as to why this is happening?
Please let me know if you need any more details.

strcpy doesn't allocate any memory for you. You're trying to copy your string to NULL, which causes undefined behaviour. You need something like:
char invalidOption[10];
strcpy(invalidOption, argv[2]);
Just make sure that invalidOption is big enough to hold the whole string (including null terminator) or you'll end up with the same problem. You can use dynamic allocation if necessary.

Related

How to get return error code of popen?

I want the error code which return by 'popen'.
Popen command is as below:
fp = popen("/system/bin/pgrep -f "/system/bin/ffmpeg -loglevel quiet -re -i /data/misc/qmmf/LiveStreaming_FIFO_1.264 -codec copy -f rtsp -rtsp_transport tcp rtsp://11.11.11.11:554/live/stream1?wowzatoken=B-VDkZmspHh-G49SQIKghznGAHryq5zNc3NE7KEDgx8=" ","r");
I am getting the PID of the currently running ffmpeg process and am reading this popen() using a file pointer in an array. Then, read the PID(char by chat and using atoi()) and kill that PID.
Checking the (fp == NULL), but not getting NULL pointer.
Mainly, I want to kill that ffmpeg process. Not all running ffmpeg process, but the specific one which distinguishes by its name.
Are there any other ways apart from this?
Any suggestions would helpful.
Assuming a Linux system, man 3 popen explains the programming interface. popen() will return NULL when fork/pipe call fail or memory cannot be allocated. On success I/O stream pointer is returned. The value of the variable doesn't change unless a new value is assigned to the variable.
To wait for the process to terminate, you should use pclose(), which will return -1 on error. Additionally, both functions set errno if an error occurs.
If you need to reliably get the child process' PID, you need to do fork() call in your code and use it's return value. Since you won't be using popen(), you also need to set up pipe(s) in your code.
I don't know that I fully understand your question, but this is what the man page says about popen() errors:
RETURN VALUE
The popen() function returns NULL if the fork(2) or pipe(2) call fails, or if it cannot allocate memory.
ERRORS
The popen() function does not set errno if memory allocation fails. If the underlying fork(2) or pipe(2) fails, errno is set appropriately. If the type argument is invalid, and this condition is detected, errno is set to EINVAL.
Are you checking errno in addition to checking the return value?

Ghostscript for PS integrity test: terminate at EOF, return error unless stack is empty

To test the integrity of PostScript files, I'd like to run Ghostscript in the following way:
Return 1 (or other error code) on error
Return 0 (success) at EOF if stack is empty
Return 1 (or other error code) otherwise
I could run gs in the background, and use a timeout to force termination if gs hangs with items left on the stack. Is there an easier solution?
Ghostscript won't hang if you send files as input (unless you write a program which enters an infinite loop or otherwise fails to reach a halting state). Having items on any of the stacks won't cause it to hang.
On the other hand, it won't give you an error if a PostScript program leaves operands on the operand stack (or dictionaries on the dictionary stack, clips on the clip stack or gstates on the graphics state stack). This is because that's not an error, and since PostScript interpreters normally run in a job server loop its not a problem either. Terminating the job returns control to the job server loop which does a save and restore round the total job, thereby clearing up anything left behind.
I'd suggest that if you really want to do this you need to adopt the same approach, you need to write a PostScript program which executes the PostScript program you want to 'test', then checks the operand stack (and other stacks if required) to see if anything is left. Note that you will want to execute the test program in a stopped context, as an error in the course of the program will clearly potentially leave stuff lying around.
Ghostscript returns 0 on a clean exit and a value less than 0 for errors, if I remember correctly. You would need to use signalerror in your test framework in order to raise an error if items are left at the end of a program.
[EDIT]
Anything supplied to Ghostscript on the command line by either -s or -d is defined in systemdict, so if we do -sInputFileName=/test.pdf then we will find in systemdict a key /InputFileName whose value is a string with the contents (/test.pdf). We can use that to pass the filename to our program.
The stopped operator takes an executable array as an argument, and returns either true or false depending on whether an error occurred while executing the array (3rd Edition PLRM, p 697).
So we need to run the program contained in the filename we've been given, and do it in a 'stopped' context. Something like this:
{InputFileName run} stopped
{
(Error occurred\n) print flush
%% Potentially check $error for more information.
}{
(program terminated normally\n) print flush
%% Here you could check the various stacks
} ifelse
The following, based 90% on KenS's answer, is 99% satisfactory:
Program checkIntegrity.ps:
{Script run} stopped
{
(\n===> Integrity test failed: ) print Script print ( has error\n\n) print
handleerror
(ignore this error which only serves to force a return value of 1) /syntaxerror signalerror
}{
% script passed, now check the stack
count dup 0 eq {
pop (\n===> Integrity test passed: ) print Script print ( terminated normally\n\n) print
} {
(\n===> Integrity test failed: ) print Script print ( left ) print
3 string cvs print ( item(s) on stack\n\n) print
Script /syntaxerror signalerror
} ifelse
} ifelse
quit
Execute with
gs -q -sScript=CodeToBeChecked.ps checkIntegrity.ps ; echo $?
For the last 1% of satisfaction I would need a replacement for
(blabla) /syntaxerror signalerror
It forces exit with return code 1, but is very verbous and distracts from the actual error in the checked script that is reported by handleerror. Therefore a cleaner way to exit(1) would be welcome.

How to access debug information in a running application

I was wondering if it is possible to access debug information in a running application that has been compiled with /DEBUG (Pascal and/or C), in order to retrieve information about structures used in the application.
The application can always ask the debugger to do something using SS$_DEBUG. If you send a list of commands that end with GO then the application will continue running after the debugger does its thing. I've used it to dump a bunch of structures formatted neatly without bothering to write the code.
ANALYZE/IMAGE can be used to examine the debugger data in the image file without running the application.
Although you may not see the nice debugger information, you can always look into a running program's data with ANALYZE/SYSTEM .. SET PROCESS ... EXAMINE ....
The SDA SEARCH command may come in handy to 'find' recognizable morcels of date, like a record that you know the program must have read.
Also check out FORMAT/TYPE=block-type, but to make use of data you'll have to compile your structures into .STB files.
When using SDA, you may want to try run the program yourself interactively in an other session to get sample sample addresses to work from.... easier than a link map!
If you programs use RMS a bunch (mine always do :-), then SDA> SHOW PROC/RMS=(FAB,RAB) may give handy addresses for record and key buffers, allthough those may also we managed by the RTL's and thus not be meaningful to you.
Too long for a comment ...
As far as I know, structure information about elements is not in the global symbol table.
What I did, on Linux, but that should work on VMS/ELF files as well:
$ cat tests.c
struct {
int ii;
short ss;
float ff;
char cc;
double dd;
char bb:1;
void *pp;
} theStruct;
...
$ cc -g -c tests.c
$ ../extruct/extruct
-e-insarg, supply an ELF object file.
Usage: ../extruct/extruct [OPTION]... elf-file variable
Display offset and size of members of the named struct/union variable
extracted from the dwarf info in the elf file.
Options are:
-b bit offsets and bit sizes for all members
-lLEVEL display level for nested structures
-n only the member names
-t print base types
$ ../extruct/extruct -t ./tests.o theStruct
size of theStruct: 0x20
offset size type name
0x0000 0x0004 int ii
0x0004 0x0002 short int ss
0x0008 0x0004 float ff
0x000c 0x0001 char cc
0x0010 0x0008 double dd
0x0018 0x0001 char bb:1
0x001c 0x0004 pp
$

What's the line after execve for since it doesn't return on success?

26: execve(prog[0],prog,env);
27: return 0;
execve() does not return on success, and the text, data, bss, and
stack of the calling process are overwritten by that of the program
loaded.
what's return 0; for?
I suggest it is to cease this compiler warning.
$ cat | gcc -W -Wall -x c -
int main(){}
^D
<stdin>: In function 'main':
<stdin>:1:1: warning: control reaches end of non-void function
This also will make happy static analyzers and IDE warnings about same thing.
That line is in case execve() somehow fails and does return. Theoretically, it never should happen, but it does sometimes. Often, the return value is set to some random number to signify that there was an error.

File Output using Gforth

As a first project I have been writing a short program to render the Mandelbrot fractal. I have got to the point of trying to output my results to a file ( e.g. .bmp or .ppm ) and got stuck.
I have not really found any examples of exactly what I am trying to do, but I have found two examples of code to copy from one file to another.
The examples in the Gforth documentation ( Section 3.27 ) did not work for me ( winXP ) in fact they seemed to open and create files but not write to files properly.
This is the Gforth documentation example that copies the contents of one file to another:
0 Value fd-in
0 Value fd-out
: open-input ( addr u -- ) r/o open-file throw to fd-in ;
: open-output ( addr u -- ) w/o create-file throw to fd-out ;
s" foo.in" open-input
s" foo.out" open-output
: copy-file ( -- )
begin
line-buffer max-line fd-in read-line throw
while
line-buffer swap fd-out write-line throw
repeat ;
I found this example ( http://rosettacode.org/wiki/File_IO#Forth ) which does work. The main problem is that I can't isolate the part that writes to a file and have it still work. The main confusion is that >r doesn't seem to consume TOS as I might expect.
: copy-file2 ( a1 n1 a2 n2 -- )
r/o open-file throw >r
w/o create-file throw r>
begin
pad maxstring 2 pick read-file throw
?dup while
pad swap 3 pick write-file throw
repeat
close-file throw
close-file throw ;
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file
I would be very grateful if someone could explain exactly how the open, create read and write -file words actually work, as my investigation keeps resulting in somewhat bizarre stacks.
Any clues as to why the Gforth examples do not work might help too.
In summary, I want to output from Gforth to a file and so far have been thwarted. Can anyone offer any help?
Thank you Vijay, I think that I understand the example that you gave. However when I try to use something like this ( which I think is similar ):
0 value test-file
: write-test
s" testfile.out" w/o create-file throw to test-file
s" test text" test-file write-line ;
I get ok but nothing is put into the file, have I made a mistake?
It seems that the problem was due to not flushing the relevant buffers or explicitly closing the file. Adding something like
test-file flush-file throw
or
test-file close-file throw
between write-line and ; makes it work. Consequently the Gforth documentation example would have worked had I followed the instructions.
Thanks again Vijay for helping.
I will try to explain how write-line works with this simple example. Here we have a buffer that contains the string " hello", and we want to write that to a file opened with open-output.
buffer 5 fd-out write-line
5 is the length of the buffer. fd-out is the open file handle. A call to write-line will leave an integer result on the stack, the value of which is implementation dependent. More information on the file I/O words could be found in File Access words.
Calling the word throw is optional. It will check the integer value on the top of the stack and based on that value either pops the topmost exception frame from the exception stack or call abort or display an implementation-dependent message giving information about the condition associated with the integer. (Exact details on how throw works could be found in THROW).
You program is incomplete, which makes the question hard to answer.
With prepending
1024 CONSTANT max-line
CREATE line-buffer max-line 3 + ALLOT
and postpending
copy-file
fd-in close-file throw
fd-out close-file throw
and after creating a testfile foo.in gforth the first program works flawlessly on Debian.
Probably your problem is caused by not properly closing the file after writing.