keichi / binary-parser

A blazing-fast declarative parser builder for binary data
MIT License
857 stars 133 forks source link

How to handle a field that is present depending on an earlier field #232

Closed gtflip closed 1 year ago

gtflip commented 1 year ago

I'm parsing PE (Portable Executable) files, and there's one section that has a field, "BaseOfData" that's only present for PE32 files, not PE32+ files.

The magic number at the beginning of the header tells you whether it's a PE32 or PE32+ file. What's the best way to handle that case?

Relevant section of the PE documentation if you're interested.

keichi commented 1 year ago

You could use choice() and pass an empty parser if the input is a PE32 file. Something like this:

var Parser = require("binary-parser").Parser;

var parser = Parser.start()
                .uint16le("Magic")
                .choice("BaseOfCode", {
                    tag: "magic",
                    choices: {
                        0x10b: Parser.start(),
                        0x20b: Parser.start().uint32le()
                    }
                });
gtflip commented 1 year ago

That worked perfectly. Thanks!