filesystem like in JM's chapter 8 with elf-exec file as data

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
ehenkes
Member
Member
Posts: 124
Joined: Mon Mar 23, 2009 3:15 am
Location: Germany
Contact:

filesystem like in JM's chapter 8 with elf-exec file as data

Post by ehenkes »

If you use text files like JM did, then everything is easy, but if you try to incorporate elf-exec-files then your fread will stop at EOF == 0x1A. Here is a work-around reading/writing headers in binary format, close, reopen/append and reading/writing data in binaty format. I would recommend to propose this code in the Tutorial, because it has higher usability:

Code: Select all

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define N 64

struct initrd_header
{
	unsigned int magic;
	char name[64];
	unsigned int offset;
	unsigned int length;
};

int main(char argc, char **argv)
{
	int nheaders = (argc-1)/2;
	struct initrd_header headers[N]; // declare N headers in Filesystem

	int i;
	for(i=0; i<N; ++i)               // set the memory of N headers to binary 0
	{
	    memset( (void*)&headers[i], 0, sizeof(struct initrd_header) );
	}

	unsigned int off = N * sizeof(struct initrd_header) + sizeof(int); // set data offset to N * 76

	for(i=0; i<nheaders; ++i)
	{
		printf("writing file %s->%s at 0x%x\n", argv[i*2+1], argv[i*2+2], off);
		strcpy(headers[i].name, argv[i*2+2]);
		headers[i].offset = off;
		FILE *stream = fopen(argv[i*2+1], "rb");
		if(stream == 0)
		{
			printf("Error: file not found: %s\n", argv[i*2+1]);
			return 1;
		}
		fseek(stream, 0, SEEK_END);
		headers[i].length = ftell(stream);
		off += headers[i].length;
		fclose(stream);
		headers[i].magic = 0xBF;
	}

	FILE *wstream = fopen("./initrd.img", "wb");
	unsigned char *data = (unsigned char *)malloc(off);
	fwrite(&nheaders, sizeof(int), 1, wstream);
	fwrite(headers, sizeof(struct initrd_header), N, wstream); // write N headers

    fclose(wstream);
    wstream = fopen("./initrd.img", "ab");

	for(i=0; i<nheaders; i++)
	{
		FILE *stream = fopen(argv[i*2+1], "rb");
		unsigned char *buf = (unsigned char *)malloc(headers[i].length);
		fread(buf, 1, headers[i].length, stream);
		fwrite(buf, 1, headers[i].length, wstream);
		fclose(stream);
		free(buf);
	}

	fclose(wstream);
	free(data);

	return 0;
}
Post Reply