File: Parser.cpp

package info (click to toggle)
gopchop 1.1.8-6
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 2,900 kB
  • ctags: 1,159
  • sloc: sh: 9,981; cpp: 4,975; ansic: 4,028; makefile: 104
file content (419 lines) | stat: -rw-r--r-- 9,259 bytes parent folder | download | duplicates (2)
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
#
# Creates an in-memory interface to a file, with largefile support.
# Uses mmap to make data available in a user-space memory window.
#
# $Id: Parser.cpp 347 2009-03-02 23:27:14Z keescook $
#
# Copyright (C) 2001-2009 Kees Cook
# kees@outflux.net, http://outflux.net/
# 
# 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 program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# http://www.gnu.org/copyleft/gpl.html
#
*/

#include "GOPchop.h"
#include "Parser.h"

// FIXME: do config.h magic...
#include <stdarg.h>
#include <errno.h>
#include <string.h>

#undef MEMORY_UPDATE
#ifdef MEMORY_UPDATE
# define MMAP_PROT	(PROT_READ|PROT_WRITE)
# define OPEN_MODE	(O_RDWR)
#else
# define MMAP_PROT	(PROT_READ)
# define OPEN_MODE	(O_RDONLY)
#endif

Parser::Parser(size_t window)
{
    // set passed-in values
    mmap_max = window;

    // set detected values
    pagesize = getpagesize();

    // set values that "reset" depends on
    filename = NULL;
    fd = -1;
    mmap_ptr = NULL;
    mmap_len = 0;
    mmap_offset = 0;
    error = NULL;

    reset();
}

void Parser::reset()
{
    if (filename)
    {
        free(filename);
        filename = NULL;
    }

    if (fd > -1)
    {
        close(fd);
        fd = -1;
    }
    filesize = 0;

    if (mmap_ptr)
    {
        if (munmap(mmap_ptr, mmap_len))
            perror("munmap");
        mmap_ptr = NULL;
        mmap_len = 0;
        mmap_offset = 0;
    }

    location = 0;
    start = NULL;
    report_errors = TRUE;
    parsing_state=PARSER_STATE_UNLOADED;

    clearError();
}

Parser::~Parser()
{
    reset();
}

int Parser::getParsingState()
{
    return parsing_state;
}

#define MIN(a,b)	((a)<(b) ? (a) : (b))
int Parser::init(char *pathname, void (*ticker) (char *, float))
{
    struct stat st;

    tick = ticker;

    // make sure we're not already running
    if (filename || fd > -1 || mmap_ptr)
    {
        reset();
        addError("%s", _("already initialized\n"));
        return FALSE;
    }

    // open file
    if ((fd = open(pathname, OPEN_MODE)) < 0)
    {
        reset();
        addError(_("cannot open '%s': %s\n"), pathname, strerror(errno));
#ifdef MEMORY_UPDATE
        addError("%s",
                 _
                 (" (write permissions are needed, but the original file won't be changed.)\n"));
#endif
        return FALSE;
    }

    // get file size
    if (fstat(fd, &st))
    {
        reset();
        addError(_("cannot get file size: %s\n"), strerror(errno));
        return FALSE;
    }

    if (!S_ISREG(st.st_mode))
    {
        reset();
        addError(_("'%s' is not a file!\n"), pathname);
        return FALSE;
    }

    filesize = st.st_size;

    mmap_len = MIN(mmap_max, filesize);

    if ((mmap_ptr = (uint8_t *) mmap(NULL, mmap_len, MMAP_PROT,
                                     MAP_PRIVATE, fd, 0)) == MAP_FAILED)
    {
        reset();
        addError("%s", _("cannot memory map file\n"));
        return FALSE;
    }

    filename = strdup(pathname);
    start = mmap_ptr;
    location = 0;

    parsing_state=PARSER_STATE_READY;

    return TRUE;
}

char *Parser::getFilename()
{
    return filename;
}

char *Parser::getError()
{
    return error;
}

off_t Parser::getSize()
{
    return filesize;
}

#define MAX(a,b)	((a) > (b) ? (a) : (b))

uint8_t *Parser::bytesAvail(off_t location, size_t bytes)
{
    off_t pagedloc;
    size_t pagedbytes;

    // make sure we're in bounds
    if (!mmap_ptr || location > filesize || location + bytes > filesize)
    {
        /*
           printf("%s",_("out of bounds\n"));
           printf(_("filesize: %llu\n"),filesize);
           printf(_("location: %llu\n"),location);
           printf(_("bytes: %d\n"),bytes);
         */
        return NULL;
    }

    // are we inbounds in current mmap region?
    if (mmap_offset <= location && location + bytes <= mmap_offset + mmap_len)
    {
        start = mmap_ptr + (location - mmap_offset);
        return start;
    }

    // we're not inbounds, let's realign on page boundry, near "location"

    // get page-aligned location
    pagedloc = location / pagesize;
    pagedloc *= pagesize;

    // figure out our expected mmap window size
    pagedbytes = MAX(mmap_max, (location - pagedloc) + bytes);
    // mmap area too large
    if (pagedbytes > mmap_max)
    {
        printf(_("mmap area too large (must increase window size!)\n"
                 "pagedbytes: %d mmap_max: %d\n"
                 "location: %llu pagedloc: %llu\n"
                 "bytes: %d\n"),
               pagedbytes, mmap_max, location, pagedloc, bytes);
        return NULL;
    }

    // unmmmap or fail
    if (munmap(mmap_ptr, mmap_len))
    {
        printf("%s", _("munmap failed\n"));
        reset();
        addError("%s", _("munmap\n"));
        return NULL;
    }

    mmap_len = pagedbytes;
    mmap_offset = pagedloc;

    // remmap or fail
    if ((mmap_ptr = (uint8_t *) mmap(NULL, mmap_len, MMAP_PROT,
                                     MAP_PRIVATE, fd,
                                     mmap_offset)) == MAP_FAILED)
    {
        printf("%s", _("mmap failed\n"));
        reset();
        addError("%s", _("cannot memory map file\n"));
        return NULL;
    }
    /*
       fprintf(stderr,_("remapped %d from %llu @ 0x%08x\n"),
       mmap_len, mmap_offset, (unsigned int)mmap_ptr);
     */

    start = mmap_ptr + (location - mmap_offset);
    return start;
}

void Parser::clearError()
{
    if (error)
    {
        free(error);
        error = NULL;
    }
}

void Parser::addError(const char *fmt, ...)
{
    char buf[1024];
    va_list vaptr;
    int len;
    int leftoff = 0;

    if (!report_errors)
        return;

    buf[0] = '\0';              // preterminate for fun

    va_start(vaptr, fmt);
    vsnprintf(buf, 1024, fmt, vaptr);
    va_end(vaptr);

    len = strlen(buf) + 1;      // one for NULL

    if (error)
    {
        leftoff = strlen(error);
        len += leftoff;
    }

    if (!(error = (char *) realloc(error, len)))
    {
        // if we can't get memory for an error, we probably
        // can't do much of anything anyway.
        perror("realloc");
        exit(1);
    }
    error[leftoff] = '\0';      // terminate our (possibly) new memory

    // this is safe now, since we used add's len to allocate it
    strcat(error, buf);

    // send out the stderr too
    fprintf(stderr, "%s", buf);
}

int Parser::consume(size_t bytes, uint8_t * match)
{
    // no bytes?  SURE!
    if (!bytes)
        return TRUE;

    if (!bytesAvail(location, bytes) || memcmp(start, match, bytes))
        return FALSE;

    start += bytes;
    location += bytes;

    return TRUE;
}

int Parser::verify(uint8_t * source, size_t bytes, uint8_t * match)
{
    // no bytes?  SURE!
    if (!bytes)
        return TRUE;

    if (memcmp(source, match, bytes) == 0)
        return TRUE;
    return FALSE;
}

// Returns "start" before incrementing by "bytes"
uint8_t *Parser::attach(size_t bytes)
{
    uint8_t *ptr;

    if ((ptr = examine(bytes)))
    {
        start += bytes;
        location += bytes;
    }

    return ptr;
}

// returns points to memory but does not increment
uint8_t *Parser::examine(size_t bytes)
{
    uint8_t *ptr = NULL;

    // no bytes? bad...
    if (bytes && bytesAvail(location, bytes))
    {
        ptr = start;
    }

    return ptr;
}

// Checks for "bytes" many bytes into the future to match "match"
int Parser::forwardMatch(size_t bytes, uint8_t * match)
{
    // no bytes?  SURE!
    if (!bytes)
        return TRUE;

    if (bytesAvail(location, bytes) && !memcmp(start, match, bytes))
    {
        return TRUE;
    }
    else
        return FALSE;
}

// Checks for up to 8 bits in the next byte, matching "value"
int Parser::forwardBitMatch(int bits, uint8_t value)
{
    uint8_t match;
    uint8_t mask;

    // 0 bits?  SURE!
    if (!bits)
        return TRUE;

    if (!bytesAvail(location, 1))
        return FALSE;

    match = value << (8 - bits);
    mask = (0xFF >> (8 - bits)) << (8 - bits);

    /*
       int result=((*start & mask) == match);
       printf(_("*start: %d mask: %d match: %d result: %d\n"),
       *start, mask, match, result);
     */

    return ((*start & mask) == match);
}

// external access to the parsing state.  This can only be set if 
// Parser is "READY" or "PARSING".  Once set to "FINISHED", it must
// be ->reset to clear it.
void Parser::setParsingState(int state)
{
    if ((parsing_state==PARSER_STATE_READY &&
         state==PARSER_STATE_PARSING) ||
        (parsing_state==PARSER_STATE_PARSING &&
         state==PARSER_STATE_FINISHED))
    {
        parsing_state=state;
    }
}


/* vi:set ai ts=4 sw=4 expandtab: */