Bug 251420

Summary: [JSC] Crash On JSC when open dir as input file
Product: WebKit Reporter: hackerzheng666
Component: JavaScriptCoreAssignee: Michael Saboff <msaboff>
Status: RESOLVED FIXED    
Severity: Normal CC: bfulgham, msaboff, webkit-bug-importer
Priority: P2 Keywords: InRadar
Version: WebKit Local Build   
Hardware: All   
OS: Linux   

Description hackerzheng666 2023-01-30 22:25:04 PST
This is a interestring bug. When I try to execute "./jsc /dir1/test.js", I forget to add test.js, which made it execute "./jsc /dir1" and it crashed.

After reviewing the code, I found there is a check which seems not so proper.

When we open a file which is dir, fseek will make it search for the end of file. But it seems that there is no EOF in dir, so it keeps finding and take
the MAX value of stream as bufferCapacity, which is 0x7fffffffffffffff, it bypass the check of "fseek(file, 0, SEEK_END) == -1", and the resize of such
value whill crash the jsc.

```cpp
template<typename Vector>
static bool fillBufferWithContentsOfFile(FILE* file, Vector& buffer)
{
    // We might have injected "use strict"; at the top.
    size_t initialSize = buffer.size();
    if (fseek(file, 0, SEEK_END) == -1)
        return false;
    long bufferCapacity = ftell(file);
    if (bufferCapacity == -1)
        return false;
    if (fseek(file, 0, SEEK_SET) == -1)
        return false;
    buffer.resize(bufferCapacity + initialSize);
    size_t readSize = fread(buffer.data() + initialSize, 1, buffer.size(), file);
    return readSize == buffer.size() - initialSize;
}
```

There is another position. But I think here the check of "!result" can prevent the crash.

```cpp
static RefPtr<Uint8Array> fillBufferWithContentsOfFile(FILE* file)
{
    if (fseek(file, 0, SEEK_END) == -1)
        return nullptr;
    long bufferCapacity = ftell(file);
    if (bufferCapacity == -1)
        return nullptr;
    if (fseek(file, 0, SEEK_SET) == -1)
        return nullptr;
    auto result = Uint8Array::tryCreate(bufferCapacity);
    if (!result)
        return nullptr;
    size_t readSize = fread(result->data(), 1, bufferCapacity, file);
    if (readSize != static_cast<size_t>(bufferCapacity))
        return nullptr;
    return result;
}
```

Regrads,
Zheng Wang
Comment 1 Radar WebKit Bug Importer 2023-01-30 22:25:18 PST
<rdar://problem/104853422>
Comment 2 Michael Saboff 2024-04-02 14:39:38 PDT
Pull request: https://github.com/WebKit/WebKit/pull/26753
Comment 3 EWS 2024-04-03 10:17:58 PDT
Committed 277010@main (6e20396fae8b): <https://commits.webkit.org/277010@main>

Reviewed commits have been landed. Closing PR #26753 and removing active labels.