diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9f0fdca --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/.idea/ +/node_modules/ diff --git a/example.js b/example.js new file mode 100644 index 0000000..fd042d3 --- /dev/null +++ b/example.js @@ -0,0 +1,6 @@ +const getArchitecture = require('.'); + +(async () => { + const arch = await getArchitecture('C:\\Windows\\System32\\cmd.exe'); + console.log(arch); // 'x64' +})(); diff --git a/index.js b/index.js new file mode 100644 index 0000000..37c1e3b --- /dev/null +++ b/index.js @@ -0,0 +1,53 @@ +const fs = require('fs'); + +module.exports = file => { + return new Promise((resolve, reject) => { + // Check that file is readable + fs.access(file, fs.constants.F_OK | fs.constants.R_OK, err => { + if (err) { + reject(new Error(`${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is not readable'}`)); + } else { + // Open file + fs.open(file, 'r', (err, fd) => { + if (err) { + reject(err); + } else { + // Determine offset to PE header + let buffer = Buffer.alloc(4); + fs.read(fd, buffer, 0, 4, 0x3C, err => { + if (err) { + reject(err); + } else { + // Read PE header + const offset = hexToDec(littleEndian(buffer)); + buffer = Buffer.alloc(2); + fs.read(fd, buffer, 0, 2, offset + 0x18, err => { + if (err) { + reject(err); + } else { + const hex = littleEndian(buffer); + const result = hex === '020b' ? 'x64' : hex === '010b' ? 'x86' : null; + + if (result === null) { + reject(new Error('Unknown')); + } else { + resolve(result); + } + } + }); + } + }); + } + }); + } + }); + }); +}; + +function littleEndian(buffer) { + return buffer.toString('hex').match(/../g).reverse().join(''); +} + +function hexToDec(hex) { + return parseInt(hex, 16); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..793e76f --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "get-architecture", + "version": "1.0.0", + "description": "Binary file architecture detector", + "repository": { + "type": "git", + "url": "git://github.com/axelstudios/get-architecture.git" + }, + "main": "./index.js", + "files": [ + "index.js" + ], + "author": "Alex Swindler ", + "engines": { + "node": "*" + }, + "scripts": { + "lint": "xo --space" + }, + "license": "MIT", + "devDependencies": { + "xo": "~0.23.0" + } +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..3a9e641 --- /dev/null +++ b/readme.md @@ -0,0 +1,22 @@ +# get-architecture + +A tiny Node utility to detect whether .exe and .dll files are 32 or 64-bit. + +## Installation + +```bash +$ npm install get-architecture +``` + +## Usage + +`get-architecture` exposes a function; simply pass this function the path of a .exe or .dll to test and it will return a promise resolving to `x86`, `x64`, or rejecting with `Unknown`. + +```js +const getArchitecture = require('get-architecture'); + +(async () => { + const arch = await getArchitecture('myFile.exe'); + console.log(arch); // 'x64' +})(); +```