Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/api/EscargotPublic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1265,7 +1265,13 @@ StringRef* Evaluator::EvaluatorResult::resultOrErrorToString(ContextRef* ctx) co
if (isSuccessful()) {
return result->toStringWithoutException(ctx);
} else {
return ((ValueRef*)error.value())->toStringWithoutException(ctx);
// Check if error value is valid before dereferencing
// In some edge cases (e.g., nested eval throw with finally allocation),
// the error value might be invalid or null
if (error.hasValue()) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anchor on if (error.hasValue()) {. Replace the nested if-else with a guard clause that returns early when the error is absent. This flattens the control flow, reduces indentation, and makes the success path more obvious. The semantics remain unchanged because the early return still yields StringRef::emptyString() when error.hasValue() is false.

return ((ValueRef*)error.value())->toStringWithoutException(ctx);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ((ValueRef*)error.value())->toStringWithoutException(ctx) dereferences the pointer returned by error.value() without verifying it is non‑null. If error.value() is null, this will cause a crash. Add a null check, e.g., if (error.hasValue() && error.value() != nullptr) before dereferencing.

}
return StringRef::emptyString();
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/builtins/BuiltinTypedArray.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,9 @@ static Value builtinTypedArrayCopyWithin(ExecutionState& state, Value thisValue,
// Set len to TypedArrayLength(taRecord).
len = O->arrayLength();
// Set count to min(count, len - startIndex, len - targetIndex).
count = std::min(std::min(count, len - startIndex), len - targetIndex);
// NOTE: After buffer resize during argument coercion, len - startIndex or len - targetIndex can be negative.
// We must clamp count to non-negative to prevent integer underflow when casting to size_t.
count = std::max(0.0, std::min(std::min(count, len - startIndex), len - targetIndex));
Comment thread
ksh8281 marked this conversation as resolved.
// Let typedArrayName be the String value of O.[[TypedArrayName]].
// Let elementSize be the Number value of the Element Size value specified in Table 59 for typedArrayName.
size_t elementSize = O->elementSize();
Expand Down
2 changes: 1 addition & 1 deletion src/interpreter/ByteCode.h
Original file line number Diff line number Diff line change
Expand Up @@ -3308,7 +3308,7 @@ class ByteCodeBlock : public gc {
context->m_locData->push_back(std::make_pair(start, idx));
}

#ifndef NDEBUG
#if !defined(NDEBUG) && defined(ESCARGOT_DEBUGGER)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The preprocessor guard #if !defined(NDEBUG) && defined(ESCARGOT_DEBUGGER) can be reordered for clarity. Using #if defined(ESCARGOT_DEBUGGER) && !defined(NDEBUG) makes the intent more obvious: code is compiled only when the debugger is enabled and NDEBUG is not defined. This small change improves readability and aligns with common macro ordering conventions. It preserves semantics and requires no functional changes. The guard remains localized to this block, so no cross-file impact.

const auto loc = computeNodeLOC(m_codeBlock->src(), m_codeBlock->functionStart(), idx);
ByteCodeLOC* bytecodeLoc = &reinterpret_cast<ByteCode*>(first)->m_loc;
bytecodeLoc->index = loc.index;
Expand Down
29 changes: 28 additions & 1 deletion src/interpreter/ByteCodeInterpreter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4602,7 +4602,34 @@ NEVER_INLINE void InterpreterSlowPath::arrayDefineOwnPropertyBySpreadElementOper

size_t newLength = baseIndex + elementLength;
arr->setArrayLength(state, newLength);
ASSERT(arr->isFastModeArray());

// Check if the array is still in fast mode after setArrayLength
// setArrayLength can convert the array to non-fast mode when length exceeds thresholds
if (UNLIKELY(!arr->isFastModeArray())) {
// Array was converted to non-fast mode, use slow path
size_t elementIndex = 0;
for (size_t i = 0; i < code->m_count; i++) {
if (LIKELY(code->m_loadRegisterIndexs[i] != REGISTER_LIMIT)) {
Value element = registerFile[code->m_loadRegisterIndexs[i]];
if (element.isObject() && element.asObject()->isSpreadArray()) {
ArrayObject* spreadArray = element.asObject()->asArrayObject();
ASSERT(spreadArray->isFastModeArray());
Value spreadElement;
for (size_t spreadIndex = 0; spreadIndex < spreadArray->arrayLength(state); spreadIndex++) {
spreadElement = spreadArray->m_fastModeData[spreadIndex];
arr->defineOwnProperty(state, ObjectPropertyName(state, baseIndex + elementIndex), ObjectPropertyDescriptor(spreadElement, ObjectPropertyDescriptor::AllPresent));
elementIndex++;
}
} else {
arr->defineOwnProperty(state, ObjectPropertyName(state, baseIndex + elementIndex), ObjectPropertyDescriptor(element, ObjectPropertyDescriptor::AllPresent));
elementIndex++;
}
} else {
elementIndex++;
}
}
return;
}

size_t elementIndex = 0;
for (size_t i = 0; i < code->m_count; i++) {
Expand Down
2 changes: 1 addition & 1 deletion src/parser/CodeBlock.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ struct ASTScopeContext;
struct ByteCodeGenerateContext;

typedef HashMap<AtomicString, StorePositiveNumberAsOddNumber, std::hash<AtomicString>, std::equal_to<AtomicString>,
GCUtil::gc_malloc_allocator<std::pair<AtomicString const, StorePositiveNumberAsOddNumber>>>
GCUtil::gc_malloc_atomic_allocator<std::pair<AtomicString const, size_t>>>
FunctionContextVarMap;

// length of argv is same with NativeFunctionInfo.m_argumentCount
Expand Down
5 changes: 3 additions & 2 deletions src/runtime/DataViewObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ class DataViewObject : public ArrayBufferView {
ErrorObject::throwBuiltinError(state, ErrorCode::RangeError, state.context()->staticStrings().DataView.string(), false, String::emptyString(), ErrorObject::Messages::GlobalObject_InvalidArrayBufferOffset);
}

// Perform coercion first before any buffer state checks
auto numericValue = val.toNumeric(state);
UNUSED_VARIABLE(numericValue);

bool isLittleEndian = _isLittleEndian.toBoolean();
throwTypeErrorIfDetached(state);
Expand All @@ -105,7 +105,8 @@ class DataViewObject : public ArrayBufferView {
}

size_t bufferIndex = numberIndex + viewOffset;
buffer()->setValueInBuffer(state, bufferIndex, type, val, isLittleEndian);
// Pass the already-coerced numeric value to prevent re-coercion in setValueInBuffer
buffer()->setValueInBuffer(state, bufferIndex, type, numericValue.first, isLittleEndian);
}
};
} // namespace Escargot
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/IteratorObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "runtime/AsyncFromSyncIteratorObject.h"
#include "runtime/ScriptAsyncFunctionObject.h"
#include "runtime/StringObject.h"
#include "runtime/ArrayBuffer.h"

namespace Escargot {

Expand Down Expand Up @@ -227,6 +228,11 @@ ValueVectorWithInlineStorage IteratorObject::iterableToList(ExecutionState& stat
if (next.hasValue()) {
Value nextValue = IteratorObject::iteratorValue(state, next.value());
values.pushBack(nextValue);
// Check if the size exceeds the maximum allowed size for TypedArray construction
// This prevents memory exhaustion when iterating over very large sparse arrays
if (values.size() >= ArrayBuffer::maxArrayBufferSize) {
ErrorObject::throwBuiltinError(state, ErrorCode::RangeError, state.context()->staticStrings().TypedArray.string(), false, String::emptyString(), ErrorObject::Messages::GlobalObject_InvalidArrayLength);
}
} else {
break;
}
Expand Down
30 changes: 27 additions & 3 deletions src/runtime/JSON.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,30 @@ struct JSONStringStream {
const Ch* tail_;
};

template <typename JSONCharType>
class JSONDocument : public rapidjson::GenericDocument<JSONCharType> {
public:
JSONDocument(ExecutionState& state)
: m_state(state)
{
}

bool StartObject()
{
CHECK_STACK_OVERFLOW(m_state);
Comment thread
ksh8281 marked this conversation as resolved.
return rapidjson::GenericDocument<JSONCharType>::StartObject();
}

bool StartArray()
{
CHECK_STACK_OVERFLOW(m_state);
return rapidjson::GenericDocument<JSONCharType>::StartArray();
}

private:
ExecutionState& m_state;
};

template <typename CharType, typename JSONCharType>
static Value parseJSONWorker(ExecutionState& state, const rapidjson::GenericValue<JSONCharType>& value)
{
Expand Down Expand Up @@ -156,12 +180,12 @@ static Value parseJSONWorker(ExecutionState& state, const rapidjson::GenericValu
}

template <typename CharType, typename JSONCharType>
static Value parseJSON(ExecutionState& state, const CharType* data, size_t length, rapidjson::GenericDocument<JSONCharType>& jsonDocument)
static Value parseJSON(ExecutionState& state, const CharType* data, size_t length, JSONDocument<JSONCharType>& jsonDocument)
{
auto strings = &state.context()->staticStrings();

JSONStringStream<JSONCharType> stringStream(data, length);
jsonDocument.ParseStream(stringStream);
jsonDocument.template ParseStream<rapidjson::kParseDefaultFlags, JSONCharType, JSONStringStream<JSONCharType>, JSONDocument<JSONCharType>>(stringStream);
if (jsonDocument.HasParseError()) {
ErrorObject::throwBuiltinError(state, ErrorCode::SyntaxError, strings->JSON.string(), true, strings->parse.string(), rapidjson::GetParseError_En(jsonDocument.GetParseError()));
}
Expand Down Expand Up @@ -197,7 +221,7 @@ Value JSON::parse(ExecutionState& state, Value text, Value reviver)

// 1, 2, 3
String* JText = text.toString(state);
rapidjson::GenericDocument<rapidjson::UTF16<char16_t>> parseResult;
JSONDocument<rapidjson::UTF16<char16_t>> parseResult(state);
Value unfiltered;
if (JText->has8BitContent()) {
size_t len = JText->length();
Expand Down
12 changes: 12 additions & 0 deletions src/runtime/StringObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ ObjectGetResult StringObject::getOwnProperty(ExecutionState& state, const Object

bool StringObject::defineOwnProperty(ExecutionState& state, const ObjectPropertyName& P, const ObjectPropertyDescriptor& desc)
{
// Check if this is an index property within the string length
// String index properties are non-configurable and non-writable per ECMAScript spec
// We must reject any attempt to define a property on these indexed positions
size_t idx = P.tryToUseAsIndexProperty();
if (idx != Value::InvalidIndexPropertyValue) {
size_t strLen = m_primitiveValue->length();
if (idx < strLen) {
// Indexed properties within string length are non-configurable
// Per ECMAScript spec, defining a non-configurable property should fail
return false;
}
}
auto r = getOwnProperty(state, P);
if (r.hasValue() && !r.isConfigurable())
return false;
Expand Down
22 changes: 21 additions & 1 deletion third_party/rapidjson/include/rapidjson/document.h
Original file line number Diff line number Diff line change
Expand Up @@ -2063,6 +2063,26 @@ class GenericDocument : public GenericValue<Encoding, Allocator> {

//!@name Parse from stream
//!@{
//! Parse JSON text from an input stream (with Encoding conversion)
/*! \tparam parseFlags Combination of \ref ParseFlag.
\tparam SourceEncoding Encoding of input stream
\tparam InputStream Type of input stream, implementing Stream concept
\param is Input stream to be parsed.
\return The document itself for fluent API.
*/
template <unsigned parseFlags, typename SourceEncoding, typename InputStream, typename Handler>
GenericDocument& ParseStream(InputStream& is)
{
ValueType::SetNull(); // Remove existing root if exist
GenericReader<SourceEncoding, Encoding, StackAllocator> reader(&stack_.GetAllocator());
ClearStackOnExit scope(*this);
parseResult_ = reader.template Parse<parseFlags>(is, (Handler&)*this);
if (parseResult_) {
RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
this->RawAssign(*stack_.template Pop<ValueType>(1)); // Add this-> to prevent issue 13.
}
return *this;
}

//! Parse JSON text from an input stream (with Encoding conversion)
/*! \tparam parseFlags Combination of \ref ParseFlag.
Expand Down Expand Up @@ -2189,7 +2209,7 @@ class GenericDocument : public GenericValue<Encoding, Allocator> {
//! Get the capacity of stack in bytes.
size_t GetStackCapacity() const { return stack_.GetCapacity(); }

private:
protected:
// clear stack on any exit from ParseStream, e.g. due to exception
struct ClearStackOnExit {
explicit ClearStackOnExit(GenericDocument& d)
Expand Down
Loading