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
10 changes: 8 additions & 2 deletions lib/internal/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -1220,13 +1220,19 @@ class URL {
url = `${url}`;
}

// canParseFast() returns -1 when the regular binding is needed.
if (base !== undefined) {
return bindingUrl.canParse(url, typeof base === 'string' ? base : `${base}`);
if (typeof base !== 'string') {
base = `${base}`;
}
const result = bindingUrl.canParseFast(url, base);
return result === -1 ? bindingUrl.canParse(url, base) : result === 1;
}

// It is important to differentiate the canParse call statements
// since they resolve into different v8 fast api overloads.
return bindingUrl.canParse(url);
const result = bindingUrl.canParseFast(url);
return result === -1 ? bindingUrl.canParse(url) : result === 1;
}
}

Expand Down
15 changes: 12 additions & 3 deletions lib/zlib.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ const {
isUint8Array,
} = require('internal/util/types');
const binding = internalBinding('zlib');
const { crc32: crc32Native, crc32c: crc32cNative } = binding;
const {
crc32: crc32String,
crc32c: crc32cString,
crc32Buffer,
crc32cBuffer,
} = binding;
const assert = require('internal/assert');
const {
Buffer,
Expand Down Expand Up @@ -1276,7 +1281,10 @@ function crc32(data, value = 0) {
validateUint32(value, 'value');
// Coerce -0 to +0.
value += 0;
return crc32Native(data, value);
// Strings use a regular binding: reading them may flatten (allocate),
// which must not happen inside a value-returning fast API call.
return typeof data === 'string' ?
crc32String(data, value) : crc32Buffer(data, value);
}

function crc32c(data, value = 0) {
Expand All @@ -1286,7 +1294,8 @@ function crc32c(data, value = 0) {
validateUint32(value, 'value');
// Coerce -0 to +0.
value += 0;
return crc32cNative(data, value);
return typeof data === 'string' ?
crc32cString(data, value) : crc32cBuffer(data, value);
}

// Legacy alias on the C++ wrapper object. This is not public API, so we may
Expand Down
69 changes: 31 additions & 38 deletions src/node_url.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ namespace url {

using v8::CFunction;
using v8::Context;
using v8::FastApiCallbackOptions;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
Expand Down Expand Up @@ -323,45 +322,34 @@ void BindingData::CanParse(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(can_parse);
}

bool BindingData::FastCanParse(
Local<Value> receiver,
Local<Value> input,
// NOLINTNEXTLINE(runtime/references) This is V8 api.
FastApiCallbackOptions& options) {
// The fast API's slow fallback must not convert or flatten strings either: it
// uses the same unsupported lazy-deoptimization continuation as the fast
// callbacks. Return a Smi sentinel so JavaScript calls the regular binding.
void BindingData::CanParseFastFallback(
const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(-1);
}

int32_t BindingData::FastCanParse(Local<Value> receiver,
const v8::FastOneByteString& input) {
TRACK_V8_FAST_API_CALL("url.canParse");
auto isolate = options.isolate;
HandleScope handleScope(isolate);
Local<String> str;
if (!input->ToString(isolate->GetCurrentContext()).ToLocal(&str)) {
return false;
}
Utf8Value utf8(isolate, str);
return ada::can_parse(utf8.ToStringView());
// Latin-1 is only UTF-8 compatible for ASCII.
if (!simdutf::validate_ascii(input.data, input.length)) return -1;
return ada::can_parse(std::string_view(input.data, input.length)) ? 1 : 0;
}

bool BindingData::FastCanParseWithBase(
Local<Value> receiver,
Local<Value> input,
Local<Value> base,
// NOLINTNEXTLINE(runtime/references) This is V8 api.
FastApiCallbackOptions& options) {
int32_t BindingData::FastCanParseWithBase(Local<Value> receiver,
const v8::FastOneByteString& input,
const v8::FastOneByteString& base) {
TRACK_V8_FAST_API_CALL("url.canParse.withBase");
auto isolate = options.isolate;
HandleScope handleScope(isolate);
auto context = isolate->GetCurrentContext();
Local<String> input_str;
if (!input->ToString(context).ToLocal(&input_str)) {
return false;
}
Local<String> base_str;
if (!base->ToString(context).ToLocal(&base_str)) {
return false;
}
Utf8Value input_utf8(isolate, input_str);
Utf8Value base_utf8(isolate, base_str);

auto base_view = base_utf8.ToStringView();
return ada::can_parse(input_utf8.ToStringView(), &base_view);
if (!simdutf::validate_ascii(input.data, input.length) ||
!simdutf::validate_ascii(base.data, base.length)) {
return -1;
}
std::string_view base_view(base.data, base.length);
return ada::can_parse(std::string_view(input.data, input.length), &base_view)
? 1
: 0;
}

CFunction BindingData::fast_can_parse_methods_[] = {
Expand Down Expand Up @@ -589,8 +577,12 @@ void BindingData::CreatePerIsolateProperties(IsolateData* isolate_data,
SetMethod(isolate, target, "parse", Parse);
SetMethod(isolate, target, "pathToFileURL", PathToFileURL);
SetMethod(isolate, target, "update", Update);
SetFastMethodNoSideEffect(
isolate, target, "canParse", CanParse, {fast_can_parse_methods_, 2});
SetMethodNoSideEffect(isolate, target, "canParse", CanParse);
SetFastMethodNoSideEffect(isolate,
target,
"canParseFast",
CanParseFastFallback,
{fast_can_parse_methods_, 2});
}

void BindingData::CreatePerContextProperties(Local<Object> target,
Expand All @@ -611,6 +603,7 @@ void BindingData::RegisterExternalReferences(
registry->Register(PathToFileURL);
registry->Register(Update);
registry->Register(CanParse);
registry->Register(CanParseFastFallback);
for (const CFunction& method : fast_can_parse_methods_) {
registry->Register(method);
}
Expand Down
17 changes: 7 additions & 10 deletions src/node_url.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,13 @@ class BindingData : public SnapshotableObject {
static void DomainToUnicode(const v8::FunctionCallbackInfo<v8::Value>& args);

static void CanParse(const v8::FunctionCallbackInfo<v8::Value>& args);
static bool FastCanParse(v8::Local<v8::Value> receiver,
v8::Local<v8::Value> input,
// NOLINTNEXTLINE(runtime/references) This is V8 api.
v8::FastApiCallbackOptions& options);
static bool FastCanParseWithBase(
v8::Local<v8::Value> receiver,
v8::Local<v8::Value> input,
v8::Local<v8::Value> base,
// NOLINTNEXTLINE(runtime/references) This is V8 api.
v8::FastApiCallbackOptions& options);
static void CanParseFastFallback(
const v8::FunctionCallbackInfo<v8::Value>& args);
static int32_t FastCanParse(v8::Local<v8::Value> receiver,
const v8::FastOneByteString& input);
static int32_t FastCanParseWithBase(v8::Local<v8::Value> receiver,
const v8::FastOneByteString& input,
const v8::FastOneByteString& base);

static void Format(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetOrigin(const v8::FunctionCallbackInfo<v8::Value>& args);
Expand Down
29 changes: 25 additions & 4 deletions src/node_zlib.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2137,14 +2137,22 @@ static void CRC32(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(CRC32Impl(args.GetIsolate(), args[0], value));
}

// Strings use CRC32 above: the fast API path must not flatten them.
static void CRC32Buffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsArrayBufferView());
CHECK(args[1]->IsUint32());
uint32_t value = args[1].As<v8::Uint32>()->Value();
args.GetReturnValue().Set(CRC32Impl(args.GetIsolate(), args[0], value));
}

static uint32_t FastCRC32(v8::Local<v8::Value> receiver,
v8::Local<v8::Value> data,
uint32_t value,
// NOLINTNEXTLINE(runtime/references)
v8::FastApiCallbackOptions& options) {
TRACK_V8_FAST_API_CALL("zlib.crc32");
v8::HandleScope handle_scope(options.isolate);
CHECK(data->IsArrayBufferView() || data->IsString());
CHECK(data->IsArrayBufferView());
return CRC32Impl(options.isolate, data, value);
}

Expand All @@ -2167,14 +2175,21 @@ static void CRC32C(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(CRC32CImpl(args.GetIsolate(), args[0], value));
}

static void CRC32CBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsArrayBufferView());
CHECK(args[1]->IsUint32());
uint32_t value = args[1].As<v8::Uint32>()->Value();
args.GetReturnValue().Set(CRC32CImpl(args.GetIsolate(), args[0], value));
}

static uint32_t FastCRC32C(v8::Local<v8::Value> receiver,
v8::Local<v8::Value> data,
uint32_t value,
// NOLINTNEXTLINE(runtime/references)
v8::FastApiCallbackOptions& options) {
TRACK_V8_FAST_API_CALL("zlib.crc32c");
v8::HandleScope handle_scope(options.isolate);
CHECK(data->IsArrayBufferView() || data->IsString());
CHECK(data->IsArrayBufferView());
return CRC32CImpl(options.isolate, data, value);
}

Expand All @@ -2192,8 +2207,12 @@ void Initialize(Local<Object> target,
MakeClass<ZstdCompressStream>::Make(env, target, "ZstdCompress");
MakeClass<ZstdDecompressStream>::Make(env, target, "ZstdDecompress");

SetFastMethodNoSideEffect(context, target, "crc32", CRC32, &fast_crc32_);
SetFastMethodNoSideEffect(context, target, "crc32c", CRC32C, &fast_crc32c_);
SetMethodNoSideEffect(context, target, "crc32", CRC32);
SetMethodNoSideEffect(context, target, "crc32c", CRC32C);
SetFastMethodNoSideEffect(
context, target, "crc32Buffer", CRC32Buffer, &fast_crc32_);
SetFastMethodNoSideEffect(
context, target, "crc32cBuffer", CRC32CBuffer, &fast_crc32c_);
target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(), "ZLIB_VERSION"),
FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION)).Check();
Expand All @@ -2206,8 +2225,10 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
MakeClass<ZstdCompressStream>::Make(registry);
MakeClass<ZstdDecompressStream>::Make(registry);
registry->Register(CRC32);
registry->Register(CRC32Buffer);
registry->Register(fast_crc32_);
registry->Register(CRC32C);
registry->Register(CRC32CBuffer);
registry->Register(fast_crc32c_);
}

Expand Down
61 changes: 61 additions & 0 deletions test/parallel/test-fast-api-calls-gc-lazy-deopt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Flags: --allow-natives-syntax --expose-gc --no-incremental-marking
'use strict';

// A value-returning fast API callback that allocates (e.g. by flattening a
// string) can run a GC that marks its optimized caller for lazy deopt, which
// V8 does not support and turns into an abort ("Lazy deopt after a fast API
// call with return value is unsupported").

require('../common');
const assert = require('assert');
const zlib = require('zlib');

const cases = {
'Buffer.byteLength': (s) => Buffer.byteLength(s, 'utf8'),
'zlib.crc32': (s) => zlib.crc32(s),
'zlib.crc32c': (s) => zlib.crc32c(s),
'URL.canParse': (s) => URL.canParse(s),
'URL.canParse with base': (s) => URL.canParse(s, 'http://example.com/'),
};

for (const [name, call] of Object.entries(cases)) {
for (const unit of ['abcdefgh', 'aé中']) {
const state = { current: undefined };
// Only object with map "dying": once dropped, the next full GC clears the
// map that the optimized caller embeds weakly.
let dying = { x: 1, dying: true };
const keep = { x: 1, keep: true };

// `eval` keeps each case's caller distinct for the optimizer.
const caller = eval(`(function caller(s) {
const result = call(s);
return [result, state.current.x]; // Polymorphic map check after the call.
})`);

eval('%PrepareFunctionForOptimization(caller)');
for (let i = 0; i < 10; i++) {
state.current = i % 2 ? keep : dying;
caller('http://example.com/' + i);
}
eval('%OptimizeFunctionOnNextCall(caller)');
caller('http://example.com/');
state.current = keep;
dying = null;

// Non-flat old-space strings: flattening them inside the call eventually
// triggers a full GC there.
const half = unit.repeat(256 * 1024);
const strings = [];
for (let i = 0; i < 16; i++) {
strings.push('http://example.com/' + half + String(i) + half);
}
globalThis.gc();
globalThis.gc();

for (let i = 0; i < strings.length; i++) {
const [result] = caller(strings[i]);
assert.strictEqual(result, call(strings[i]), `${name} (${i})`);
strings[i] = null;
}
}
}
2 changes: 2 additions & 0 deletions typings/internalBinding/url.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export interface URLBinding {
domainToUnicode(input: string): string;
canParse(input: string): boolean;
canParse(input: string, base: string): boolean;
canParseFast(input: string): -1 | 0 | 1;
canParseFast(input: string, base: string): -1 | 0 | 1;
format(input: string, fragment?: boolean, unicode?: boolean, search?: boolean, auth?: boolean): string;
parse(input: string, base?: string): string | false;
update(input: string, actionType: typeof urlUpdateActions, value: string): string | false;
Expand Down
2 changes: 2 additions & 0 deletions typings/internalBinding/zlib.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,6 @@ export interface ZlibBinding {
ZstdDecompress: typeof InternalZlibBinding.ZstdDecompress;
crc32(data: string | ArrayBufferView, value: number): number;
crc32c(data: string | ArrayBufferView, value: number): number;
crc32Buffer(data: ArrayBufferView, value: number): number;
crc32cBuffer(data: ArrayBufferView, value: number): number;
}
Loading