-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathbinary_parser.js
More file actions
566 lines (477 loc) · 17.6 KB
/
binary_parser.js
File metadata and controls
566 lines (477 loc) · 17.6 KB
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//========================================================================================
// Globals
//========================================================================================
var Context = require("./context").Context;
var PRIMITIVE_TYPES = {
'UInt8' : 1,
'UInt16LE' : 2,
'UInt16BE' : 2,
'UInt32LE' : 4,
'UInt32BE' : 4,
'Int8' : 1,
'Int16LE' : 2,
'Int16BE' : 2,
'Int32LE' : 4,
'Int32BE' : 4,
'FloatLE' : 4,
'FloatBE' : 4,
'DoubleLE' : 8,
'DoubleBE' : 8
};
var SPECIAL_TYPES = {
'String' : null,
'Buffer' : null,
'Array' : null,
'Skip' : null,
'Choice' : null,
'Nest' : null,
'Bit' : null
};
var BIT_RANGE = [];
(function() {
var i;
for (i = 1; i <= 32; i++) {
BIT_RANGE.push(i);
}
})();
// Converts Parser's method names to internal type names
var NAME_MAP = {};
Object.keys(PRIMITIVE_TYPES)
.concat(Object.keys(SPECIAL_TYPES))
.forEach(function(type) {
NAME_MAP[type.toLowerCase()] = type;
});
//========================================================================================
// class Parser
//========================================================================================
//----------------------------------------------------------------------------------------
// constructor
//----------------------------------------------------------------------------------------
var Parser = function() {
this.varName = '';
this.type = '';
this.options = {};
this.next = null;
this.head = null;
this.compiled = null;
this.endian = 'be';
this.constructorFn = null;
};
//----------------------------------------------------------------------------------------
// public methods
//----------------------------------------------------------------------------------------
Parser.start = function() {
return new Parser();
};
Object.keys(PRIMITIVE_TYPES)
.forEach(function(type) {
Parser.prototype[type.toLowerCase()] = function(varName, options) {
return this.setNextParser(type.toLowerCase(), varName, options);
};
var typeWithoutEndian = type.replace(/BE|LE/, '').toLowerCase();
if (!(typeWithoutEndian in Parser.prototype)) {
Parser.prototype[typeWithoutEndian] = function(varName, options) {
return this[typeWithoutEndian + this.endian](varName, options);
};
}
});
BIT_RANGE.forEach(function(i) {
Parser.prototype['bit' + i.toString()] = function(varName, options) {
if (!options) {
options = {};
}
options.length = i;
return this.setNextParser('bit', varName, options);
};
});
Parser.prototype.skip = function(length, options) {
if (options && options.assert) {
throw new Error('assert option on skip is not allowed.');
}
return this.setNextParser('skip', '', {length: length});
};
Parser.prototype.string = function(varName, options) {
if (!options.zeroTerminated && !options.length) {
throw new Error('Neiter length nor zeroTerminated is defined for string.');
}
if (options.stripNull && !options.length) {
throw new Error('Length must be defined if stripNull is defined.');
}
options.encoding = options.encoding || 'utf8';
return this.setNextParser('string', varName, options);
};
Parser.prototype.buffer = function(varName, options) {
if (!options.length && !options.readUntil) {
throw new Error('Length nor readUntil is defined in buffer parser');
}
return this.setNextParser('buffer', varName, options);
};
Parser.prototype.array = function(varName, options) {
if (!options.readUntil && !options.length) {
throw new Error('Length option of array is not defined.');
}
if (!options.type) {
throw new Error('Type option of array is not defined.');
}
if (typeof options.type === 'string' && Object.keys(PRIMITIVE_TYPES).indexOf(NAME_MAP[options.type]) < 0) {
throw new Error('Specified primitive type "' + options.type + '" is not supported.');
}
return this.setNextParser('array', varName, options);
};
Parser.prototype.choice = function(varName, options) {
if (!options.tag) {
throw new Error('Tag option of array is not defined.');
}
if (!options.choices) {
throw new Error('Choices option of array is not defined.');
}
Object.keys(options.choices).forEach(function(key) {
if (isNaN(parseInt(key, 10))) {
throw new Error('Key of choices must be a number.');
}
if (!options.choices[key]) {
throw new Error('Choice Case ' + key + ' of ' + varName + ' is not valid.');
}
if (typeof options.choices[key] === 'string' && Object.keys(PRIMITIVE_TYPES).indexOf(NAME_MAP[options.choices[key]]) < 0) {
throw new Error('Specified primitive type "' + options.choices[key] + '" is not supported.');
}
});
return this.setNextParser('choice', varName, options);
};
Parser.prototype.nest = function(varName, options) {
if (!options.type) {
throw new Error('Type option of nest is not defined.');
}
if (!(options.type instanceof Parser)) {
throw new Error('Type option of nest must be a Parser object.');
}
return this.setNextParser('nest', varName, options);
};
Parser.prototype.endianess = function(endianess) {
switch (endianess.toLowerCase()) {
case 'little':
this.endian = 'le';
break;
case 'big':
this.endian = 'be';
break;
default:
throw new Error('Invalid endianess: ' + endianess);
}
return this;
};
Parser.prototype.create = function(constructorFn) {
if (!(constructorFn instanceof Function)) {
throw new Error('Constructor must be a Function object.');
}
this.constructorFn = constructorFn;
return this;
};
Parser.prototype.getCode = function() {
var ctx = new Context();
if (this.constructorFn) {
ctx.pushCode('var vars = new constructorFn("main");');
} else {
ctx.pushCode('var vars = {};');
}
ctx.pushCode('var offset = 0;');
ctx.pushCode('if (!Buffer.isBuffer(buffer)) {');
ctx.generateError('"argument buffer is not a Buffer object"');
ctx.pushCode('}');
this.generate(ctx);
ctx.pushCode('return vars;');
return ctx.code;
};
Parser.prototype.compile = function() {
this.compiled = new Function('buffer', 'callback', 'constructorFn', this.getCode());
};
Parser.prototype.sizeOf = function() {
var size = NaN;
if (Object.keys(PRIMITIVE_TYPES).indexOf(this.type) >= 0) {
size = PRIMITIVE_TYPES[this.type];
// if this is a fixed length string
} else if (this.type === 'String' && typeof this.options.length === 'number') {
size = this.options.length;
// if this is a fixed length array
} else if (this.type === 'Array' && typeof this.options.length === 'number') {
var elementSize = NaN;
if (typeof this.options.type === 'string'){
elementSize = PRIMITIVE_TYPES[NAME_MAP[this.options.type]];
} else if (this.options.type instanceof Parser) {
elementSize = this.options.type.sizeOf();
}
size = this.options.length * elementSize;
// if this a skip
} else if (this.type === 'Skip') {
size = this.options.length;
} else if (!this.type) {
size = 0;
}
if (this.next) {
size += this.next.sizeOf();
}
return size;
};
// Follow the parser chain till the root and start parsing from there
Parser.prototype.parse = function(buffer, callback) {
if (!this.compiled) {
this.compile();
}
return this.compiled(buffer, callback, this.constructorFn);
};
//----------------------------------------------------------------------------------------
// private methods
//----------------------------------------------------------------------------------------
Parser.prototype.setNextParser = function(type, varName, options) {
var parser = new Parser();
parser.type = NAME_MAP[type];
parser.varName = varName;
parser.options = options || parser.options;
parser.endian = this.endian;
if (this.head) {
this.head.next = parser;
} else {
this.next = parser;
}
this.head = parser;
return this;
};
// Call code generator for this parser
Parser.prototype.generate = function(ctx) {
if (this.type) {
this['generate' + this.type](ctx);
this.generateAssert(ctx);
}
var varName = ctx.generateVariable(this.varName);
if (this.options.formatter) {
this.generateFormatter(ctx, varName, this.options.formatter);
}
return this.generateNext(ctx);
};
Parser.prototype.generateAssert = function(ctx) {
if (!this.options.assert) {
return;
}
var varName = ctx.generateVariable(this.varName);
switch (typeof this.options.assert) {
case 'function':
ctx.pushCode('if (!({0}).call(vars, {1})) {', this.options.assert, varName);
break;
case 'number':
ctx.pushCode('if ({0} !== {1}) {', this.options.assert, varName);
break;
case 'string':
ctx.pushCode('if ("{0}" !== {1}) {', this.options.assert, varName);
break;
default:
throw new Error('Assert option supports only strings, numbers and assert functions.');
}
ctx.generateError('"Assert error: {0} is " + {0}', varName);
ctx.pushCode('}');
};
// Recursively call code generators and append results
Parser.prototype.generateNext = function(ctx) {
if (this.next) {
ctx = this.next.generate(ctx);
}
return ctx;
};
Object.keys(PRIMITIVE_TYPES).forEach(function(type) {
Parser.prototype['generate' + type] = function(ctx) {
ctx.pushCode('{0} = buffer.read{1}(offset);', ctx.generateVariable(this.varName), type);
ctx.pushCode('offset += {0};', PRIMITIVE_TYPES[type]);
};
});
Parser.prototype.generateBit = function(ctx) {
// TODO find better method to handle nested bit fields
var parser = JSON.parse(JSON.stringify(this));
parser.varName = ctx.generateVariable(parser.varName);
ctx.bitFields.push(parser);
if (!this.next || (this.next && ['Bit', 'Nest'].indexOf(this.next.type) < 0)) {
var sum = 0;
ctx.bitFields.forEach(function(parser) {
sum += parser.options.length;
});
var val = ctx.generateTmpVariable();
if (sum <= 8) {
ctx.pushCode('var {0} = buffer.readUInt8(offset);', val);
sum = 8;
} else if (sum <= 16) {
ctx.pushCode('var {0} = buffer.readUInt16BE(offset);', val);
sum = 16;
} else if (sum <= 24) {
var val1 = ctx.generateTmpVariable();
var val2 = ctx.generateTmpVariable();
ctx.pushCode('var {0} = buffer.readUInt16BE(offset);', val1);
ctx.pushCode('var {0} = buffer.readUInt8(offset + 2);', val2);
ctx.pushCode('var {2} = ({0} << 8) | {1};', val1, val2, val);
sum = 24;
} else if (sum <= 32) {
ctx.pushCode('var {0} = buffer.readUInt32BE(offset);', val);
sum = 32;
} else {
throw new Error('Currently, bit field sequence longer than 4-bytes is not supported.');
}
ctx.pushCode('offset += {0};', sum / 8);
var bitOffset = 0;
var isBigEndian = this.endian === 'be';
ctx.bitFields.forEach(function(parser) {
ctx.pushCode('{0} = {1} >> {2} & {3};',
parser.varName,
val,
isBigEndian ? sum - bitOffset - parser.options.length : bitOffset,
(1 << parser.options.length) - 1
);
bitOffset += parser.options.length;
});
ctx.bitFields = [];
}
};
Parser.prototype.generateSkip = function(ctx) {
var length = ctx.generateOption(this.options.length);
ctx.pushCode('offset += {0};', length);
};
Parser.prototype.generateString = function(ctx) {
var name = ctx.generateVariable(this.varName);
var start = ctx.generateTmpVariable();
if (this.options.length && this.options.zeroTerminated) {
ctx.pushCode('var {0} = offset;', start);
ctx.pushCode('while(buffer.readUInt8(offset++) !== 0 && offset - {0} < {1});',
start,
this.options.length
);
ctx.pushCode('{0} = buffer.toString(\'{1}\', {2}, offset - {2} < {3} ? offset - 1 : offset);',
name,
this.options.encoding,
start,
this.options.length
);
} else if(this.options.length) {
ctx.pushCode('{0} = buffer.toString(\'{1}\', offset, offset + {2});',
name,
this.options.encoding,
ctx.generateOption(this.options.length)
);
ctx.pushCode('offset += {0};', ctx.generateOption(this.options.length));
} else if (this.options.zeroTerminated) {
ctx.pushCode('var {0} = offset;', start);
ctx.pushCode('while(buffer.readUInt8(offset++) !== 0);');
ctx.pushCode('{0} = buffer.toString(\'{1}\', {2}, offset - 1);',
name,
this.options.encoding,
start
);
}
if(this.options.stripNull) {
ctx.pushCode('{0} = {0}.replace(/\\x00+$/g, \'\')', name);
}
};
Parser.prototype.generateBuffer = function(ctx) {
if (this.options.readUntil === 'eof') {
ctx.pushCode('{0} = buffer.slice(offset, buffer.length - 1);',
ctx.generateVariable(this.varName)
);
} else {
ctx.pushCode('{0} = buffer.slice(offset, offset + {1});',
ctx.generateVariable(this.varName),
ctx.generateOption(this.options.length)
);
ctx.pushCode('offset += {0};', ctx.generateOption(this.options.length));
}
if (this.options.clone) {
var buf = ctx.generateTmpVariable();
ctx.pushCode('var {0} = new Buffer({1}.length);', buf, ctx.generateVariable(this.varName));
ctx.pushCode('{0}.copy({1});', ctx.generateVariable(this.varName), buf);
ctx.pushCode('{0} = {1}', ctx.generateVariable(this.varName), buf);
}
};
Parser.prototype.generateArray = function(ctx) {
var length = ctx.generateOption(this.options.length);
var type = this.options.type;
var counter = ctx.generateTmpVariable();
var lhs = ctx.generateVariable(this.varName);
var item = ctx.generateTmpVariable();
var key = this.options.key;
var isHash = typeof key === 'string';
if (isHash) {
ctx.pushCode('{0} = {};', lhs);
} else {
ctx.pushCode('{0} = [];', lhs);
}
if (typeof this.options.readUntil === 'function') {
ctx.pushCode('do {');
} else if (this.options.readUntil === 'eof') {
ctx.pushCode('for (var {0} = 0; offset < buffer.length; {0}++) {', counter);
} else {
ctx.pushCode('for (var {0} = 0; {0} < {1}; {0}++) {', counter, length);
}
if (typeof type === 'string') {
ctx.pushCode('var {0} = buffer.read{1}(offset);', item, NAME_MAP[type]);
ctx.pushCode('offset += {0};', PRIMITIVE_TYPES[NAME_MAP[type]]);
} else if (type instanceof Parser) {
ctx.pushCode('var {0} = {};', item);
ctx.pushScope(item);
type.generate(ctx);
ctx.popScope();
}
if (isHash) {
ctx.pushCode('{0}[{2}.{1}] = {2};', lhs, key, item);
} else {
ctx.pushCode('{0}.push({1});', lhs, item);
}
ctx.pushCode('}');
if (typeof this.options.readUntil === 'function') {
ctx.pushCode(' while (!({0}).call(this, {1}, buffer.slice(offset)));', this.options.readUntil, item);
}
};
Parser.prototype.generateChoiceCase = function(ctx, varName, type) {
if (typeof type === 'string') {
ctx.pushCode('{0} = buffer.read{1}(offset);', ctx.generateVariable(this.varName), NAME_MAP[type]);
ctx.pushCode('offset += {0};', PRIMITIVE_TYPES[NAME_MAP[type]]);
} else if (type instanceof Parser) {
ctx.pushPath(varName);
type.generate(ctx);
ctx.popPath();
}
};
Parser.prototype.generateChoice = function(ctx) {
var tag = ctx.generateOption(this.options.tag);
ctx.pushCode('{0} = {};', ctx.generateVariable(this.varName));
ctx.pushCode('switch({0}) {', tag);
Object.keys(this.options.choices).forEach(function(tag) {
var type = this.options.choices[tag];
ctx.pushCode('case {0}:', tag);
this.generateChoiceCase(ctx, this.varName, type);
ctx.pushCode('break;');
}, this);
ctx.pushCode('default:');
if (this.options.defaultChoice) {
this.generateChoiceCase(ctx, this.varName, this.options.defaultChoice);
} else {
ctx.generateError('"Met undefined tag value " + {0} + " at choice"', tag);
}
ctx.pushCode('}');
};
Parser.prototype.generateNest = function(ctx) {
var nestVar = ctx.generateVariable(this.varName);
if(this.options.type.constructorFn) {
ctx.pushCode('{0} = new constructorFn("' + this.varName + '");', nestVar);
} else {
ctx.pushCode('{0} = {};', nestVar);
}
ctx.pushPath(this.varName);
this.options.type.generate(ctx);
ctx.popPath();
};
Parser.prototype.generateFormatter = function(ctx, varName, formatter) {
if (typeof formatter === 'function') {
ctx.pushCode('{0} = ({1}).call(this, {0});', varName, formatter);
}
};
Parser.prototype.isInteger = function() {
return !!this.type.match(/U?Int[8|16|32][BE|LE]?|Bit\d+/);
};
//========================================================================================
// Exports
//========================================================================================
exports.Parser = Parser;