File: main.c

package info (click to toggle)
node-crc 4.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,344 kB
  • sloc: python: 3,073; xml: 632; javascript: 327; sh: 299; ansic: 227; makefile: 24
file content (283 lines) | stat: -rw-r--r-- 8,463 bytes parent folder | download | duplicates (3)
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//  Copyright (c) 2006-2013  Thomas Pircher  <tehpeh@gmx.net>
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

#include "crc.h"
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>

static bool atob(const char *str);
static crc_t xtoi(const char *str);
static int get_config(int argc, char *argv[], crc_cfg_t *cfg);
#if CRC_ALGO_BIT_BY_BIT
static crc_t crc_verify(const crc_cfg_t *cfg, crc_t crc_pre_final, crc_t crc);
static crc_t crc_reflect(crc_t data, size_t data_len);
#endif



static bool verbose = false;
static unsigned char str[256] = "123456789";

bool atob(const char *str)
{
    if (!str) {
        return 0;
    }
    if (isdigit(str[0])) {
        return (bool)atoi(str);
    }
    if (tolower(str[0]) == 't') {
        return true;
    }
    return false;
}

crc_t xtoi(const char *str)
{
    crc_t ret = 0;

    if (!str) {
        return 0;
    }
    if (str[0] == '0' && tolower(str[1]) == 'x') {
        str += 2;
        while (*str) {
            if (isdigit(*str))
                ret = 16 * ret + *str - '0';
            else if (isxdigit(*str))
                ret = 16 * ret + tolower(*str) - 'a' + 10;
            else
                return ret;
            str++;
        }
    } else if (isdigit(*str)) {
        while (*str) {
            if (isdigit(*str))
                ret = 10 * ret + *str - '0';
            else
                return ret;
            str++;
        }
    }
    return ret;
}


int get_config(int argc, char *argv[], crc_cfg_t *cfg)
{
    int c;
    int option_index;
    static struct option long_options[] = {
        {"width",           1, 0, 'w'},
        {"poly",            1, 0, 'p'},
        {"reflect-in",      1, 0, 'n'},
        {"xor-in",          1, 0, 'i'},
        {"reflect-out",     1, 0, 'u'},
        {"xor-out",         1, 0, 'o'},
        {"verbose",         0, 0, 'v'},
        {"check-string",    1, 0, 's'},
        {"table-idx-with",  1, 0, 't'},
        {0, 0, 0, 0}
    };

    while (1) {
        option_index = 0;

        c = getopt_long(argc, argv, "w:p:ni:uo:v", long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
            case 0:
                printf("option %s", long_options[option_index].name);
                if (optarg)
                    printf(" with arg %s", optarg);
                printf ("\n");
            case 'w':
                cfg->width = atoi(optarg);
                break;
            case 'p':
                cfg->poly = xtoi(optarg);
                break;
            case 'n':
                cfg->reflect_in = atob(optarg);
                break;
            case 'i':
                cfg->xor_in = xtoi(optarg);
                break;
            case 'u':
                cfg->reflect_out = atob(optarg);
                break;
            case 'o':
                cfg->xor_out = xtoi(optarg);
                break;
            case 's':
                memcpy(str, optarg, strlen(optarg) < sizeof(str) ? strlen(optarg) + 1 : sizeof(str));
                str[sizeof(str) - 1] = '\0';
                break;
            case 'v':
                verbose = true;
                break;
            case 't':
                // ignore --table_idx_width option
                break;
            case '?':
                return -1;
            case ':':
                fprintf(stderr, "missing argument to option %c\n", c);
                return -1;
            default:
                fprintf(stderr, "unhandled option %c\n", c);
                return -1;
        }
    }
    cfg->msb_mask = (crc_t)1u << (cfg->width - 1);
    cfg->crc_mask = (cfg->msb_mask - 1) | cfg->msb_mask;
    cfg->crc_shift = cfg->width < 8 ? 8 - cfg->width : 0;

    cfg->poly &= cfg->crc_mask;
    cfg->xor_in &= cfg->crc_mask;
    cfg->xor_out &= cfg->crc_mask;
    return 0;
}


#if CRC_ALGO_BIT_BY_BIT
crc_t crc_verify(const crc_cfg_t *cfg, crc_t crc_pre_final, crc_t crc)
{
    crc_t result;
    unsigned char data;
    unsigned int i;

    // don't verify if the width is not a multiple of 8
    if (cfg->width % 8) {
        return 0;
    }
    if (cfg->xor_out) {
        crc ^= cfg->xor_out;
    }
    if (cfg->reflect_out) {
        crc = crc_reflect(crc, cfg->width);
    }
    result = crc_pre_final;
    for (i = 0; i < cfg->width / 8; i++) {
        data = (crc >> (cfg->width - 8 * i - 8)) & 0xff;
        if (cfg->reflect_in) {
            data = crc_reflect(data, 8);
        }
        result = crc_update(cfg, result, &data, 1);
    }
    // no crc_finalize, because if the CRC calculation is correct, result == 0.
    // A crc_finalize would XOR-in again some ones into the solution.
    // In theory the finalize function of the bit-by-bit algorithm
    // would also loop over cfg->width zero bits, but since
    // a) result == 0, and
    // b) input data == 0
    // the output would always be zero
    return result;
}

crc_t crc_reflect(crc_t data, size_t data_len)
{
    unsigned int i;
    crc_t ret;

    ret = 0;
    for (i = 0; i < data_len; i++)
    {
        if (data & 0x01) {
            ret = (ret << 1) | 1;
        } else {
            ret = ret << 1;
        }
        data >>= 1;
    }
    return ret;
}
#endif       // CRC_ALGO_BIT_BY_BIT


int main(int argc, char *argv[])
{
    crc_cfg_t cfg = {
        0,      // width
        0,      // poly
        0,      // xor_in
        0,      // reflect_in
        0,      // xor_out
        0,      // reflect_out

        0,      // crc_mask
        0,      // msb_mask
        0,      // crc_shift
    };
    crc_t crc;
    crc_t crc_test, crc_pre_final;
    char format[20];
    int ret, i;

    ret = get_config(argc, argv, &cfg);
    if (ret == 0) {
#       if CRC_ALGO_TABLE_DRIVEN
        crc_table_gen(&cfg);
#       endif       // CRC_ALGO_TABLE_DRIVEN
        crc = crc_init(&cfg);
        crc = crc_pre_final = crc_update(&cfg, crc, str, strlen((char *)str));
        crc = crc_finalize(&cfg, crc);

#       if CRC_ALGO_BIT_BY_BIT
        if (crc_verify(&cfg, crc_pre_final, crc) != 0) {
            fprintf(stderr, "error: crc verification failed\n");
            return 1;
        }
#       endif

        // calculate the checksum again, but this time loop over the input
        // bytes one-by-one.
        crc_test = crc_init(&cfg);
        for (i = 0; str[i]; i++)
        {
            crc_test = crc_update(&cfg, crc_test, str + i, 1);
        }
        crc_test = crc_finalize(&cfg, crc_test);
        if (crc_test != crc) {
            fprintf(stderr, "error: crc loop verification failed\n");
            return 1;
        }

        if (verbose) {
            snprintf(format, sizeof(format), "%%-16s = 0x%%0%dx\n", (unsigned int)(cfg.width + 3) / 4);
            printf("%-16s = %d\n", "width", (unsigned int)cfg.width);
            printf(format, "poly", (unsigned int)cfg.poly);
            printf("%-16s = %s\n", "reflect_in", cfg.reflect_in ? "true": "false");
            printf(format, "xor_in", cfg.xor_in);
            printf("%-16s = %s\n", "reflect_out", cfg.reflect_out ? "true": "false");
            printf(format, "xor_out", (unsigned int)cfg.xor_out);
            printf(format, "crc_mask", (unsigned int)cfg.crc_mask);
            printf(format, "msb_mask", (unsigned int)cfg.msb_mask);
        }
        printf("0x%llx\n", (unsigned long long int)crc);
    }
    return !ret;
}