summaryrefslogtreecommitdiffstats
path: root/utils/ypr0tools/extract_section.c
blob: 8ad12bc7df12633972083ec803b6b3c2a13d3617 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2011 Thomas Martitz
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

/* A simple replacement program for (
 * dd if=$file1 of=$file2 bs=1 skip=$offset count=$size
 *
 * Written because byte-size operations with dd are unbearably slow.
 */

void usage(void)
{
    fprintf(stderr, "Usage: extract_section <romfile> <outfile> <offset> <byte count>\n");
    exit(1);
}

void die(const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    exit(1);
}

int main(int argc, const char* argv[])
{
    if (argc != 5)
        usage();

    int ifd, ofd;
    ssize_t size = atol(argv[4]);
    long skip = atol(argv[3]);

    if (!size)
        die("invalid byte count\n");

    ifd = open(argv[1], O_RDONLY);
    if (ifd < 0)
        die("Could not open %s for reading!\n", argv[1]);

    ofd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (ofd < 0)
        die("Could not create %s\n", argv[2]);

    void *buf = malloc(size);
    if (!buf) die("OOM\n");

    lseek(ifd, skip, SEEK_SET);
    lseek(ofd, 0, SEEK_SET);
    if (read(ifd, buf, size) != size)
        die("Read failed\n");
    if (write(ofd, buf, size) != size)
        die("write failed\n");

    close(ifd);
    close(ofd);

    exit(EXIT_SUCCESS);
}