Re: Writing to text segment



On Jun 10, 6:05 pm, santosh <santosh....@xxxxxxxxx> wrote:
rahul wrote:
On Jun 10, 2:11 pm, Ian Collins <ian-n...@xxxxxxxxxxx> wrote:
rahul wrote:
void foo(void) {
/* blah blah */
}

char buf[] = {....};
memcpy( (void *)&foo, buf, sizeof buf);

This thing is giving segmentation fault on RHEL 5/gcc 4.1. Is the
text segment protected? I am assuming foo has enough space for buf.

I'm amazed you even managed to get it, what ever it is, to compile.

Post real code.
The code is real, just abridged. Would you elaborate why this should
not compile?

Because it won't compile?

For short programs (especially when the OP does not know the exact place
where the bug first occurs), this group generally prefers a complete,
compilable program to be posted. This way the regulars can compile it
themselves; compiler diagnostics are a great help in troubleshooting.
Except it a minority of cases, it's very hard to pinpoint errors from
isolated code fragments, unless fortuitously, the error just happens to
be within the fragment. Even in that case the actual observed bug may
have been caused by other errors upstream.


/* BEGIN bar.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 100

/* Just allocating enough space for copying */
int
bar (void) {
volatile int i = 1;
i = 2;
i = 3;
i = 4;
i = 5;
i = 6;
return i;
}

int
main (void) {
int fd = fopen ("foo.o", O_RDONLY);
int nread = 0;
int ret;
char buf[SIZE];
nread = read (fd, buf, SIZE);
memcpy ( (void *)&bar, (void *)buf, SIZE);
ret = bar();
return 0;
}

/* BEGIN foo.c */
int
foo (void) {
return 1;
}
/* foo.c compiled as Position Independent Code */

Is it good enough for you? This thing is just the skeleton of the real
code.

My problem was not related to compiling or running the program. My
question was about
the behavior as per standards when one writes to .text segment. I
already have got the answer.
..text is read-only ( at least in linux).
And can you tell me now why it is not supposed to compile?
.



Relevant Pages