blob: 443efcd957f800d77bef905f149ed5113d48dcdb [file] [log] [blame]
Thomas Heijligend1e04572023-11-27 14:28:55 +00001
2#include <stdio.h>
3
Thomas Heijligen62268ee2023-11-27 15:10:41 +00004#include "blockdev.h"
Thomas Heijligend1e04572023-11-27 14:28:55 +00005
Thomas Heijligen62268ee2023-11-27 15:10:41 +00006FILE* block_device = NULL;
Thomas Heijligend1e04572023-11-27 14:28:55 +00007size_t device_size = 0;
8
9
10int devopen(const char* name, int* reopen)
11{
12 block_device = fopen(name, "rwb");
13 if (!block_device) {
14 return 0;
15 }
Thomas Heijligen62268ee2023-11-27 15:10:41 +000016 fseek(block_device, 0, SEEK_END);
17 device_size = ftell(block_device);
Thomas Heijligend1e04572023-11-27 14:28:55 +000018 return 1;
19}
20
21
22void devclose(void)
23{
Thomas Heijligen62268ee2023-11-27 15:10:41 +000024 if (block_device) {
Thomas Heijligend1e04572023-11-27 14:28:55 +000025 fclose(block_device);
Thomas Heijligen62268ee2023-11-27 15:10:41 +000026 }
Thomas Heijligend1e04572023-11-27 14:28:55 +000027 block_device = NULL;
28 device_size = 0;
29}
30
31int devread(unsigned long sector, unsigned long byte_offset, unsigned long byte_len, void *buf)
32{
33 if (!block_device) {
Thomas Heijligen62268ee2023-11-27 15:10:41 +000034 fprintf(stderr, "devread: Device not open.\n");
Thomas Heijligend1e04572023-11-27 14:28:55 +000035 return 0;
36 }
37
38 const unsigned long offset = sector * 512 + byte_offset;
Thomas Heijligen62268ee2023-11-27 15:10:41 +000039 if (offset + byte_len > device_size) {
40 fprintf(stderr, "devread: Attempt to read beyond device.\n");
Thomas Heijligend1e04572023-11-27 14:28:55 +000041 return 0;
42 }
43
Thomas Heijligen62268ee2023-11-27 15:10:41 +000044 if (fseek(block_device, sector * 512 + byte_offset, SEEK_SET) != 0) {
45 fprintf(stderr, "devread: Failed to set offset on device.\n");
46 return 0;
47 }
Thomas Heijligend1e04572023-11-27 14:28:55 +000048 if (fread(buf, byte_len, 1, block_device) != byte_len) {
Thomas Heijligen62268ee2023-11-27 15:10:41 +000049 fprintf(stderr, "devread: Failed to read from device.\n");
Thomas Heijligend1e04572023-11-27 14:28:55 +000050 return 0;
51 }
52 return 1;
53}
54
55
56
57//void dev_set_partition(unsigned long start, unsigned long size);
58//void dev_get_partition(unsigned long *start, unsigned long *size);
59
60//int file_open(const char *filename);
61//int file_read(void *buf, unsigned long len);
62//unsigned long file_seek(unsigned long offset);
63//unsigned long file_size(void);
64//void file_set_size(unsigned long size);
65//void file_close(void);