Skip to content
Myr

Fix shebang parsing reading past the end of a small file

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 5464d43 · Browse files · 2 files+23 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+23 added−2 removed

  • tests:+18 added−0 removed
  • other:+5 added−2 removed

2 files+23 added−2 removed

modified:lib/arguments/command-file.js+5 added-2 removed
125 unmodified lines
126127// Read the file's first bytes to find its shebang interpreter, if it has one128const readShebang = file => {129 const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);130 let bytesRead = 0;131132 try {133 const fileDescriptor = openSync(file, 'r');134 try {134 readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);135 bytesRead = readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);136 } finally {137 closeSync(fileDescriptor);138 }139 } catch {140 return undefined;141 }142143 // A file shorter than the buffer leaves it zero-filled, so only the bytes actually read must be parsed.144 // Otherwise, a shebang line which is not terminated by a newline would include those `\0` characters.142 return parseShebang(buffer.toString());145 return parseShebang(buffer.toString('utf8', 0, bytesRead));146};147148const shebangRegExp = /^#!(?<line>.*)/;149
55 unmodified lines
modified:test/arguments/command-resolution.js+18 added
150 unmodified lines
151 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);152 t.is(stdoutSync, 'foo');153});154155/*156Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer.157A file which only contains a shebang line, without a trailing newline, is shorter than that buffer, which is zero-filled.158Only the bytes actually read must be parsed, otherwise the interpreter would include those `\0` characters, which does not resolve to any file.159The file is created by the test since Unix cannot execute it, so it must not be used by any other test.160*/161if (isWindows) {162 test('Runs a shebang script shorter than the shebang buffer', async t => {163 const filePath = path.join(FIXTURES_DIRECTORY, 'shebang-only.js');164 await writeFile(filePath, '#!/usr/bin/env node');165 t.teardown(() => unlink(filePath));166167 const {exitCode, stdout} = await execa('shebang-only.js');168 t.is(exitCode, 0);169 t.is(stdout, '');170 });171}172173// Neither the caller's arguments array nor its options object should be mutated,174// whether or not a shell is used (each path clones the arguments internally).175const testNoMutation = async (t, options) => {176 const commandArguments = ['foo', 'bar'];
369 unmodified lines