Skip to content

Commit 7c1a631

Browse files
committed
Fix shebang parsing reading past the end of a small file
1 parent 5464d43 commit 7c1a631

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎lib/arguments/command-file.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,19 +127,22 @@ const SHEBANG_BYTE_LENGTH = 150;
127127
// Read the file's first bytes to find its shebang interpreter, if it has one
128128
const readShebang = file => {
129129
const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);
130+
let bytesRead = 0;
130131

131132
try {
132133
const fileDescriptor = openSync(file, 'r');
133134
try {
134-
readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);
135+
bytesRead = readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);
135136
} finally {
136137
closeSync(fileDescriptor);
137138
}
138139
} catch {
139140
return undefined;
140141
}
141142

142-
return parseShebang(buffer.toString());
143+
// 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.
145+
return parseShebang(buffer.toString('utf8', 0, bytesRead));
143146
};
144147

145148
const shebangRegExp = /^#!(?<line>.*)/;

‎test/arguments/command-resolution.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,24 @@ test('Runs a shebang script with a space after the "#!"', async t => {
152152
t.is(stdoutSync, 'foo');
153153
});
154154

155+
/*
156+
Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer.
157+
A file which only contains a shebang line, without a trailing newline, is shorter than that buffer, which is zero-filled.
158+
Only the bytes actually read must be parsed, otherwise the interpreter would include those `\0` characters, which does not resolve to any file.
159+
The file is created by the test since Unix cannot execute it, so it must not be used by any other test.
160+
*/
161+
if (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));
166+
167+
const {exitCode, stdout} = await execa('shebang-only.js');
168+
t.is(exitCode, 0);
169+
t.is(stdout, '');
170+
});
171+
}
172+
155173
// Neither the caller's arguments array nor its options object should be mutated,
156174
// whether or not a shell is used (each path clones the arguments internally).
157175
const testNoMutation = async (t, options) => {

0 commit comments

Comments
 (0)