summaryrefslogtreecommitdiff
path: root/Userland/Utilities/blockdev.cpp
blob: ff2f9d207ad131580a0a6963b938b17d3c2985b3 (plain)
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
/*
 * Copyright (c) 2021, David Isaksson <davidisaksson93@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/ArgsParser.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>

static void fetch_ioctl(int fd, int request)
{
    size_t value;
    if (ioctl(fd, request, &value) < 0) {
        perror("ioctl");
        exit(1);
    }
    outln("{}", value);
}

int main(int argc, char** argv)
{
    if (unveil("/dev", "r") < 0) {
        perror("unveil");
        return 1;
    }

    if (unveil(nullptr, nullptr) < 0) {
        perror("unveil");
        return 1;
    }

    if (pledge("stdio rpath", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    const char* device = nullptr;

    bool flag_get_disk_size = false;
    bool flag_get_block_size = false;

    Core::ArgsParser args_parser;
    args_parser.set_general_help("Call block device ioctls");
    args_parser.add_option(flag_get_disk_size, "Get size in bytes", "size", 's');
    args_parser.add_option(flag_get_block_size, "Get block size in bytes", "block-size", 'b');
    args_parser.add_positional_argument(device, "Device to query", "device");
    args_parser.parse(argc, argv);

    int fd = open(device, O_RDONLY);
    if (fd < 0) {
        perror("open");
        return 1;
    }

    if (flag_get_disk_size) {
        fetch_ioctl(fd, STORAGE_DEVICE_GET_SIZE);
    }
    if (flag_get_block_size) {
        fetch_ioctl(fd, STORAGE_DEVICE_GET_BLOCK_SIZE);
    }

    return 0;
}