AndybnACT / NCTU-Unix-Programming

This repo contains all homework that I've done for the class "Advanced Programming in the Unix Environment" at NCTU

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fail on stderr redirection (hw2)

AndybnACT opened this issue · comments

If fsmon.so is loaded with a command that redirects stderr to a file, the process fails with SIGSEGV. Example is provided as below:

$ LD_PRELOAD=./fsmon.so ./testcase/dir 2>./test
[1]    18527 segmentation fault (core dumped) 

The reason behind this issue is related to BASH's redirection mechanism. As we may see in the source code of BASH, before it opens the redirected ./test file, the function make_redirection prepares the flag that will be passed to redir_open. The redirection provided in the test case belongs to r_output_direction so that ./test will be opened with flags O_TRUNC | O_WRONLY | O_CREAT, which does not imply 'read' capability.

However, when our fsmon.so reopens stderr as the I/O stream logFILE with fdopen at startup routine, the passed flag "w+", which implies r/w capabilities, is not consistent with the file descriptor opened by BASH. Thus, the invalid argument causes fdopen to return a NULL pointer and the following SIGSEGV at any dereference of logFILE such as fprintf(logFILE, ...).

To solve this problem, simply delete the "+" character at fdopen, just as commit 70c1c41 does

We could also test the original version with $ LD_PRELOAD=./fsmon.so ./testcase/dir 2<>./test , then everything would turn out alright. In this way, the ./test will be opened with O_RDWR | O_CREAT.

Dang, I got 10 points original score on this project just because this single "+" character. What a world!!

I got 96-10=86 for this issue finally. Though I am still curious about where did I loss the 4% according to the grading policy, It would be too irritating to ask among this topic. And I'm not a person who really cares about grades if it doesn't look like a joke. Never mind~
BASH redirection