Welcome to mirror list, hosted at ThFree Co, Russian Federation.

primordials.md « contributing « doc - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e93d224495a53f42141ce048eaea5965d4cdc1d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# Usage of primordials in core

The file `lib/internal/per_context/primordials.js` subclasses and stores the JS
built-ins that come from the VM so that Node.js built-in modules do not need to
later look these up from the global proxy, which can be mutated by users.

Usage of primordials should be preferred for any new code, but replacing current
code with primordials should be
[done with care](#primordials-with-known-performance-issues). It is highly
recommended to ping the relevant team when reviewing a pull request that touches
one of the subsystems they "own".

## Accessing primordials

The primordials are meant for internal use only, and are only accessible for
internal core modules. User code cannot use or rely on primordials. It is
usually fine to rely on ECMAScript built-ins and assume that it will behave as
specified.

If you would like to access the `primordials` object to help you with Node.js
core development or for tinkering, you can expose it on the global scope using
this combination of CLI flags:

```bash
node --expose-internals -r internal/test/binding
```

## Contents of primordials

### Properties of the global object

Objects and functions on the global object can be deleted or replaced. Using
them from primordials makes the code more reliable:

```js
globalThis.Array === primordials.Array; // true

globalThis.Array = function() {
  return [1, 2, 3];
};
globalThis.Array === primordials.Array; // false

primordials.Array(0); // []
globalThis.Array(0); // [1,2,3]
```

### Prototype methods

ECMAScript provides a group of methods available on built-in objects that are
used to interact with JavaScript objects.

```js
const array = [1, 2, 3];
array.push(4); // Here `push` refers to %Array.prototype.push%.
console.log(JSON.stringify(array)); // [1,2,3,4]

// %Array.prototype%.push is modified in userland.
Array.prototype.push = function push(val) {
  return this.unshift(val);
};

array.push(5); // Now `push` refers to the modified method.
console.log(JSON.stringify(array)); // [5,1,2,3,4]
```

Primordials wrap the original prototype functions with new functions that take
the `this` value as the first argument:

```js
const {
  ArrayPrototypePush,
} = primordials;

const array = [1, 2, 3];
ArrayPrototypePush(array, 4);
console.log(JSON.stringify(array)); // [1,2,3,4]

Array.prototype.push = function push(val) {
  return this.unshift(val);
};

ArrayPrototypePush(array, 5);
console.log(JSON.stringify(array)); // [1,2,3,4,5]
```

### Safe classes

Safe classes are classes that provide the same API as their equivalent class,
but whose implementation aims to avoid any reliance on user-mutable code.
Safe classes should not be exposed to user-land; use unsafe equivalent when
dealing with objects that are accessible from user-land.

### Variadic functions

There are some built-in functions that accept a variable number of arguments
(e.g.: `Math.max`, `%Array.prototype.push%`). It is sometimes useful to provide
the list of arguments as an array. You can use primordial function with the
suffix `Apply` (e.g.: `MathMaxApply`, `ArrayPrototypePushApply`) to do that.

## Primordials with known performance issues

One of the reasons why the current Node.js API is not completely tamper-proof is
performance: sometimes the use of primordials can cause performance regressions
with V8, which when in a hot code path, could significantly decrease the
performance of code in Node.js.

* Methods that mutate the internal state of arrays:
  * `ArrayPrototypePush`
  * `ArrayPrototypePop`
  * `ArrayPrototypeShift`
  * `ArrayPrototypeUnshift`
* Methods of the function prototype:
  * `FunctionPrototypeBind`
  * `FunctionPrototypeCall`: creates performance issues when used to invoke
    super constructors.
  * `FunctionPrototype`: use `() => {}` instead when referencing a no-op
    function.
* `SafeArrayIterator`
* `SafeStringIterator`
* `SafePromiseAll`
* `SafePromiseAllSettled`
* `SafePromiseAny`
* `SafePromiseRace`
* `SafePromisePrototypeFinally`: use `try {} finally {}` block instead.

In general, when sending or reviewing a PR that makes changes in a hot code
path, use extra caution and run extensive benchmarks.

## Implicit use of user-mutable methods

### Unsafe array iteration

There are many usual practices in JavaScript that rely on iteration. It's useful
to be aware of them when dealing with arrays (or `TypedArray`s) in core as array
iteration typically calls several user-mutable methods. This sections lists the
most common patterns in which ECMAScript code relies non-explicitly on array
iteration and how to avoid it.

<details>

<summary>Avoid for-of loops on arrays</summary>

```js
for (const item of array) {
  console.log(item);
}
```

This code is internally expanded into something that looks like:

```js
{
  // 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
  // 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
  // 3. Call that function.
  const iterator = array[Symbol.iterator]();
  // 1. Lookup `next` property on `iterator` (doesn't exist).
  // 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
  // 3. Call that function.
  let { done, value: item } = iterator.next();
  while (!done) {
    console.log(item);
    // Repeat.
    ({ done, value: item } = iterator.next());
  }
}
```

Instead of utilizing iterators, you can use the more traditional but still very
performant `for` loop:

```js
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}
```

The following code snippet illustrates how user-land code could impact the
behavior of internal modules:

```js
// User-land
Array.prototype[Symbol.iterator] = () => ({
  next: () => ({ done: true }),
});

// Core
let forOfLoopBlockExecuted = false;
let forLoopBlockExecuted = false;
const array = [1, 2, 3];
for (const item of array) {
  forOfLoopBlockExecuted = true;
}
for (let i = 0; i < array.length; i++) {
  forLoopBlockExecuted = true;
}
console.log(forOfLoopBlockExecuted); // false
console.log(forLoopBlockExecuted); // true
```

This only applies if you are working with a genuine array (or array-like
object). If you are instead expecting an iterator, a for-of loop may be a better
choice.

</details>

<details>

<summary>Avoid array destructuring assignment on arrays</summary>

```js
const [first, second] = array;
```

This is roughly equivalent to:

```js
// 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
// 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
// 3. Call that function.
const iterator = array[Symbol.iterator]();
// 1. Lookup `next` property on `iterator` (doesn't exist).
// 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
// 3. Call that function.
const first = iterator.next().value;
// Repeat.
const second = iterator.next().value;
```

Instead you can use object destructuring:

```js
const { 0: first, 1: second } = array;
```

or

```js
const first = array[0];
const second = array[1];
```

This only applies if you are working with a genuine array (or array-like
object). If you are instead expecting an iterator, array destructuring is the
best choice.

</details>

<details>

<summary>Avoid spread operator on arrays</summary>

```js
// 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
// 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
// 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
const arrayCopy = [...array];
func(...array);
```

Instead you can use other ECMAScript features to achieve the same result:

```js
const arrayCopy = ArrayPrototypeSlice(array);
ReflectApply(func, null, array);
```

</details>

<details>

<summary><code>%Array.prototype.concat%</code> looks up
         <code>@@isConcatSpreadable</code> property of the passed
         arguments and the <code>this</code> value.</summary>

```js
{
  // Unsafe code example:
  // 1. Lookup @@isConcatSpreadable property on `array` (user-mutable if
  //    user-provided).
  // 2. Lookup @@isConcatSpreadable property on `%Array.prototype%
  //    (user-mutable).
  // 2. Lookup @@isConcatSpreadable property on `%Object.prototype%
  //    (user-mutable).
  const array = [];
  ArrayPrototypeConcat(array);
}
```

```js
// User-land
Object.defineProperty(Object.prototype, Symbol.isConcatSpreadable, {
  get() {
    this.push(5);
    return true;
  },
});

// Core
{
  // Using ArrayPrototypeConcat does not produce the expected result:
  const a = [1, 2];
  const b = [3, 4];
  console.log(ArrayPrototypeConcat(a, b)); // [1, 2, 5, 3, 4, 5]
}
{
  // Concatenating two arrays can be achieved safely, e.g.:
  const a = [1, 2];
  const b = [3, 4];
  // Using %Array.prototype.push% and `SafeArrayIterator` to get the expected
  // outcome:
  const concatArray = [];
  ArrayPrototypePush(concatArray, ...new SafeArrayIterator(a),
                     ...new SafeArrayIterator(b));
  console.log(concatArray); // [1, 2, 3, 4]

  // Or using `ArrayPrototypePushApply` if it's OK to mutate the first array:
  ArrayPrototypePushApply(a, b);
  console.log(a); // [1, 2, 3, 4]
}
```

</details>

<details>

<summary><code>%Object.fromEntries%</code> iterate over an array</summary>

```js
{
  // Unsafe code example:
  // 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
  // 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
  // 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
  const obj = ObjectFromEntries(array);
}

{
  // Safe example using `SafeArrayIterator`:
  const obj = ObjectFromEntries(new SafeArrayIterator(array));
}

{
  // Safe example without using `SafeArrayIterator`:
  const obj = {};
  for (let i = 0; i < array.length; i++) {
    obj[array[i][0]] = array[i][1];
  }
  // In a hot code path, this would be the preferred method.
}
```

</details>

<details>

<summary><code>%Promise.all%</code>,
         <code>%Promise.allSettled%</code>,
         <code>%Promise.any%</code>, and
         <code>%Promise.race%</code> iterate over an array</summary>

```js
// 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
// 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
// 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
PromiseAll(array); // unsafe

PromiseAll(new SafeArrayIterator(array));
SafePromiseAll(array); // safe
```

</details>

<details>

<summary><code>%Map%</code>, <code>%Set%</code>, <code>%WeakMap%</code>, and
         <code>%WeakSet%</code> constructors iterate over an array</summary>

```js
// User-land
Array.prototype[Symbol.iterator] = () => ({
  next: () => ({ done: true }),
});

// Core

// 1. Lookup @@iterator property on %Array.prototype% (user-mutable).
// 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
const set = new SafeSet([1, 2, 3]);

console.log(set.size); // 0
```

```js
// User-land
Array.prototype[Symbol.iterator] = () => ({
  next: () => ({ done: true }),
});

// Core
const set = new SafeSet();
set.add(1).add(2).add(3);
console.log(set.size); // 3
```

</details>

### Promise objects

<details>

<summary><code>%Promise.prototype.finally%</code> looks up <code>then</code>
         property of the Promise instance</summary>

```js
// User-land
Promise.prototype.then = function then(a, b) {
  return Promise.resolve();
};

// Core
let finallyBlockExecuted = false;
PromisePrototypeFinally(somePromiseThatEventuallySettles,
                        () => { finallyBlockExecuted = true; });
process.on('exit', () => console.log(finallyBlockExecuted)); // false
```

```js
// User-land
Promise.prototype.then = function then(a, b) {
  return Promise.resolve();
};

// Core
let finallyBlockExecuted = false;
(async () => {
  try {
    return await somePromiseThatEventuallySettles;
  } finally {
    finallyBlockExecuted = true;
  }
})();
process.on('exit', () => console.log(finallyBlockExecuted)); // true
```

</details>

<details>

<summary><code>%Promise.all%</code>,
         <code>%Promise.allSettled%</code>,
         <code>%Promise.any%</code>, and
         <code>%Promise.race%</code> look up <code>then</code>
         property of the Promise instances</summary>

You can use safe alternatives from primordials that differ slightly from the
original methods:

* It expects an array (or array-like object) instead of an iterable.
* It wraps each promise in `SafePromise` objects and wraps the result in a new
  `Promise` instance – which may come with a performance penalty.
* Because it doesn't look up `then` property, it may not be the right tool to
  handle user-provided promises (which may be instances of a subclass of
  `Promise`).

```js
// User-land
Promise.prototype.then = function then(a, b) {
  return Promise.resolve();
};

// Core
let thenBlockExecuted = false;
PromisePrototypeThen(
  PromiseAll(new SafeArrayIterator([PromiseResolve()])),
  () => { thenBlockExecuted = true; }
);
process.on('exit', () => console.log(thenBlockExecuted)); // false
```

```js
// User-land
Promise.prototype.then = function then(a, b) {
  return Promise.resolve();
};

// Core
let thenBlockExecuted = false;
PromisePrototypeThen(
  SafePromiseAll([PromiseResolve()]),
  () => { thenBlockExecuted = true; }
);
process.on('exit', () => console.log(thenBlockExecuted)); // true
```

</details>

### (Async) Generator functions

Generators and async generators returned by generator functions and async
generator functions are relying on user-mutable methods; their use in core
should be avoided.

<details>

<summary><code>%GeneratorFunction.prototype.prototype%.next</code> is
         user-mutable</summary>

```js
// User-land
Object.getPrototypeOf(function* () {}).prototype.next = function next() {
  return { done: true };
};

// Core
function* someGenerator() {
  yield 1;
  yield 2;
  yield 3;
}
let loopCodeExecuted = false;
for (const nb of someGenerator()) {
  loopCodeExecuted = true;
}
console.log(loopCodeExecuted); // false
```

</details>

<details>

<summary><code>%AsyncGeneratorFunction.prototype.prototype%.next</code> is
         user-mutable</summary>

```js
// User-land
Object.getPrototypeOf(async function* () {}).prototype.next = function next() {
  return new Promise(() => {});
};

// Core
async function* someGenerator() {
  yield 1;
  yield 2;
  yield 3;
}
let finallyBlockExecuted = false;
async () => {
  try {
    for await (const nb of someGenerator()) {
      // some code;
    }
  } finally {
    finallyBlockExecuted = true;
  }
};
process.on('exit', () => console.log(finallyBlockExecuted)); // false
```

</details>

### Text processing

#### Unsafe string methods

| The string method             | looks up the property |
| ----------------------------- | --------------------- |
| `String.prototype.match`      | `Symbol.match`        |
| `String.prototype.matchAll`   | `Symbol.matchAll`     |
| `String.prototype.replace`    | `Symbol.replace`      |
| `String.prototype.replaceAll` | `Symbol.replace`      |
| `String.prototype.search`     | `Symbol.search`       |
| `String.prototype.split`      | `Symbol.split`        |

```js
// User-land
RegExp.prototype[Symbol.replace] = () => 'foo';
String.prototype[Symbol.replace] = () => 'baz';

// Core
console.log(StringPrototypeReplace('ber', /e/, 'a')); // 'foo'
console.log(StringPrototypeReplace('ber', 'e', 'a')); // 'baz'
console.log(RegExpPrototypeSymbolReplace(/e/, 'ber', 'a')); // 'bar'
```

#### Unsafe string iteration

As with arrays, iterating over strings calls several user-mutable methods. Avoid
iterating over strings when possible, or use `SafeStringIterator`.

#### Unsafe `RegExp` methods

Functions that lookup the `exec` property on the prototype chain:

* `RegExp.prototype[Symbol.match]`
* `RegExp.prototype[Symbol.matchAll]`
* `RegExp.prototype[Symbol.replace]`
* `RegExp.prototype[Symbol.search]`
* `RegExp.prototype[Symbol.split]`
* `RegExp.prototype.test`

```js
// User-land
RegExp.prototype.exec = () => null;

// Core
console.log(RegExpPrototypeTest(/o/, 'foo')); // false
console.log(RegExpPrototypeExec(/o/, 'foo') !== null); // true
```

#### Don't trust `RegExp` flags

RegExp flags are not own properties of the regex instances, which means flags
can be reset from user-land.

<details>

<summary>List of <code>RegExp</code> methods that look up properties from
         mutable getters</summary>

| `RegExp` method                | looks up the following flag-related properties                     |
| ------------------------------ | ------------------------------------------------------------------ |
| `get RegExp.prototype.flags`   | `global`, `ignoreCase`, `multiline`, `dotAll`, `unicode`, `sticky` |
| `RegExp.prototype[@@match]`    | `global`, `unicode`                                                |
| `RegExp.prototype[@@matchAll]` | `flags`                                                            |
| `RegExp.prototype[@@replace]`  | `global`, `unicode`                                                |
| `RegExp.prototype[@@split]`    | `flags`                                                            |
| `RegExp.prototype.toString`    | `flags`                                                            |

</details>

```js
// User-land
Object.defineProperty(RegExp.prototype, 'global', { value: false });

// Core
console.log(RegExpPrototypeSymbolReplace(/o/g, 'foo', 'a')); // 'fao'

const regex = /o/g;
ObjectDefineProperties(regex, {
  dotAll: { value: false },
  exec: { value: undefined },
  flags: { value: 'g' },
  global: { value: true },
  ignoreCase: { value: false },
  multiline: { value: false },
  unicode: { value: false },
  sticky: { value: false },
});
console.log(RegExpPrototypeSymbolReplace(regex, 'foo', 'a')); // 'faa'
```

### Defining object own properties

When defining property descriptor (to add or update an own property to a
JavaScript object), be sure to always use a null-prototype object to avoid
prototype pollution.

```js
// User-land
Object.prototype.get = function get() {};

// Core
try {
  ObjectDefineProperty({}, 'someProperty', { value: 0 });
} catch (err) {
  console.log(err); // TypeError: Invalid property descriptor.
}
```

```js
// User-land
Object.prototype.get = function get() {};

// Core
ObjectDefineProperty({}, 'someProperty', { __proto__: null, value: 0 });
console.log('no errors'); // no errors.
```

Same applies when trying to modify an existing property, e.g. trying to make a
read-only property enumerable:

```js
// User-land
Object.prototype.value = 'Unrelated user-provided data';

// Core
class SomeClass {
  get readOnlyProperty() { return 'genuine data'; }
}
ObjectDefineProperty(SomeClass.prototype, 'readOnlyProperty', { enumerable: true });
console.log(new SomeClass().readOnlyProperty); // Unrelated user-provided data
```

```js
// User-land
Object.prototype.value = 'Unrelated user-provided data';

// Core
const kEnumerableProperty = { __proto__: null, enumerable: true };
// In core, use const {kEnumerableProperty} = require('internal/util');
class SomeClass {
  get readOnlyProperty() { return 'genuine data'; }
}
ObjectDefineProperty(SomeClass.prototype, 'readOnlyProperty', kEnumerableProperty);
console.log(new SomeClass().readOnlyProperty); // genuine data
```

### Defining a `Proxy` handler

When defining a `Proxy`, the handler object could be at risk of prototype
pollution when using a plain object literal:

```js
// User-land
Object.prototype.get = () => 'Unrelated user-provided data';

// Core
const objectToProxy = { someProperty: 'genuine value' };

const proxyWithPlainObjectLiteral = new Proxy(objectToProxy, {
  has() { return false; },
});
console.log(proxyWithPlainObjectLiteral.someProperty); // Unrelated user-provided data

const proxyWithNullPrototypeObject = new Proxy(objectToProxy, {
  __proto__: null,
  has() { return false; },
});
console.log(proxyWithNullPrototypeObject.someProperty); // genuine value
```