Re: Passing execution to a memory address
- From: Nelu <spamahead@xxxxxxxxx>
- Date: Thu, 01 Mar 2007 09:55:45 -0500
polas wrote:
Hi everyone - I have a question. I am just playing around with C (I
realise there are better ways to do what I want, but I would like to
do it this way to increase my understanding of C) and would like to
read an executable file in to a portion of memory and then pass
execution to this and execute the file. However, I can not get it
working and my efforts have resulted in a Seg Fault.
Below is the code I have got
#include "stdio.h"
it's:
#include <stdio.h>
also, you are using malloc a little later so you need stdlib.h
#include <stdlib.h>
void (*p) ();
int main()
preferable to use int main(void)
{
FILE *reader;
reader=fopen("sample", "r"); /* Open in TEXT mode */
you should make sure that fopen succeeded.
void *x=malloc(8000);
you should make sure that malloc succeeded.
int j=fread(x, 1, 8000,reader);
fread returns size_t. It shouldn't be a problem in your case but
it's a good thing to remember if you want values higher than 8000.
printf ("Read %d\n",j);
fclose(reader);
funcp=(fctype)x;
what is fctype?
printf("%d\n",x);
x is a pointer to void. You are not allowed to print it with %d.
If you want to print it's address use: printf("%p\n",x);
p=x;
That's not good. You can't assign a void pointer to a function
pointer. They're not the same thing.
printf("%d\n",p);
You can't print it like that. Not even sure you can print that.
p();
p is not pointing to a function so what is it supposed to do?
}
Where sample is a tested small executable file (compiled from c, just
to display a message.) It seems that the file is being read ok (as it
reports reading the correct number of bytes.)
Suppose we don't see the other mistakes. If sample is executable
and you open it as a text file then you're not going to read the
file properly.
I would appreciate any help on this - it seems to me that I need some
sort of equivalent jump instruction as in assembly, (instead of
function pointers) but I can not find one.
Try to use the system function. Anything else is both highly
system dependent and OT here.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
.
- Follow-Ups:
- Re: Passing execution to a memory address
- From: Keith Thompson
- Re: Passing execution to a memory address
- From: polas
- Re: Passing execution to a memory address
- References:
- Passing execution to a memory address
- From: polas
- Passing execution to a memory address
- Prev by Date: Re: When to use automatic variables and when to use malloc
- Next by Date: Re: Passing execution to a memory address
- Previous by thread: Re: Passing execution to a memory address
- Next by thread: Re: Passing execution to a memory address
- Index(es):
Relevant Pages
|