forked from caldwell/gdisk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.c
83 lines (75 loc) · 2.41 KB
/
device.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) 2008 David Caldwell, All Rights Reserved.
#define _GNU_SOURCE
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include "device.h"
void *alloc_sectors(struct device *dev, unsigned long sectors)
{
char *data = calloc(sectors, dev->sector_size);
if (!data)
err(0, "Couldn't allocate memory for %ld sectors (%ld bytes)", sectors, dev->sector_size * sectors);
return data;
}
void *get_sectors(struct device *dev, unsigned long long sector_num, unsigned long sectors)
{
void *data = alloc_sectors(dev, sectors);
if (!device_read(dev, data, sector_num, sectors))
err(errno, "Couldn't read sectors %ld through %ld", sector_num, sector_num+sectors);
return data;
}
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include "xmem.h"
static struct device *open_file_device(char *name)
{
unsigned long long sector_size=512, sector_count=0;
char *meta = name;
char *filename = strsep(&meta, ",");
char *sector_size_str = meta;
if (sector_size_str) sector_size = strtoull(sector_size_str, NULL, 0);
int fd = open(filename, O_RDWR);
if (fd < 0)
err(errno, "Error opening %s", filename);
if (!sector_count) {
struct stat st;
if (fstat(fd, &st) == -1)
err(errno, "can't find file size");
sector_count = st.st_size/sector_size;
}
struct device dev = {
.fd = fd,
.name = xstrdup(filename),
.sector_size = sector_size,
.sector_count = sector_count,
};
return xmemdup(&dev, sizeof(dev));
}
struct device *open_device(char *name)
{
struct device *dev = open_disk_device(name);
if (!dev || dev->sector_size == 0 || dev->sector_count == 0) {
close_device(dev);
dev = open_file_device(name);
}
return dev;
}
void close_device(struct device *dev)
{
if (!dev) return;
close(dev->fd);
free(dev->name);
free(dev);
}
#include <stdio.h>
bool device_read(struct device *dev, void *buffer, unsigned long long sector, unsigned long sectors)
{
return pread(dev->fd, buffer, dev->sector_size * sectors, dev->sector_size * sector) == dev->sector_size * sectors;
}
bool device_write(struct device *dev, void *buffer, unsigned long long sector, unsigned long sectors)
{
return pwrite(dev->fd, buffer, dev->sector_size * sectors, dev->sector_size * sector) == dev->sector_size * sectors;
}