summaryrefslogtreecommitdiff
path: root/src/coff2bin.cpp
blob: 6438d364b61cc8ffd4e86198f0582ac716562297 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/* SPDX-License-Identifier: Unlicense
 */

#include "coff_image.h"
#include "data_buffer.h"

#define OPTPARSE_IMPLEMENTATION
#define OPTPARSE_API static
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include "optparse/optparse.h"
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>

static int Coff2Bin(FILE *input_stream, FILE *output_stream)
{
    auto input = DataBuffer::FromStream(input_stream);
    const size_t input_size = input.occupied_size;
    if (input_size == 0) {
        fprintf(stderr, "DataBuffer::FromStream(input, input_stream): "
                "Error: No data has been read\n");
        return EXIT_FAILURE;
    }
    const COFF::Image coff(static_cast<DataBuffer&&>(input));
    if (!coff.IsValid()) {
        fprintf(stderr, "Error: COFF image is not valid: %s\n", coff.Error());
        return EXIT_FAILURE;
    }
    const auto &file_header = coff.FileHeader();
    if (file_header.nsections == 0) {
        fprintf(stderr, "Error: COFF image does not contain sections\n");
        return EXIT_FAILURE;
    }
    for (size_t i = 0; i < file_header.nsections; i++) {
        const auto section = coff.GetSectionHeader(i);
        const auto type = static_cast<COFF::SectionType>(section.flags & 0x8ff);
        if (COFF::SectionType::Text == type) {
            const auto data = coff.GetSectionDataView(section);
            const size_t ret = fwrite(
                    data.buffer, data.size, 1, output_stream);
            (void) ret;
            assert(ret == 1);
            break;
        }
    }
    return EXIT_SUCCESS;
}

static void PrintUsage(FILE *s, const char *argv0)
{
    // Please, keep all lines in 80 columns range when printed.
    fprintf(s,
    "Usage: %s [options] <input-file-name>\n"
    "Options:\n"
    "  -h, --help            Show this message.\n"
    "  -o, --output FILE     Where to write binary data to (stdout if not set).\n"
    "  <input_file_name>     COFF file with the machine code to extract\n"
    "                        ('-' means stdin).\n"
    , argv0);
}

int main(int, char* argv[])
{
    struct optparse_long longopts[] = {
        {"help", 'h', OPTPARSE_NONE},
        {"output", 'o', OPTPARSE_OPTIONAL},
        {},
    };
    const char *input_file_name = nullptr;
    const char *output_file_name = nullptr;
    struct optparse options;
    optparse_init(&options, argv);
    // Parse opts
    int option;
    while ((option = optparse_long(&options, longopts, NULL)) != -1) {
        switch (option) {
        case 'h':
            PrintUsage(stdout, argv[0]);
            return EXIT_SUCCESS;
            break;
        case 'o':
            output_file_name = options.optarg;
            break;
        case '?':
            fprintf(stderr, "main: optparse_long: Error: \"%s\"\n", options.errmsg);
            return EXIT_FAILURE;
        }
    }
    // Parse input file name
    char *arg;
    while ((arg = optparse_arg(&options))) {
        if (input_file_name == nullptr) {
            input_file_name = arg;
        } else {
            fprintf(stderr, "error: too many free arguments provided\n");
            return EXIT_FAILURE;
        }
    }
    // Open the files
    FILE *input_stream = nullptr;
    FILE *output_stream = stdout;
    if (input_file_name) {
        if (0 == strcmp(input_file_name, "-")) {
            input_stream = stdin;
        } else {
            input_stream = fopen(input_file_name, "r");
        }
        if (input_stream == nullptr) {
            const int err = errno;
            fprintf(stderr,
                    "main: fopen(\"%s\", \"r\"): Error (%d): \"%s\"\n",
                    input_file_name, err, strerror(err));
            return EXIT_FAILURE;
        }
    } else {
        fprintf(stderr, "main: Error: no input file name specified, see usage below.\n");
        PrintUsage(stderr, argv[0]);
        return EXIT_FAILURE;
    }
    if (output_file_name) {
        output_stream = fopen(output_file_name, "w");
        if (output_stream == nullptr) {
            const int err = errno;
            fprintf(stderr,
                    "main: fopen(\"%s\", \"w\"): Error (%d): \"%s\"\n",
                    output_file_name, err, strerror(err));
            fclose(input_stream);
            return EXIT_FAILURE;
        }
    }
    // Run the program
    const int ret = Coff2Bin(input_stream, output_stream);
    fclose(output_stream);
    fclose(input_stream);
    return ret;
}