forked from keichi/binary-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_parser.js
More file actions
749 lines (643 loc) · 20.1 KB
/
binary_parser.js
File metadata and controls
749 lines (643 loc) · 20.1 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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//========================================================================================
// Globals
//========================================================================================
var vm = require("vm");
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 aliasRegistry = {};
var FUNCTION_PREFIX = "___parser_";
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;
this.alias = 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.namely = function(alias) {
aliasRegistry[alias] = this;
this.alias = alias;
return this;
};
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 && !options.greedy) {
throw new Error(
"Neither length, zeroTerminated, nor greedy is defined for string."
);
}
if ((options.zeroTerminated || options.length) && options.greedy) {
throw new Error(
"greedy is mutually exclusive with length and zeroTerminated for string."
);
}
if (options.stripNull && !(options.length || options.greedy)) {
throw new Error(
"Length or greedy 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 && !options.lengthInBytes) {
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" &&
!aliasRegistry[options.type] &&
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 (arguments.length == 1 && typeof varName === "object") {
options = varName;
varName = null;
}
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" &&
!aliasRegistry[options.choices[key]] &&
Object.keys(PRIMITIVE_TYPES).indexOf(NAME_MAP[options.choices[key]]) < 0
) {
throw new Error(
'Specified primitive type "' +
options.choices[key] +
'" is not supported.'
);
}
}, this);
return this.setNextParser("choice", varName, options);
};
Parser.prototype.nest = function(varName, options) {
if (arguments.length == 1 && typeof varName === "object") {
options = varName;
varName = null;
}
if (!options.type) {
throw new Error("Type option of nest is not defined.");
}
if (!(options.type instanceof Parser) && !aliasRegistry[options.type]) {
throw new Error("Type option of nest must be a Parser object.");
}
if (!(options.type instanceof Parser) && !varName) {
throw new Error(
"options.type must be a object if variable name is omitted."
);
}
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();
ctx.pushCode("if (!Buffer.isBuffer(buffer)) {");
ctx.generateError('"argument buffer is not a Buffer object"');
ctx.pushCode("}");
if (!this.alias) {
this.addRawCode(ctx);
} else {
this.addAliasedCode(ctx);
}
if (this.alias) {
ctx.pushCode("return {0}(0).result;", FUNCTION_PREFIX + this.alias);
} else {
ctx.pushCode("return vars;");
}
return ctx.code;
};
Parser.prototype.addRawCode = function(ctx) {
ctx.pushCode("var offset = 0;");
if (this.constructorFn) {
ctx.pushCode("var vars = new constructorFn();");
} else {
ctx.pushCode("var vars = {};");
}
this.generate(ctx);
this.resolveReferences(ctx);
ctx.pushCode("vars.__bytesRead = offset; return vars;");
};
Parser.prototype.addAliasedCode = function(ctx) {
ctx.pushCode("function {0}(offset) {", FUNCTION_PREFIX + this.alias);
if (this.constructorFn) {
ctx.pushCode("var vars = new constructorFn();");
} else {
ctx.pushCode("var vars = {};");
}
this.generate(ctx);
ctx.markResolved(this.alias);
this.resolveReferences(ctx);
ctx.pushCode("return { offset: offset, result: vars };");
ctx.pushCode("}");
return ctx;
};
Parser.prototype.resolveReferences = function(ctx) {
var references = ctx.getUnresolvedReferences();
ctx.markRequested(references);
references.forEach(function(alias) {
var parser = aliasRegistry[alias];
parser.addAliasedCode(ctx);
});
};
Parser.prototype.compile = function() {
var src = "(function(buffer, constructorFn) { " + this.getCode() + " })";
this.compiled = vm.runInThisContext(src);
};
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 buffer
} else if (
this.type === "Buffer" &&
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;
// if this is a nested parser
} else if (this.type === "Nest") {
size = this.options.type.sizeOf();
} 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) {
if (!this.compiled) {
this.compile();
}
return this.compiled(buffer, 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
);
} else if (this.options.greedy) {
ctx.pushCode("var {0} = offset;", start);
ctx.pushCode("while(buffer.length > offset++);");
ctx.pushCode(
"{0} = buffer.toString('{1}', {2}, offset);",
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);",
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) {
ctx.pushCode("{0} = Buffer.from({0});", ctx.generateVariable(this.varName));
}
};
Parser.prototype.generateArray = function(ctx) {
var length = ctx.generateOption(this.options.length);
var lengthInBytes = ctx.generateOption(this.options.lengthInBytes);
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 if (lengthInBytes !== undefined) {
ctx.pushCode(
"for (var {0} = offset; offset - {0} < {1}; ) {",
counter,
lengthInBytes
);
} else {
ctx.pushCode("for (var {0} = 0; {0} < {1}; {0}++) {", counter, length);
}
if (typeof type === "string") {
if (!aliasRegistry[type]) {
ctx.pushCode("var {0} = buffer.read{1}(offset);", item, NAME_MAP[type]);
ctx.pushCode("offset += {0};", PRIMITIVE_TYPES[NAME_MAP[type]]);
} else {
var tempVar = ctx.generateTmpVariable();
ctx.pushCode("var {0} = {1}(offset);", tempVar, FUNCTION_PREFIX + type);
ctx.pushCode("var {0} = {1}.result; offset = {1}.offset;", item, tempVar);
if (type !== this.alias) ctx.addReference(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") {
if (!aliasRegistry[type]) {
ctx.pushCode(
"{0} = buffer.read{1}(offset);",
ctx.generateVariable(this.varName),
NAME_MAP[type]
);
ctx.pushCode("offset += {0};", PRIMITIVE_TYPES[NAME_MAP[type]]);
} else {
var tempVar = ctx.generateTmpVariable();
ctx.pushCode("var {0} = {1}(offset);", tempVar, FUNCTION_PREFIX + type);
ctx.pushCode(
"{0} = {1}.result; offset = {1}.offset;",
ctx.generateVariable(this.varName),
tempVar
);
if (type !== this.alias) ctx.addReference(type);
}
} else if (type instanceof Parser) {
ctx.pushPath(varName);
type.generate(ctx);
ctx.popPath(varName);
}
};
Parser.prototype.generateChoice = function(ctx) {
var tag = ctx.generateOption(this.options.tag);
if (this.varName) {
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 instanceof Parser) {
if (this.varName) {
ctx.pushCode("{0} = {};", nestVar);
}
ctx.pushPath(this.varName);
this.options.type.generate(ctx);
ctx.popPath(this.varName);
} else if (aliasRegistry[this.options.type]) {
var tempVar = ctx.generateTmpVariable();
ctx.pushCode(
"var {0} = {1}(offset);",
tempVar,
FUNCTION_PREFIX + this.options.type
);
ctx.pushCode("{0} = {1}.result; offset = {1}.offset;", nestVar, tempVar);
if (this.options.type !== this.alias) ctx.addReference(this.options.type);
}
};
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;