예제 #1
0
파일: fattest.c 프로젝트: MikrySoft/openfat
int main(int argc, char *argv[])
{
	struct block_device *bldev;
	FatVol vol;
	FatFile file;
	char *rootpath = argc > 2 ? argv[2] : "/";

	bldev = block_device_file_new(argc > 1 ? argv[1] : "fat32.img", "r+");
	assert(bldev != NULL);

	assert(fat_vol_init(bldev, &vol) == 0);
	fprintf(stderr, "Fat type is FAT%d\n", vol.type);

	fat_mkdir(&vol, "Directory1");
	fat_mkdir(&vol, "Directory2");
	fat_mkdir(&vol, "Directory3");
	assert(fat_chdir(&vol, "Directory1") == 0);
	fat_mkdir(&vol, "Directory1");
	fat_mkdir(&vol, "Directory2");
	fat_mkdir(&vol, "Directory3");
	if(fat_create(&vol, "Message file with a long name.txt", O_WRONLY, &file) == 0) {
		for(int i = 0; i < 100; i++) {
			char message[80];
			sprintf(message, "Here is a message %d\n", i);
			assert(fat_write(&file, message, strlen(message)) == (int)strlen(message));
		}
	}
	assert(fat_chdir(&vol, "..") == 0);
	assert(fat_open(&vol, ".", O_RDONLY, &file) == 0);
	print_tree(&vol, &file, rootpath[0] == '/' ? rootpath + 1 : rootpath);

	block_device_file_destroy(bldev);
}
예제 #2
0
void sdcallback(enum sd_event event)
{
	uint8_t ret;
	DBG_INFO("[sd]: ");
	switch(event)
	{
		case sd_event_inserted:
			printf("card inserted\n");
			break;
		case sd_event_inserted_wp:
			printf("card inserted (WP!)\n");
			break;
		case sd_event_removed:
			printf("card removed\n");
			break;
		case sd_event_initialized:
			printf("card initialized\n");
			ret = partition_open(&partition,sd_read,0,0);
			fat_close(fatfs);
			fatfs = fat_open(&partition);
			fat_root = fat_get_dir_entry(fatfs, "/");
			tftpd_init(fat_root);
			//httpd_chroot(fat_root);
			break;
		case sd_event_error:
			DBG_ERROR("error %x\n",sd_errno());
			break;
		default:
			DBG_ERROR("unknown event\n");
			break;
	}
}
예제 #3
0
uint8_t SDCardClass::init() {
  if (isInit)
    return 0;
  
  if (fs != NULL) {
    fat_close(fs);
    fs = NULL;
  }

  if (partition != NULL) {
    partition_close(partition);
    partition = NULL;
  }
  
  if (!sd_raw_init()) {
    return 1;
  }

  partition = partition_open(sd_raw_read, sd_raw_read_interval,
			     sd_raw_write, sd_raw_write_interval,
			     0);

  if (!partition) {
    return 2;
  }

  fs = fat_open(partition);
  if (!fs) {
    return 3;
  }

  isInit = true;

  return 0;
}
char init_filesystem(void)
{
	//setup sd card slot 
	if(!sd_raw_init())
	{
		return 0;
	}

	//open first partition
	partition = partition_open(sd_raw_read,
									sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
									sd_raw_write,
									sd_raw_write_interval,
#else
									0,
									0,
#endif
									0
							   );

	if(!partition)
	{
		//If the partition did not open, assume the storage device
		//is a "superfloppy", i.e. has no MBR.
		partition = partition_open(sd_raw_read,
								   sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
								   sd_raw_write,
								   sd_raw_write_interval,
#else
								   0,
								   0,
#endif
								   -1
								  );
		if(!partition)
		{
			return 0;
		}
	}

	//Open file system
	fs = fat_open(partition);
	if(!fs)
	{
		return 0;
	}

	//Open root directory
	fat_get_dir_entry_of_path(fs, "/", &dir_entry);
	dd=fat_open_dir(fs, &dir_entry);
	
	if(!dd)
	{
		return 0;
	}
	return 1;
}
예제 #5
0
uint8_t RepRapSDCard::open_filesys(void)
{
  /* open file system */
  fs = fat_open(partition);
  if(!fs)
    return 0;

  return 1;
}
예제 #6
0
/******************************************************************************
 * User API
 ******************************************************************************/
char FAT::initialize()
{


	//setup sd card slot 
	if(!sd_raw_init())
	{
		return 0;
	}
	
	PORTB |= (1<<0);
	
	//open first partition
	_partition = partition_open(sd_raw_read,
									sd_raw_read_interval,
									sd_raw_write,
									sd_raw_write_interval,
									0
							   );

	if(!_partition)
	{
		//If the partition did not open, assume the storage device
		//is a "superfloppy", i.e. has no MBR.
		_partition = partition_open(sd_raw_read,
								   sd_raw_read_interval,
								   sd_raw_write,
								   sd_raw_write_interval,
								   -1
								  );
		if(!_partition)
		{
			return 0;
		}
	}

	//Open file system
	//struct fat_fs_struct* fs = fat_open(partition);
	_fs = fat_open(_partition);
	if(!_fs)
	{
		return 0;
	}

	//Open root directory
	//struct fat_dir_entry_struct directory;
	fat_get_dir_entry_of_path(_fs, "/", &_directory);

	//struct fat_dir_struct* dd = fat_open_dir(fs, &directory);
	_dd=fat_open_dir(_fs, &_directory);
	if(!_dd)
	{
		return 0;
	}
	return 1;
}
예제 #7
0
void list_dir(void *arg) {
	terminal_clear();
	printf("%s\n", path);
	printf("%s", arg);
	
	int files, fd, i, j, k;
	
	for(i = 0; i < 8; i++) {
		dir[i][0] = 0;
	}
	
	uint8_t stat;
	struct FATDirList list[8];
	char *buf, *tmp;
	for(files = 0; (i = fat_dirlist(path, list, 8, files)); files += i) {
		for (j = i - 1; j >= 0; j--) {
			if(list[j].filename[0]) {
				stat = list[j].attrib;
				
				//skip volume labels
				if(stat & 0x8)
					continue;
				
				if(list[j].filename[0] == '.')
					continue;
				
				buf = dir[j];
				
				for(k = 5; k != ~0; k--) {
					if(stat & (0x1 << k))
						*buf++ = attribs[k];
					else
						*buf++ = '-';
				}
				if(stat & 0x10) {
					*buf++ = '\t';
					*buf++ = '\t';
				} else {
					pathcat((char *) pathbuf, path, list[j].filename);
					fd = fat_open(pathbuf, O_RDONLY);
					*buf++ = '\t';
					//print_filesize(fat_fsize(fd));
					*buf++ = '0';
					*buf++ = '\t';
					fat_close(fd);
				}
				tmp = list[j].filename;
				
				while(*tmp) {
					*buf++ = *tmp++;
				}
				*buf = 0;
			}
		}
	}
}
예제 #8
0
파일: test_fat.c 프로젝트: mitlab/oggbox
int main(int argc, char *argv[]) {
  int p = 0;
  int rerrno = 0;
  FILE *fp;
  int len;
  uint8_t *d;
//   int v;
  printf("Running FAT tests...\n\n");
  printf("[%4d] start block device emulation...", p++);
  printf("   %d\n", block_init());
  
  printf("[%4d] mount filesystem, FAT32", p++);
  printf("   %d\n", fat_mount(0, PART_TYPE_FAT32));

//   p = test_open(p);

  int fd;
  
//   printf("Open\n");
//   fd = fat_open("/newfile.txt", O_WRONLY | O_CREAT, 0777, &rerrno);
//   printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno));
//   if(fd > -1) {
//     printf("Write\n");
//     fat_write(fd, "Hello World\n", 12, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//     printf("Close\n");
//     fat_close(fd, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//   }
  
  printf("Open\n");
  fd = fat_open("/newfile.png", O_WRONLY | O_CREAT, 0777, &rerrno);
  printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno));
  if(fd > -1) {
    fp = fopen("/home/nathan/gowrong_draft1.png", "rb");
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    d = malloc(len);
    fseek(fp, 0, SEEK_SET);
    fread(d, 1, len, fp);
    fclose(fp);
    printf("Write PNG\n");
    fat_write(fd, d, len, &rerrno);
    printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
    printf("Close\n");
    fat_close(fd, &rerrno);
    printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
  }
  
  block_pc_snapshot_all("writenfs.img");
  exit(0);
}
예제 #9
0
bool FatFsClass::initialize(void)
{
	/* setup sd card slot */
	if(!sd_raw_init()){
		return false;
	}

	/* open first partition */
	_partition = partition_open(sd_raw_read,
								sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
								sd_raw_write,
								sd_raw_write_interval,
#else
								0,
								0,
#endif
								0
								);

	if(!_partition){
		/* If the partition did not open, assume the storage device
		 * is a "superfloppy", i.e. has no MBR.
		 */
		_partition = partition_open(sd_raw_read,
									sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
									sd_raw_write,
									sd_raw_write_interval,
#else
									0,
									0,
#endif
									-1
									);
		if(!_partition){
			return false;
		}
	}

	/* open file system */
	_fs = fat_open(_partition);
	if(!_fs){
		return false;
	}

	/* open root directory */
	return changeDirectory("/");
}
예제 #10
0
static void execute_elf(void *arg) {
	int fd, size, i, j;
	void *entry;
	//extern void *end;
	void *elf_begin = ((void *)(&end)) + 4*1024;
	uint8_t *tmp = elf_begin;
	
	printf("Load file to RAM\n");
	fd = fat_open(path, O_RDONLY);
	size = fat_fsize(fd);
	
	for(j = 512; j < size; j += 512) {
		fat_read_sect(fd);
		for(i = 0; i < 512; i++) {
			*tmp++ = fat_buf[i];
		}
	}
	fat_read_sect(fd);
	for(i = 0; i < j - size; i++) {
		*tmp++ = fat_buf[i];
	}
	
	fat_close(fd);
	printf("File loaded\n");
	printf("Highest addr used is 0x%X\n", tmp);
	//input_poll();
	
	mmu040_init();
	terminal_clear();
	printf("MMU Init\n");
	if(!(entry = elf_load(elf_begin, do_debug))) {
		printf("Failed to load ELF\n");
		input_poll();
		return;
	}
	printf("ELF load successful, entry is 0x%X, press any key\n", entry);
	//input_poll();
	//printf("Here we have 0x%X\n", *((uint32_t *) entry));
	//input_poll();
	mmu_disable();
	if(do_debug) {
		char *argv[] = {"debug"};
		mmu_enable_and_jump(entry, 1, argv);
	} else {
		mmu_enable_and_jump(entry, 0, NULL);
	}
}
예제 #11
0
void load_hex_to_rom(const char *path) {
		void *entry;
		HexStat stat = {0, 0xFFFFFFFF};
		RomHeader header;
		int x, y;
		int fd;
		
		printf("Erasing ROM... ");
		
		rom_erase();
		while(rom_status() & 0x1);
		
		terminal_set_fg(TERMINAL_COLOR_LIGHT_GREEN);
		printf("done.\n");
		terminal_set_fg(TERMINAL_COLOR_LIGHT_GRAY);
		
		printf("Writing to ROM... ");
		terminal_get_pos(&x, &y);
		
		fd = fat_open(path, O_RDONLY);
		
		if(hexload(get_byte, fd, _write_rom_byte, &stat, &entry) < 0) {
			terminal_set_fg(TERMINAL_COLOR_RED);
			printf("Invalid hex file");
			terminal_set_fg(TERMINAL_COLOR_LIGHT_GRAY);
			
			fat_close(fd);
			return;
		}
		fat_close(fd);
		
		header.magic = 0xDEADBEEF;
		header.entry = (uint32_t) entry;
		header.size = stat.size;
		header.dest_addr = LLRAM_BASE | stat.offset;
		header.flash_offset = stat.offset;
		
		rom_write(ROM_SIZE - 512, (void *) &header, sizeof(header));
		
		terminal_set_pos(x, y);
		terminal_set_fg(TERMINAL_COLOR_LIGHT_GREEN);
		printf("done.\n");
		terminal_set_fg(TERMINAL_COLOR_LIGHT_GRAY);
		printf("Press any key...");
}
예제 #12
0
int main()
{
	int res;
	Volume *v;
	nls_init();
	res = fat_mount("../img/floppy.img", &v);
	printf("Mount: %i (%s)\n", res, strerror(-res));
	//for (res = 0; res < 100000; res++)
	//unlink_test(v, "\\grub\\menu.lst");
	//rmdir_test(v, "\\faccio un provolone");
	rename_test(v, "\\grub\\rentest", "\\puppo");
		//read_test(v, "\\grub\\menu.lst");
		//lfnfind_test(v, "\\grub", "*.*");
		//create_test(v, "\\faccio una prova.txt");
		//mkdir_test(v, "\\faccio un provolone");
		//dosfind_test(v, "\\autoexec.bat\\*.*");
	res = fat_unmount(v);
	printf("Unmount: %i (%s)\n", res, strerror(-res));
	#if 0
	//res = fat_open(v, "\\autoexec.bat", NULL, O_RDWR, 0, &c);
	res = fat_open(v, "\\faccio una prova.txt", NULL, O_RDWR | O_CREAT | O_EXCL, 0, &c);
	printf("Open: %i (%s)\n", res, strerror(-res));
	#if 1 /* write */
	res = fat_lseek(c, 0, SEEK_SET);
	printf("Seek: %i (%s)\n", res, strerror(-res));
	for (k = 0; k < sizeof(buf); k++) buf[k] = (k % 10) + '0';
	res = fat_write(c, buf, sizeof(buf));
	printf("Write: %i (%s)\n", res, strerror(-res));
	#elif 0 /* read */
	res = fat_read(c, buf, sizeof(buf));
	printf("Read: %i (%s)\n", res, strerror(-res));
	for (k = 0; k < res; k++) fputc(buf[k], stdout);
	#elif 0 /* truncate */
	res = fat_ftruncate(c, 65432);
	printf("Truncate: %i (%s)\n", res, strerror(-res));
	#endif
	res = fat_close(c);
	printf("Close: %i (%s)\n", res, strerror(-res));
	res = fat_unmount(v);
	printf("Unmount: %i (%s)\n", res, strerror(-res));
	#endif
	return 0;
}
예제 #13
0
파일: main.c 프로젝트: 4nh51rk/mailboxbomb
int try_sd_load(void)
{
	int err;

	err = sd_init();
	if (err) {
		printf("SD card not found (%d)\n", err);
		return err;
	}

	err = fat_init();
	if (err == 0)
		printf("SD card detected\n");
	else {
		printf("SD card not detected (%d)\n", err);
		return err;
	}

//	if (usbgecko_checkgecko())
//		printf("USBGecko serial interface detected\n");
//	else
//		printf("USBGecko serial interface not detected\n");

	printf("Opening boot.elf:\n");
	err = fat_open("boot.elf");

	if (err) {
		printf("boot.elf not found (%d)\n", err);
		return err;
	}

extern u32 fat_file_size;

	printf("reading %d bytes...\n", fat_file_size);
	err = fat_read(code_buffer, fat_file_size);
	if (err) {
		printf("Error %d reading file\n", err);
		return err;
	}

	printf("Done.\n");
	return 0;
}
예제 #14
0
파일: example.c 프로젝트: MikrySoft/openfat
int main(void)
{
	struct mmc_port spi2;
	struct block_mbr_partition part;
	struct fat_vol_handle vol;
	struct fat_file_handle file;

	stm32_setup();

	mmc_init(SPI2, GPIOA, GPIO3, &spi2);
	mbr_partition_init(&part, (struct block_device *)&spi2, 0);

	assert(fat_vol_init((struct block_device *)&part, &vol) == 0);
	printf("Fat type is FAT%d\n", vol.type);

	time_counter = 0;
	char dirname[20];
	char filename[20];
	char buffer[2000];
	for(int i = 0; i < 100; i++) {
		sprintf(dirname, "Dir%d", i);
		fat_mkdir(&vol, dirname);
		assert(fat_chdir(&vol, dirname) == 0);
		for(int j = 0; j < 100; j++) {
			sprintf(filename, "File%d", j);
			assert(fat_create(&vol, filename, O_WRONLY, &file) == 0);
			assert(fat_write(&file, buffer, sizeof(buffer)) == sizeof(buffer));
		}
		assert(fat_chdir(&vol, "..") == 0);
	}
	asm("bkpt");

	assert(fat_open(&vol, ".", 0, &file) == 0);
	print_tree(&vol, &file, 0);

	while (1) {
	}

	return 0;
}
예제 #15
0
파일: example.c 프로젝트: MikrySoft/openfat
void print_tree(struct fat_vol_handle *vol, struct fat_file_handle *dir, int nest)
{
	struct fat_file_handle subdir;
	struct dirent ent;

	while(!fat_readdir(dir, &ent)) {
		if((strcmp(ent.d_name, ".") == 0) || 
		   (strcmp(ent.d_name, "..") == 0))
			continue;

		for(int i = 0; i < nest; i++) printf("\t");
		printf("%s\n", ent.d_name);

		if(ent.fat_attr == FAT_ATTR_DIRECTORY) {
			fat_chdir(vol, ent.d_name);
			assert(fat_open(vol, ".", 0, &subdir) == 0);
			print_tree(vol, &subdir, nest + 1);
			fat_chdir(vol, "..");
		}
	}

}
예제 #16
0
파일: fattest.c 프로젝트: MikrySoft/openfat
void print_tree(struct fat_vol_handle *vol, struct fat_file_handle *dir, 
		const char *path)
{
	struct dirent ent;
	char tmppath[1024];
	struct fat_file_handle subdir;

	while(!fat_readdir(dir, &ent)) {
		if((strcmp(ent.d_name, ".") == 0) || 
		   (strcmp(ent.d_name, "..") == 0))
			continue;
		sprintf(tmppath, "%s/%s", path, ent.d_name);
		puts(tmppath);
		
		if(ent.fat_attr == FAT_ATTR_DIRECTORY) {
			fat_chdir(vol, ent.d_name);
			assert(fat_open(vol, ".", 0, &subdir) == 0);
			print_tree(vol, &subdir, tmppath);
			fat_chdir(vol, "..");
		}
	}

}
예제 #17
0
int _fat_open(struct vfs_file_s *file, struct mount_s *mount, const char *filename, int oflags, int perm)
{
	struct fat_context * fat = malloc(sizeof(struct fat_context));
	memset(fat, 0, sizeof(*fat));
	
	file->priv[0] = fat;
	struct bdev *bdev = mount->priv[0];

	if (fat_init(fat, bdev) < 0)
	{
		free(fat);
		return -1;
	}
	
	if (fat_open(fat, filename) < 0)
	{
		free(fat);
		return -1;
	}

	file->ops = &vfs_fat_ops;
	
	return 0;
}
예제 #18
0
파일: SDCard.cpp 프로젝트: CyrilLD/sjfw
bool openFilesys()
{
  /* open file system */
  fs = fat_open(partition);
  return fs != 0;
}
예제 #19
0
int main()
{
    /* we will just use ordinary idle mode */
    set_sleep_mode(SLEEP_MODE_IDLE);

    /* setup uart */
    uart_init();

    while(1)
    {


        /* setup sd card slot */
        if(!sd_raw_init())
        {
#if DEBUG
            uart_puts_p(PSTR("MMC/SD initialization failed\n"));
#endif
            continue;
        }

        /* open first partition */
        struct partition_struct* partition = partition_open(sd_raw_read,
                                                            sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
                                                            sd_raw_write,
                                                            sd_raw_write_interval,
#else
                                                            0,
                                                            0,
#endif
                                                            0
                                                           );

        if(!partition)
        {
            /* If the partition did not open, assume the storage device
             * is a "superfloppy", i.e. has no MBR.
             */
            partition = partition_open(sd_raw_read,
                                       sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
                                       sd_raw_write,
                                       sd_raw_write_interval,
#else
                                       0,
                                       0,
#endif
                                       -1
                                      );
            if(!partition)
            {
#if DEBUG
                uart_puts_p(PSTR("opening partition failed\n"));
#endif
                continue;
            }
        }

        /* open file system */
        struct fat_fs_struct* fs = fat_open(partition);
        if(!fs)
        {
#if DEBUG
            uart_puts_p(PSTR("opening filesystem failed\n"));
#endif
            continue;
        }

        /* open root directory */
        struct fat_dir_entry_struct directory;
        fat_get_dir_entry_of_path(fs, "/", &directory);

        struct fat_dir_struct* dd = fat_open_dir(fs, &directory);
        if(!dd)
        {
#if DEBUG
            uart_puts_p(PSTR("opening root directory failed\n"));
#endif
            continue;
        }

        /* print some card information as a boot message */
        print_disk_info(fs);

        /* provide a simple shell */
        char buffer[24];
        while(1)
        {
            /* print prompt */
            uart_putc('>');
            uart_putc(' ');

            /* read command */
            char* command = buffer;
            if(read_line(command, sizeof(buffer)) < 1)
                continue;

            /* execute command */
            if(strcmp_P(command, PSTR("init")) == 0)
            {
                break;
            }
            else if(strncmp_P(command, PSTR("cd "), 3) == 0)
            {
                command += 3;
                if(command[0] == '\0')
                    continue;

                /* change directory */
                struct fat_dir_entry_struct subdir_entry;
                if(find_file_in_dir(fs, dd, command, &subdir_entry))
                {
                    struct fat_dir_struct* dd_new = fat_open_dir(fs, &subdir_entry);
                    if(dd_new)
                    {
                        fat_close_dir(dd);
                        dd = dd_new;
                        continue;
                    }
                }

                uart_puts_p(PSTR("directory not found: "));
                uart_puts(command);
                uart_putc('\n');
            }
            else if(strcmp_P(command, PSTR("ls")) == 0)
            {
                /* print directory listing */
                struct fat_dir_entry_struct dir_entry;
                while(fat_read_dir(dd, &dir_entry))
                {
                    uint8_t spaces = sizeof(dir_entry.long_name) - strlen(dir_entry.long_name) + 4;

                    uart_puts(dir_entry.long_name);
                    uart_putc(dir_entry.attributes & FAT_ATTRIB_DIR ? '/' : ' ');
                    while(spaces--)
                        uart_putc(' ');
                    uart_putdw_dec(dir_entry.file_size);
                    uart_putc('\n');
                }
            }
            else if(strncmp_P(command, PSTR("cat "), 4) == 0)
            {
                command += 4;
                if(command[0] == '\0')
                    continue;

                /* search file in current directory and open it */
                struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
                if(!fd)
                {
                    uart_puts_p(PSTR("error opening "));
                    uart_puts(command);
                    uart_putc('\n');
                    continue;
                }

                /* print file contents */
                uint8_t buffer[8];
                uint32_t offset = 0;
                while(fat_read_file(fd, buffer, sizeof(buffer)) > 0)
                {
                    uart_putdw_hex(offset);
                    uart_putc(':');
                    for(uint8_t i = 0; i < 8; ++i)
                    {
                        uart_putc(' ');
                        uart_putc_hex(buffer[i]);
                    }
                    uart_putc('\n');
                    offset += 8;
                }

                fat_close_file(fd);
            }
            else if(strcmp_P(command, PSTR("disk")) == 0)
            {
                if(!print_disk_info(fs))
                    uart_puts_p(PSTR("error reading disk info\n"));
            }
#if FAT_WRITE_SUPPORT
            else if(strncmp_P(command, PSTR("rm "), 3) == 0)
            {
                command += 3;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct file_entry;
                if(find_file_in_dir(fs, dd, command, &file_entry))
                {
                    if(fat_delete_file(fs, &file_entry))
                        continue;
                }

                uart_puts_p(PSTR("error deleting file: "));
                uart_puts(command);
                uart_putc('\n');
            }
            else if(strncmp_P(command, PSTR("touch "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct file_entry;
                if(!fat_create_file(dd, command, &file_entry))
                {
                    uart_puts_p(PSTR("error creating file: "));
                    uart_puts(command);
                    uart_putc('\n');
                }
            }
            else if(strncmp_P(command, PSTR("write "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                char* offset_value = command;
                while(*offset_value != ' ' && *offset_value != '\0')
                    ++offset_value;

                if(*offset_value == ' ')
                    *offset_value++ = '\0';
                else
                    continue;

                /* search file in current directory and open it */
                struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
                if(!fd)
                {
                    uart_puts_p(PSTR("error opening "));
                    uart_puts(command);
                    uart_putc('\n');
                    continue;
                }

                int32_t offset = strtolong(offset_value);
                if(!fat_seek_file(fd, &offset, FAT_SEEK_SET))
                {
                    uart_puts_p(PSTR("error seeking on "));
                    uart_puts(command);
                    uart_putc('\n');

                    fat_close_file(fd);
                    continue;
                }

                /* read text from the shell and write it to the file */
                uint8_t data_len;
                while(1)
                {
                    /* give a different prompt */
                    uart_putc('<');
                    uart_putc(' ');

                    /* read one line of text */
                    data_len = read_line(buffer, sizeof(buffer));
                    if(!data_len)
                        break;

                    /* write text to file */
                    if(fat_write_file(fd, (uint8_t*) buffer, data_len) != data_len)
                    {
                        uart_puts_p(PSTR("error writing to file\n"));
                        break;
                    }
                }

                fat_close_file(fd);
            }
            else if(strncmp_P(command, PSTR("mkdir "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct dir_entry;
                if(!fat_create_dir(dd, command, &dir_entry))
                {
                    uart_puts_p(PSTR("error creating directory: "));
                    uart_puts(command);
                    uart_putc('\n');
                }
            }
#endif
#if SD_RAW_WRITE_BUFFERING
            else if(strcmp_P(command, PSTR("sync")) == 0)
            {
                if(!sd_raw_sync())
                    uart_puts_p(PSTR("error syncing disk\n"));
            }
#endif

            else if(strcmp_P(command, PSTR("sync")) == 0)
            {
                // vytvor adresar mereni_teploty

                // nekonecna smycka - pomoci RTCka kazdou minutu odmer teplotu
            }


            else
            {
                uart_puts_p(PSTR("unknown command: "));
                uart_puts(command);
                uart_putc('\n');
            }
        }

        /* close directory */
        fat_close_dir(dd);

        /* close file system */
        fat_close(fs);

        /* close partition */
        partition_close(partition);
    }

    return 0;
}
예제 #20
0
int main (){
	//s32 i, j;
	//s32 len, status;
	FATTIE * fp;
	u8 * str = (u8 *)"Test string to demonstrate that\nsdcard filesystem works properly\n";

	init_platform();

	while(*cd_ptr != 0);

	sd_trivial_delay(1000000);

	spi_dev_status |= SD_FS_CARD_DETECT;

	switch(init_fat_filesystem()) {
	case 0:
		xil_printf("microSD initialized successfully\n\r");
		break;

	default:
		xil_printf("Exiting\n\r");
		return -1;
	}

	fp = fat_open((u8 *)"TESTERIN.SGF");

	if(fp == NULL) {
		xil_printf("Couldn't open file\n\r");
		goto end;
	}

	// Pass in the sgf config structure into init_sgf_file() for writing the header of SGF
	init_sgf_file(fp);


	/* Read from memory */

	// Just for testing the function out
	Move one, two, three, four;
	one.stoneColor = BLACK_STONE;
	one.stoneX = 3;
	one.stoneY = 3;

	two.stoneColor = WHITE_STONE;
	two.stoneX = 15;
	two.stoneY = 15;

	three.stoneColor = BLACK_STONE;
	three.stoneX = 15;
	three.stoneY = 3;

	four.stoneColor = WHITE_STONE;
	four.stoneX = 3;
	four.stoneY = 15;

	// This is where you append the newly placed stone in the SGF file (filename)
	// Obviously, you can just declare one Move struct and reuse it using a while loop until stoneColor == 0 like below
	write_sgf_move(fp, one.stoneX, one.stoneY, one.stoneColor);
	write_sgf_move(fp, two.stoneX, two.stoneY, two.stoneColor);
	write_sgf_move(fp, three.stoneX, three.stoneY, three.stoneColor);
	write_sgf_move(fp, four.stoneX, four.stoneY, four.stoneColor);

	/*
	Move tmp;
	unsigned int offset = 0;

	tmp = *(some_memory_address + offset);

	while(tmp.stoneColor != NO_STONE) {
		write_sgf_move(filename, tmp.stoneX, tmp.stoneY, tmp.stoneColor);
		offset += 3;    // The structs are stacked perfectly into the memory, so add 3 bytes.
		tmp = *(some_memory_address + offset);
	}
	*/

	/* Write a simple ")" to close off the main branch in SGF */
	// You may want to read extra Move from the memory and check if the stoneColor == 0;
	end_sgf_file(fp);

	fat_close(fp);

	fp = fat_open((u8 *)"ABCDEFGH.TXT");

	fat_write(fp, str, strlen(str));

	fat_close(fp);

	end: sd_eject_card();


	return 0;
}
예제 #21
0
파일: main.c 프로젝트: Marvenlee/cheviot
void Main (void)
{
	void (*kernel_entry_point)(struct BootInfo *bi);
	void (*procman_entry_point)(void);
	size_t nbytes_read;
	size_t filesz;
	void *mod;
	void *addr;
	vm_addr heap_base, heap_ceiling;
	vm_addr user_stack_base, user_stack_ceiling;

    // Initialize bootloader
	
	dbg_init();
	BlinkLEDs(10);
	sd_card_init(&bdev);
	fat_init();
	init_mem();

	// Load kernel at 1MB mark
	
	if (elf_load ("BOOT/KERNEL", (void *)&kernel_entry_point) != 0)
		KPanic ("Cannot load kernel");
	
	kernel_phdr_cnt = phdr_cnt;
	bmemcpy (kernel_phdr_table, phdr_table, sizeof (Elf32_PHdr) *  MAX_PHDR);
	
	user_base = 0x00800000;
	heap_base    = segment_table[segment_cnt-1].base;
	heap_ceiling = segment_table[segment_cnt-1].ceiling;
		
	if (heap_ceiling > user_base)
		heap_ceiling = user_base;
	
	addr = SegmentCreate (heap_base, heap_ceiling - heap_base, SEG_TYPE_ALLOC, MAP_FIXED | PROT_READWRITE);

	if (addr == NULL)
		KPanic ("Could not allocate HEAP!");

	KLog ("heap_base = %#010x, heap_ceiling = %#010x", heap_base, heap_ceiling);

    
    // Load root process (the Executive at 8MB mark
		
	if (elf_load ("BOOT/FILESYS", (void *)&procman_entry_point) != 0)
		KPanic ("Cannot load filesystem manager");

	procman_phdr_cnt = phdr_cnt;
	bmemcpy (procman_phdr_table, phdr_table, sizeof (Elf32_PHdr) * MAX_PHDR);


    // Allocate memory for module table, read startup.txt
    // and load modules above 8MB
    
	module_table = SegmentCreate (user_base, sizeof (struct Module) * NMODULE, SEG_TYPE_ALLOC, PROT_READWRITE);
	KLog ("module_table = %#010x", module_table);

	if ((vm_addr)module_table < user_base)
		KPanic ("Bad module_table");
	
	if (fat_open ("BOOT/STARTUP.TXT") != 0)
		KPanic ("Cannot open STARTUP.TXT");
	
	module_cnt = 0;
	
	while (module_cnt < NMODULE)
	{
		if ((nbytes_read = fat_getline(module_table[module_cnt].name, 64)) == 0)
			break;
		
		if (module_table[module_cnt].name[0] == '\0' ||
			module_table[module_cnt].name[0] == '\n' ||
			module_table[module_cnt].name[0] == '\r' ||
			module_table[module_cnt].name[0] == ' ')
		{
			KLOG ("Skipping blank lines");
			continue;
		}
		
		if (fat_open (module_table[module_cnt].name) != 0)
			KPanic ("Cannot open module");
		
		filesz = fat_get_filesize();
		
		mod = SegmentCreate (user_base, filesz, SEG_TYPE_ALLOC, PROT_READWRITE);
		
		if (fat_read (mod, filesz) == filesz)
		{
			module_table[module_cnt].addr = mod;
			module_table[module_cnt].size = filesz;
			module_cnt++;
		}
	}
	
	
	// Allocate a stack for the Executive
	
	user_stack_base = SegmentCreate (user_base, 65536, SEG_TYPE_ALLOC, PROT_READWRITE);	
	user_stack_ceiling = user_stack_base + 65536;

    
    // Pass the bootinfo, segment_table and module_table to kernel.
    
	bootinfo.procman_entry_point = procman_entry_point;
	bootinfo.user_stack_base = user_stack_base;
	bootinfo.user_stack_ceiling = user_stack_ceiling;
	bootinfo.user_base = user_base;
	bootinfo.heap_base = heap_base;
	bootinfo.heap_ceiling = heap_ceiling;
	bootinfo.screen_width = screen_width;
	bootinfo.screen_height = screen_height;
	bootinfo.screen_buf = screen_buf;
	bootinfo.screen_pitch = screen_pitch;
	bootinfo.module_table = module_table;
	bootinfo.module_cnt = module_cnt;
	bootinfo.segment_table = segment_table;
	bootinfo.segment_cnt = segment_cnt;
		
	KLOG ("Calling KERNEL entry point %#010x", (uint32) kernel_entry_point);
	
	kernel_entry_point(&bootinfo);
	while (1);
}
예제 #22
0
파일: fatreq.c 프로젝트: LucidOne/Rovio
int fat_request(DWORD Function, void *Params)
{
  int Res;
  switch (Function)
  {
    case FD32_READ:
    {
      fd32_read_t *X = (fd32_read_t *) Params;
      tFile       *F;
      if (X->Size < sizeof(fd32_read_t)) return EINVAL;
      F = (tFile *) X->DeviceId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_read(F, X->Buffer, X->BufferBytes);
    }
    case FD32_WRITE:
    {
      #ifdef FATWRITE
      fd32_write_t *X = (fd32_write_t *) Params;
      tFile        *F;
      if (X->Size < sizeof(fd32_write_t)) return EINVAL;
      F = (tFile *) X->DeviceId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_write(F, X->Buffer, X->BufferBytes);
      #else
      return EROFS;
      #endif
    }
    case FD32_LSEEK:
    {
      fd32_lseek_t *X = (fd32_lseek_t *) Params;
      if (X->Size < sizeof(fd32_lseek_t)) return EINVAL;
      if (((tFile *) X->DeviceId)->FilSig != FAT_FILSIG) return EBADF;
      return fat_lseek((tFile *) X->DeviceId, &X->Offset, X->Origin);
    }
    case FD32_OPENFILE:
    {
      fd32_openfile_t *X = (fd32_openfile_t *) Params;
      tVolume         *V;
      if (X->Size < sizeof(fd32_openfile_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_open(V, X->FileName, X->Mode, X->Attr, X->AliasHint, (tFile **) &X->FileId);
    }
    case FD32_CLOSE:
    {
      fd32_close_t *X = (fd32_close_t *) Params;
      tFile        *F;
      if (X->Size < sizeof(fd32_close_t)) return EINVAL;
      F = (tFile *) X->DeviceId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_close(F);
    }
    case FD32_READDIR:
    {
      fd32_readdir_t *X = (fd32_readdir_t *) Params;
      tFile          *F;
      if (X->Size < sizeof(fd32_readdir_t)) return EINVAL;
      F = (tFile *) X->DirId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_readdir(F, (fd32_fs_lfnfind_t *) X->Entry);
    }
    case FD32_FFLUSH:
    {
      #ifdef FATWRITE
      fd32_fflush_t *X = (fd32_fflush_t *) Params;
      tFile         *F;
      if (X->Size < sizeof(fd32_fflush_t)) return EINVAL;
      F = (tFile *) X->DeviceId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_fflush(F);
      #else
      return EROFS;
      #endif
    }
    case FD32_OPEN:
    {
      fd32_open_t *X = (fd32_open_t *) Params;
      if (X->Size < sizeof(fd32_open_t)) return EINVAL;
      if (((tFile *) X->DeviceId)->FilSig != FAT_FILSIG) return EBADF;
      return ++((tFile *) X->DeviceId)->References;
    }
    case FD32_GETATTR:
    {
      fd32_getattr_t *X = (fd32_getattr_t *) Params;
      if (X->Size < sizeof(fd32_getattr_t)) return EINVAL;
      if (((tFile *) X->FileId)->FilSig != FAT_FILSIG) return EBADF;
      return fat_get_attr((tFile *) X->FileId, (fd32_fs_attr_t *) X->Attr);
    }
    case FD32_SETATTR:
    {
      #ifdef FATWRITE
      fd32_setattr_t *X = (fd32_setattr_t *) Params;
      tFile          *F;
      if (X->Size < sizeof(fd32_setattr_t)) return EINVAL;
      F = (tFile *) X->FileId;
      if (F->FilSig != FAT_FILSIG) return EBADF;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(F->V)) < 0) return Res;
      #endif
      return fat_set_attr(F, (fd32_fs_attr_t *) X->Attr);
      #else
      return EROFS;
      #endif
    }
    case FD32_REOPENDIR:
    {
      fd32_reopendir_t *X = (fd32_reopendir_t *) Params;
      tVolume          *V;
      if (X->Size < sizeof(fd32_reopendir_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_reopendir(V, (tFindRes *) X->DtaReserved, (tFile **) &X->DirId);
    }
    case FD32_UNLINK:
    {
      #ifdef FATWRITE
      fd32_unlink_t *X = (fd32_unlink_t *) Params;
      tVolume       *V;
      if (X->Size < sizeof(fd32_unlink_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_unlink(V, X->FileName, X->Flags);
      #else
      return EROFS;
      #endif
    }
    case FD32_RENAME:
    {
      #ifdef FATWRITE
      fd32_rename_t *X = (fd32_rename_t *) Params;
      tVolume       *V;
      if (X->Size < sizeof(fd32_rename_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_rename(V, X->OldName, X->NewName);
      #else
      return EROFS;
      #endif
    }
    case FD32_MKDIR:
    {
      #ifdef FATWRITE
      fd32_mkdir_t *X = (fd32_mkdir_t *) Params;
      tVolume      *V;
      if (X->Size < sizeof(fd32_mkdir_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_mkdir(V, X->DirName);
      #else
      return FD32_EROFS;
      #endif
    }
    case FD32_RMDIR:
    {
      #ifdef FATWRITE
      fd32_rmdir_t *X = (fd32_rmdir_t *) Params;
      tVolume      *V;
      if (X->Size < sizeof(fd32_rmdir_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_rmdir(V, X->DirName);
      #else
      return FD32_EROFS;
      #endif
    }
    case FD32_MOUNT:
    {
      fd32_mount_t *X = (fd32_mount_t *) Params;
      if (X->Size < sizeof(fd32_mount_t)) return EINVAL;
      return fat_mount(X->hDev, (tVolume **) &X->FsDev);
    }
    case FD32_UNMOUNT:
    {
      fd32_unmount_t *X = (fd32_unmount_t *) Params;
      tVolume        *V;
      if (X->Size < sizeof(fd32_unmount_t)) return EINVAL;
      V = (tVolume *) X->DeviceId;
      if (V->VolSig != FAT_VOLSIG) return ENODEV;
      #ifdef FATREMOVABLE
      if ((Res = fat_mediachange(V)) < 0) return Res;
      #endif
      return fat_unmount(V);
    }
    case FD32_PARTCHECK:
    {
      fd32_partcheck_t *X = (fd32_partcheck_t *) Params;
      if (X->Size < sizeof(fd32_partcheck_t)) return EINVAL;
      return fat_partcheck(X->PartId);
    }
    case FD32_GETFSINFO:
    {
      fd32_getfsinfo_t *X = (fd32_getfsinfo_t *) Params;
      if (X->Size < sizeof(fd32_getfsinfo_t)) return EINVAL;
      return fat_get_fsinfo((fd32_fs_info_t *) X->FSInfo);
    }
    case FD32_GETFSFREE:
      return fat_get_fsfree((fd32_getfsfree_t *) Params);
  }
  return EINVAL;
}
예제 #23
0
void select_file_action(void *arg) {
	int selected = *((int *) arg);
	int i, j, k, fd, size;
	volatile uint8_t *tmp;
	
	switch(selected) {
		case 0:
			fd = fat_open(path, O_RDONLY);
			size = fat_fsize(fd);
	
			for(j = 0; j < size; j += 512) {
				terminal_clear();
				fat_read_sect(fd);
				for(i = 0; i < 512; i++) {
					if(fat_buf[i] < 32 || fat_buf[i] > 126)
						printf("?");
					else
						printf("%c", fat_buf[i]);
					
				}
				input_poll();
			}
			fat_close(fd);
			break;
		case 1:
			fd = fat_open(path, O_RDONLY);
			size = fat_fsize(fd);
	
			for(j = 0; j < size; j += 512) {
				terminal_clear();
				printf("\nSector %u\n", j >> 9);
				fat_read_sect(fd);
				for(i = 0; i < 256; i+=16) {
					tmp =((uint8_t *) fat_buf) + i;
					printf("%04x\t%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\t\t", 
						j + i,
						tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], 
						tmp[8], tmp[9], tmp[10], tmp[11], tmp[12], tmp[13], tmp[14], tmp[15]
					);
					for(k = 0; k < 16; k++) {
						if(tmp[k] < 32 || tmp[k] > 126)
							printf(".");
						else
							printf("%c", tmp[k]);
					}
					printf("\n");
					
				}
				input_poll();
				terminal_clear();
				printf("\nSector %u\n", j >> 9);
				for(i = 256; i < 512; i+=16) {
					tmp =((uint8_t *) fat_buf) + i;
					printf("%04x\t%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\t\t", 
						j + i,
						tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], 
						tmp[8], tmp[9], tmp[10], tmp[11], tmp[12], tmp[13], tmp[14], tmp[15]
					);
					for(k = 0; k < 16; k++) {
						if(tmp[k] < 32 || tmp[k] > 126)
							printf(".");
						else
							printf("%c", tmp[k]);
					}
					printf("\n");
					
				}
				input_poll();
			}
			fat_close(fd);

			break;
		case 2:
			{
				void *addr, *entry;
				fd = fat_open(path, O_RDONLY);
				if(hexload(get_byte, fd, hexload_write_byte, NULL, &entry) < 0) {
					printf("Invalid hex file");
					fat_close(fd);
					input_poll();
					break;
				}
				fat_close(fd);
				fd = fat_open(path, O_RDONLY);
				
				if(hexload(get_byte, fd, hexload_verify_byte, NULL, &addr) < 0) {
					printf("Hexload validate error at 0x%X\n", addr);
					fat_close(fd);
					input_poll();
					break;
				}
				
				__asm__ __volatile__ ("cpusha %dc\n");
				goto *addr;
				
				fat_close(fd);
				input_poll();
			}
			break;
		case 4:
			fd = fat_open(path, O_RDONLY);
			size = fat_fsize(fd);
			tmp = MEM_VGA_RAM;
			
			for(j = 512; j < size; j += 512) {
				fat_read_sect(fd);
				for(i = 0; i < 512; i++) {
					*tmp++ = fat_buf[i];
				}
			}
			fat_read_sect(fd);
			for(i = 0; i < j - size; i++) {
				*tmp++ = fat_buf[i];
			}
			
			fat_close(fd);
			input_poll();
			terminal_clear();
			break;
		case 5:
			load_hex_to_rom(path);
			input_poll();
			
			break;
		
		case 6:
			terminal_clear();
			printf("Loading WAV to RAM\n");
			
			fd = fat_open(path, O_RDONLY);
			size = fat_fsize(fd);
			tmp = (volatile uint8_t *) SDRAM_BASE;
			
			printf("0/%u kB", size >> 10);
		
			for(j = 0; j < size; j += 512) {
				fat_read_sect(fd);
				for(i = 0; i < 512; i++) {
					*tmp++ = fat_buf[i];
				}
				printf("\r%u/%u kB", j >> 10, size >> 10);
			}
			fat_close(fd);
			printf("\n");
			wav_play((uint8_t *) SDRAM_BASE);
			printf("Press any key\n");
			input_poll();
			terminal_clear();
	}
}
예제 #24
0
/**************************************************************
 * Error codes to test for on fat_open();
 *
 * [EACCES] - write on a read only file
 * [EISDIR] - write access to a directory
 * [ENAMETOOLONG] - file path is too long
 * [ENFILE] - too many files are open
 * [ENOENT] - no file with that name or empty filename
 * [ENOSPC] - write to a full volume
 * [ENOTDIR] - part of subpath is not a directory but a file
 * [EROFS] - write access to file on read-only filesystem
 * [EINVAL] - mode is not valid
 **************************************************************/
int test_open(int p) {
    int i;
    int v;
    const char *desc[] = {"Test O_WRONLY on a read only file.",
                          "Test O_RDWR on a read only file.",
                          "Test O_RDONLY on a read only file.",
                          "Test O_WRONLY on a directory.",
                          "Test O_RDWR on a directory.",
                          "Test O_RDONLY on a directory.",
                          "Test O_WRONLY on a missing file.",
                          "Test O_RDWR on a missing file.",
                          "Test O_RDONLY on a missing file.",
                          "Test O_WRONLY on a path with file as non terminal member.",
                          "Test O_RDWR on a path with file as non terminal member.",
                          "Test O_RDONLY on a path with a file as non terminal member.",
                         };
    const char *filename[] = {"/ROFILE.TXT",
                              "/ROFILE.TXT",
                              "/ROFILE.TXT",
                              "/DIR1",
                              "/DIR1",
                              "/DIR1",
                              "/MISSING.TXT",
                              "/MISSING.TXT",
                              "/MISSING.TXT",
                              "/ROFILE.TXT/NONE.TXT",
                              "/ROFILE.TXT/NONE.TXT",
                              "/ROFILE.TXT/NONE.TXT",
                             };
    const int flags[] = {O_WRONLY,
                         O_RDWR,
                         O_RDONLY,
                         O_WRONLY,
                         O_RDWR,
                         O_RDONLY,
                         O_WRONLY,
                         O_RDWR,
                         O_RDONLY,
                         O_WRONLY,
                         O_RDWR,
                         O_RDONLY,
                        };
    const int result[] = {EACCES,
                          EACCES,
                          0,
                          EISDIR,
                          EISDIR,
                          0,
                          ENOENT,
                          ENOENT,
                          ENOENT,
                          ENOTDIR,
                          ENOTDIR,
                          ENOTDIR,
                         };
    const int cases = 12;

    int rerrno;

    for(i=0; i<cases; i++) {
        printf("[%4d] Testing %s", p++, desc[i]);
        v = fat_open(filename[i], flags[i], 0, &rerrno);
        if(rerrno == result[i]) {
            printf("  [ ok ]\n");
        } else {
            printf("  [fail]\n  expected (%d) %s\n  got (%d) %s\n", result[i], strerror(result[i]), rerrno, strerror(-rerrno));
        }
        if(v > -1) {
            fat_close(v, &rerrno);
            if(rerrno != 0) {
                printf("fat_close returned %d (%s)\n", rerrno, strerror(rerrno));
            }

        }
    }
    return p;
}
예제 #25
0
int main(int argc, char *argv[]) {
    int p = 0;
    int rerrno = 0;
    int result;
    int parts;
    uint8_t temp[512];
    struct partition *part_list;

    if(argc < 2) {
        printf("Please specify a disk image to work on.\n");
        exit(-2);
    }

    block_pc_set_image_name(argv[1]);
//   int v;
    printf("Running FAT tests...\n\n");
    printf("[%4d] start block device emulation...", p++);
    printf("   %d\n", block_init());

    printf("[%4d] mount filesystem, FAT32", p++);

    result = fat_mount(0, block_get_volume_size(), PART_TYPE_FAT32);

    printf("   %d\n", result);

    if(result != 0) {
        // mounting failed.
        // try listing the partitions
        block_read(0, temp);
        parts = read_partition_table(temp, block_get_volume_size(), &part_list);

        printf("Found %d valid partitions.\n", parts);

        if(parts > 0) {
            result = fat_mount(part_list[0].start, part_list[0].length, part_list[0].type);
        }
        if(result != 0) {
            printf("Mount failed\n");
            exit(-2);
        }

    }

    printf("Part type = %02X\n", fatfs.type);
    //   p = test_open(p);

    int fd;
    int i;
    char block_o_data[1024];
    uint32_t temp_uint = 0xDEADBEEF;
    memset(block_o_data, 0x42, 1024);
//   printf("Open\n");
//   fd = fat_open("/newfile.txt", O_WRONLY | O_CREAT, 0777, &rerrno);
//   printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno));
//   if(fd > -1) {
//     printf("Write\n");
//     fat_write(fd, "Hello World\n", 12, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//     printf("Close\n");
//     fat_close(fd, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//   }

//   printf("Open\n");
//   fd = fat_open("/newfile.png", O_WRONLY | O_CREAT, 0777, &rerrno);
//   printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno));
//   if(fd > -1) {
//     fp = fopen("gowrong_draft1.png", "rb");
//     fseek(fp, 0, SEEK_END);
//     len = ftell(fp);
//     d = malloc(len);
//     fseek(fp, 0, SEEK_SET);
//     fread(d, 1, len, fp);
//     fclose(fp);
//     printf("Write PNG\n");
//     fat_write(fd, d, len, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//     printf("Close\n");
//     fat_close(fd, &rerrno);
//     printf("errno=%d (%s)\n", rerrno, strerror(rerrno));
//   }

    printf("errno = (%d) %s\n", rerrno, strerror(rerrno));
    result = fat_mkdir("/foo", 0777, &rerrno);
    printf("mkdir /foo: %d (%d) %s\n", result, rerrno, strerror(rerrno));

    result = fat_mkdir("/foo/bar", 0777, &rerrno);
    printf("mkdir /foo/bar: %d (%d) %s\n", result, rerrno, strerror(rerrno));

    result = fat_mkdir("/web", 0777, &rerrno);
    printf("mkdir /web: %d (%d) %s\n", result, rerrno, strerror(rerrno));

    if((fd = fat_open("/foo/bar/file.html", O_WRONLY | O_CREAT, 0777, &rerrno)) == -1) {
        printf("Couldn't open file (%d) %s\n", rerrno, strerror(rerrno));
        exit(-1);
    }

    for(i=0; i<20; i++) {
//     printf("fd.cluster = %d\n", file_num[fd].full_first_cluster);
        if(fat_write(fd, block_o_data, 1024, &rerrno) == -1) {
            printf("Error writing to new file (%d) %s\n", rerrno, strerror(rerrno));
        }
    }

    if(fat_close(fd, &rerrno)) {
        printf("Error closing file (%d) %s\n", rerrno, strerror(rerrno));
    }

    printf("Open directory\n");
    if((fd = fat_open("/foo/bar", O_RDONLY, 0777, &rerrno)) < 0) {
        printf("Failed to open directory (%d) %s\n", rerrno, strerror(rerrno));
        exit(-1);
    }
    struct dirent de;

    while(!fat_get_next_dirent(fd, &de, &rerrno)) {
        printf("%s\n", de.d_name);
    }
    printf("Directory read failed. (%d) %s\n", rerrno, strerror(rerrno));

    if(fat_close(fd, &rerrno)) {
        printf("Error closing directory, (%d) %s\n", rerrno, strerror(rerrno));
    }

    if(fat_open("/web/version.txt", O_RDONLY, 0777, &rerrno) < 0) {
        printf("Error opening missing file (%d) %s\n", rerrno, strerror(rerrno));
    } else {
        printf("success! opened non existent file for reading.\n");
    }

    printf("Trying to write a big file.\n");

    if((fd = fat_open("big_file.bin", O_WRONLY | O_CREAT, 0777, &rerrno))) {
        printf("Error opening a file for writing.\n");
    }

    for(i=0; i<1024 * 1024 * 10; i++) {
        if((i & 0xfff) == 0)
            printf("Written %d bytes\n", i * 4);
        fat_write(fd, &temp_uint, 4, &rerrno);
    }
    fat_close(fd, &rerrno);

//   result = fat_rmdir("/foo/bar", &rerrno);
//   printf("rmdir /foo/bar: %d (%d) %s\n", result, rerrno, strerror(rerrno));
//
//   result = fat_rmdir("/foo", &rerrno);
//   printf("rmdir /foo: %d (%d) %s\n", result, rerrno, strerror(rerrno));

    block_pc_snapshot_all("writenfs.img");
    exit(0);
}