diff --git a/.github/workflows/build-android.yaml b/.github/workflows/build-android.yaml
deleted file mode 100644
index 9d2ad65c..00000000
--- a/.github/workflows/build-android.yaml
+++ /dev/null
@@ -1,37 +0,0 @@
-name: Build Android Project
-on:
- push:
- branches: [ unstable ]
- pull_request:
- branches: [ unstable ]
-
-jobs:
- build:
- runs-on: ubuntu-latest
- steps:
- - name: Clone repo
- uses: actions/checkout@v2
- - name: Installing JDK 8
- uses: actions/setup-java@v2
- with:
- distribution: 'zulu'
- java-version: '8'
- - name: Installing Cordova!
- run: |
- sudo npm i cordova@10.0.0 -g
- - name: Installing the npm dependencies!
- run: |
- cd testapp
- npm i
- - name: Copying nodejs-mobile-cordova plugin
- run: |
- cd testapp
- npm run copy-module
- - name: Preparing the Android project!
- run: |
- cd testapp
- cordova prepare android
- - name: Building the Android project!
- run: |
- cd testapp
- cordova build android
diff --git a/.github/workflows/build-ios.yaml b/.github/workflows/build-ios.yaml
deleted file mode 100644
index 8d91f3f6..00000000
--- a/.github/workflows/build-ios.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-name: Build IOS Project
-on:
- push:
- branches: [ unstable ]
- pull_request:
- branches: [ unstable ]
-
-jobs:
- build:
- runs-on: macOS-latest
- steps:
- - name: Clone repo
- uses: actions/checkout@v2
- - name: Installing Cordova!
- run: |
- sudo npm i cordova@10.0.0 -g
- - name: Installing the npm dependencies!
- run: |
- cd testapp
- npm i
- - name: Copying nodejs-mobile-cordova plugin
- run: |
- cd testapp
- npm run copy-module
- - name: Preparing the IOS project!
- run: |
- cd testapp
- cordova prepare ios
- - name: Building the ISO project!
- run: |
- cd testapp
- cordova build ios
diff --git a/.gitignore b/.gitignore
index 49260768..8fcb5408 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
.vscode/
-node_modules/
\ No newline at end of file
+node_modules/
+package-lock.json
diff --git a/.node-version b/.node-version
new file mode 100644
index 00000000..72e4a483
--- /dev/null
+++ b/.node-version
@@ -0,0 +1 @@
+18.14.2
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 00000000..a79584db
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,15 @@
+# Testing, code coverage, and linting
+.eslintignore
+.eslintrc.yml
+.jshinrc
+
+# Git
+.git
+.gitattributes
+.gitignore
+
+# Github
+.github
+
+# test
+tests/
diff --git a/README.md b/README.md
index feb1eec1..7171cb1a 100644
--- a/README.md
+++ b/README.md
@@ -3,24 +3,23 @@
## Installation
```bash
-$ cordova plugin add nodejs-mobile-cordova
+% cordova plugin add nodejs-mobile-cordova
```
## Requirements
- - Cordova 9.x or higher
- - iOS 11 or higher
- - Android API 22 or higher
+- Cordova 12.x or higher
+- Android API 24 or higher
When building an application for the Android platform, make sure you have the [Android NDK](https://developer.android.com/ndk/index.html) installed and the environment variable `ANDROID_NDK_HOME` set, for example:
+
```bash
-$ export ANDROID_NDK_HOME=/Users/username/Library/Android/sdk/ndk-bundle
+% export ANDROID_NDK_HOME=/Users/username/Library/Android/sdk/ndk-bundle
```
## Supported Platforms
-- Android (ARMv7a, x86)
-- iOS (ARM64)
+- Android (ARMv7a, ARM64)
## Reporting Issues
@@ -30,6 +29,7 @@ So please, open the issue [there](https://github.com/janeasystems/nodejs-mobile/
## Methods available in the Cordova layer
These methods can be called from the Cordova javascript code directly:
+
- `nodejs.start`
- `nodejs.startWithScript`
- `nodejs.channel.on`
@@ -43,9 +43,9 @@ These methods can be called from the Cordova javascript code directly:
| Param | Type |
| --- | --- |
-| scriptFileName | string |
-| callback | function |
-| options | [StartupOptions](#cordova.StartupOptions) |
+| scriptFileName | `string` |
+| callback | `function` |
+| options | `[StartupOptions](#cordova.StartupOptions)` |
Starts the nodejs-mobile runtime thread with a file inside the `nodejs-project` directory.
@@ -53,9 +53,9 @@ Starts the nodejs-mobile runtime thread with a file inside the `nodejs-project`
| Param | Type |
| --- | --- |
-| scriptBody | string |
-| callback | function |
-| options | [StartupOptions](#cordova.StartupOptions) |
+| scriptBody | `string` |
+| callback | `function` |
+| options | `[StartupOptions](#cordova.StartupOptions)` |
Starts the nodejs-mobile runtime thread with a script body.
@@ -63,8 +63,8 @@ Starts the nodejs-mobile runtime thread with a script body.
| Param | Type |
| --- | --- |
-| event | string |
-| callback | [function](#cordova.channelCallback) |
+| event | `string` |
+| callback | `[function](#cordova.channelCallback)` |
Registers a callback for user-defined events raised from the nodejs-mobile side.
@@ -72,7 +72,7 @@ Registers a callback for user-defined events raised from the nodejs-mobile side.
| Param | Type |
| --- | --- |
-| event | string |
+| event | `string` |
| message | any JS type that can be serialized with `JSON.stringify` and deserialized with `JSON.parse` |
Raises a user-defined event on the nodejs-mobile side.
@@ -81,7 +81,7 @@ Raises a user-defined event on the nodejs-mobile side.
| Param | Type |
| --- | --- |
-| listenerCallback | [function](#cordova.channelCallback) |
+| listenerCallback | `[function](#cordova.channelCallback)` |
Registers a callback for 'message' events raised from the nodejs-mobile side.
It is an alias for `nodejs.channel.on('message', listenerCallback);`.
@@ -95,11 +95,11 @@ It is an alias for `nodejs.channel.on('message', listenerCallback);`.
Raises a 'message' event on the nodejs-mobile side.
It is an alias for `nodejs.channel.post('message', message);`.
-
-### StartupOptions: object
+### StartupOptions: `object`
+
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| redirectOutputToLogcat | boolean | true | Allows to disable the redirection of the Node stdout/stderr to the Android logcat |
+| redirectOutputToLogcat | `boolean` | `true` | Allows to disable the redirection of the Node stdout/stderr to the Android logcat |
Note: the stdout/stderr redirection is applied to the whole application, the side effect is that some undesired/duplicated output may appear in the logcat.
For example, the Chromium console output `I/chromium: [INFO:CONSOLE(xx)]` is also sent to stderr and will show up in logcat has well, with the `NODEJS-MOBILE` log tag.
@@ -107,6 +107,7 @@ For example, the Chromium console output `I/chromium: [INFO:CONSOLE(xx)]` is als
## Methods available in the Node layer
The following methods can be called from the Node javascript code through the `cordova-bridge` module:
+
```js
var cordova = require('cordova-bridge');
```
@@ -123,12 +124,13 @@ The following methods can be called from the Node javascript code through the `c
| Param | Type |
| --- | --- |
-| event | string |
-| callback | [function](#cordova.channelCallback) |
+| event | `string` |
+| callback | `[function](#cordova.channelCallback)` |
Registers a callback for user-defined events raised from the cordova side.
-> To receive messages from `nodejs.channel.send`, use:
+> To receive messages from `nodejs.channel.send`, use
+>
> ```js
> cordova.channel.on('message', listenerCallback);
> ```
@@ -137,7 +139,7 @@ Registers a callback for user-defined events raised from the cordova side.
| Param | Type |
| --- | --- |
-| event | string |
+| event | `string` |
| message | any JS type that can be serialized with `JSON.stringify` and deserialized with `JSON.parse` |
Raises a user-defined event on the cordova side.
@@ -155,8 +157,8 @@ It is an alias for `cordova.channel.post('message', message);`.
| Param | Type |
| --- | --- |
-| event | string |
-| callback | function |
+| event | `string` |
+| callback | `function` |
Registers callbacks for App events.
Currently supports the 'pause' and 'resume' events, which are raised automatically when the app switches to the background/foreground.
@@ -188,8 +190,8 @@ cordova.app.on('pause', (pauseLock) => {
Returns a writable path used for persistent data storage in the application. Its value corresponds to `NSDocumentDirectory` on iOS and `FilesDir` on Android.
-
-### Channel callback: function(arg)
+### Channel callback: `function(arg)`
+
| Name | Type |
| --- | --- |
| arg | any JS type that can be serialized with `JSON.stringify` and deserialized with `JSON.parse` |
@@ -208,39 +210,53 @@ The Android OS doesn't define a temporary directory for the system or applicatio
This shows how to build an iOS app that exchanges text messages between the Cordova layer and the Node.js layer.
In macOS, using `Terminal`:
+
```bash
-$ cordova create HelloCordova
-$ cd HelloCordova
-$ cordova platform add ios
-$ cordova plugin add nodejs-mobile-cordova
-$ cordova plugin add cordova-plugin-console
+% cordova create HelloCordova
+% cd HelloCordova
+% cordova platform add ios
+% cordova plugin add nodejs-mobile-cordova
+% cordova plugin add cordova-plugin-console
```
+
You can either manually create the `./www/nodejs-project/` folder, the `./www/nodejs-project/main.js` file and edit `./www/js/index.js` or use the provided helper script to do it automatically. The helper script copies a more extended sample compared to the one provided with the manual steps.
---
-#### Set up project files using the helper script
+
+### Set up project files using the helper script
+
If you choose to use the helper script, you will be asked to overwrite the existing `./www/js/index.js` file:
+
```bash
-$ ./plugins/nodejs-mobile-cordova/install/sample-project/copy-sample-project.sh
-$ overwrite www/js/index.js? (y/n [n]) y
+./plugins/@red-mobile/nodejs-mobile-cordova/install/sample-project/copy-sample-project.sh
+overwrite www/js/index.js? (y/n [n]) y
```
+
The script creates the `./www/nodejs-project/` folder and adds two files:
- - `./www/nodejs-project/main.js`
- - `./www/nodejs-project/package.json`
+
+- `./www/nodejs-project/main.js`
+- `./www/nodejs-project/package.json`
The changes in `./www/js/index.js` are needed to invoke Node.js for Mobile Apps from Cordova.
---
-#### Set up project files using the manual steps
+
+### Set up project files using the manual steps
+
If you want to set up the project manually, first create the project folder for the Node.js files:
+
```bash
-$ mkdir www/nodejs-project
+% mkdir www/nodejs-project
```
+
Then, with your editor of choice (we use VS Code in this example) create the `main.js` script file:
+
```bash
-$ code www/nodejs-project/main.js
+% code www/nodejs-project/main.js
```
+
Add the following code to `main.js` and save the file:
+
```js
const cordova = require('cordova-bridge');
@@ -249,11 +265,15 @@ cordova.channel.on('message', function (msg) {
cordova.channel.send('Replying to this message: ' + msg);
});
```
+
Edit the cordova script file `www/js/index.js`:
+
+```bash
+% code `./www/js/index.js`
```
-$ code `./www/js/index.js`
-```
+
Append the following code at the end of the file:
+
```js
function channelListener(msg) {
console.log('[cordova] received:' + msg);
@@ -278,36 +298,45 @@ function startNodeProject() {
```
Search for the `onDeviceReady` event and in the event handler add a call to `startNodeProject()`:
+
```js
onDeviceReady: function() {
this.receivedEvent('deviceready');
startNodeProject();
},
```
+
Save the changes to the `www/js/index.js` file to complete the manual steps of setting up the project files.
---
After the project files have been created, either manually or using the helper script, open the Cordova app project in Xcode:
+
```bash
-$ open platforms/ios/HelloCordova.xcodeproj
+% open platforms/ios/HelloCordova.xcodeproj
```
+
Switch to Xcode:
- * select HelloCordova to view the project settings
- * in the `General` settings:
- * in the `Signing` section select a team to sign the app
- * in `Deployment Info` section select `Deployment Target` `11.0` or higher
+
+- select HelloCordova to view the project settings
+- in the `General` settings:
+ - in the `Signing` section select a team to sign the app
+ - in `Deployment Info` section select `Deployment Target` `11.0` or higher
Go back to `Terminal` to build the Cordova app
+
```bash
-$ cordova build ios --device
+% cordova build ios --device
```
+
Switch to Xcode:
- * select a target device for the project
- * run the project
- * enlarge the `Console` area and scroll to the bottom
- If you created the project following the manual steps, the output will look like this:
+- select a target device for the project
+- run the project
+- enlarge the `Console` area and scroll to the bottom
+
+If you created the project following the manual steps, the output will look like this:
+
```bash
2017-10-02 18:49:18.606100+0200 HelloCordova[2182:1463518] Node.js Mobile Engine Started
[node] received: Hello from Cordova!
@@ -315,7 +344,8 @@ Switch to Xcode:
```
If you used the helper script, the output will look like this:
-```
+
+```bash
2018-02-26 09:18:21.178612+0100 HelloCordova[1089:957630] Node.js Mobile Engine started
2018-02-26 09:18:21.385605+0100 HelloCordova[1089:957630] [cordova] MESSAGE from Node: "main.js loaded"
2018-02-26 09:18:21.385760+0100 HelloCordova[1089:957630] [cordova] "STARTED" event received from Node
@@ -326,16 +356,18 @@ If you used the helper script, the output will look like this:
```
## Node Modules
+
Node modules can be added to the project using `npm`.
The Node modules have to be installed in the `./www/nodejs-project/` folder and a `package.json` file needs to be added to the folder.
If you used the helper script to install the sample project, the `package.json` file is already present and you can proceed adding the desired Node modules.
-If you don't know how to create the `package.json` file, just copy the sample one from `./plugins/nodejs-mobile-cordova/install/sample-project/www/nodejs-project/package.json`.
+If you don't know how to create the `package.json` file, just copy the sample one from `./plugins/@red-mobile/nodejs-mobile-cordova/install/sample-project/www/nodejs-project/package.json`.
Then proceed with the installation of the Node modules you want to add to your Node.js project:
-```
-$ cd www/nodejs-project/
-$ npm install module-name
+
+```bash
+% cd www/nodejs-project/
+% npm install module-name
```
Rebuild your Cordova project so that the newly added Node modules are added to the Cordova application.
@@ -353,10 +385,12 @@ The plugin automatically detects native modules in `./www/nodejs-project/` by se
Building native modules for Android can take a long time, since it depends on building a standalone NDK toolchain for each required architecture. The resulting `.node` binaries are then included in the final application in a separate asset path for each architecture and the correct one will be chosen at runtime.
While the plugin tries to detect automatically the presence of native modules, there's a way to override this detection and turn the native modules build process on or off, by creating the `www/NODEJS_MOBILE_BUILD_NATIVE_MODULES_VALUE.txt` file and setting its contents to `1` or `0` respectively. E.g., from the root path of your project:
+
```sh
echo "1" > www/NODEJS_MOBILE_BUILD_NATIVE_MODULES_VALUE.txt
cordova run android
```
+
```sh
echo "1" > www/NODEJS_MOBILE_BUILD_NATIVE_MODULES_VALUE.txt
cordova run ios
@@ -367,7 +401,8 @@ cordova run ios
### Android
If the installed Android NDK version is `>= r18`, the following error can occur while building for Android:
-```
+
+```sh
FAILURE: Build failed with an exception.
* What went wrong:
@@ -380,16 +415,18 @@ This is caused by the Gradle version used by `cordova-android` version `6.x` not
The [cordova-android issue](https://github.com/apache/cordova-android/issues/504) mentions possible workarounds the user may take to get around this issue, including updating the gradle plugin used by your Android Project / using an older NDK.
To solve this issue while using Android NDK versions `>= r18` with cordova-android 6.x without having to update the project created by cordova, the recommended workaround would be to copy the `mips64el-linux-android-4.9` and `mipsel-linux-android-4.9` toolchains from an older release into your local NDK install or create a local link to other toolchains so that the Gradle internal checks pass, since these toolchains won't be used by Cordova. Here's one way to do this, assuming the `ANDROID_NDK_HOME` environment variable is set in your system:
-```
-cd $ANDROID_NDK_HOME/toolchains
-ln -s aarch64-linux-android-4.9 mips64el-linux-android
-ln -s arm-linux-androideabi-4.9 mipsel-linux-android
+
+```bash
+% cd $ANDROID_NDK_HOME/toolchains
+% ln -s aarch64-linux-android-4.9 mips64el-linux-android
+% ln -s arm-linux-androideabi-4.9 mipsel-linux-android
```
### iOS
When using `Xcode 10` with `cordova-ios` version `4.x`, the following error might occur when trying to build or run the application:
-```
+
+```sh
The executable was signed with invalid entitlements.
The entitlements specified in you Application's Code Signing Entitlements file are invalid, not permitted, or do not match those specified in you provisioning profile.
@@ -397,17 +434,21 @@ The entitlements specified in you Application's Code Signing Entitlements file a
This is caused by the new `Xcode 10` build system, as documented in this [cordova-ios issue](https://github.com/apache/cordova-ios/issues/407), including these recommended workarounds:
-* Including the `--buildFlag="-UseModernBuildSystem=0"` flag in the `build` and `run` commands:
-```
-cordova run ios --buildFlag='-UseModernBuildSystem=0'
-cordova build ios --buildFlag='-UseModernBuildSystem=0'
-```
-* Adding the flag under the iOS release or debug config when using a `build.json` config file:
-```
-"buildFlag": [
- "-UseModernBuildSystem=0"
-]
-```
-* Changing the build system to the "Legacy Build System" when building from the Xcode IDE:
+- Including the `--buildFlag="-UseModernBuildSystem=0"` flag in the `build` and `run` commands:
+
+ ```bash
+ % cordova run ios --buildFlag='-UseModernBuildSystem=0'
+ % cordova build ios --buildFlag='-UseModernBuildSystem=0'
+ ```
+
+- Adding the flag under the iOS release or debug config when using a `build.json` config file:
+
+ ```json
+ "buildFlag": [
+ "-UseModernBuildSystem=0"
+ ]
+ ```
+
+- Changing the build system to the "Legacy Build System" when building from the Xcode IDE:
1. In the Xcode "File Menu", select "Project Settings...";
1. In the "Project Settings..." window, inside the "Per-User Project Settings:" area, change the "Build System:" setting to "Legacy Build System".
diff --git a/install/hooks/android/after-prepare-create-macOS-builder-helper.js b/install/hooks/android/after-prepare-create-macOS-builder-helper.js
index 91eda523..ec8d5e5c 100644
--- a/install/hooks/android/after-prepare-create-macOS-builder-helper.js
+++ b/install/hooks/android/after-prepare-create-macOS-builder-helper.js
@@ -14,6 +14,7 @@ function getPlatformWWWPath(context, platform) {
return platformAPIInstance.locations.www;
}
+
// Adds a helper script to run "npm rebuild" with the current PATH.
// This workaround is needed for Android Studio on macOS when it is not started
// from the command line, as npm probably won't be in the PATH at build time.
diff --git a/install/hooks/android/before-plugin-install.js b/install/hooks/android/before-plugin-install.js
index e720d6de..958350fc 100644
--- a/install/hooks/android/before-plugin-install.js
+++ b/install/hooks/android/before-plugin-install.js
@@ -2,9 +2,8 @@ var fs = require('fs');
var zlib = require('zlib');
const nodeProjectFolder = 'www/nodejs-project';
-const libFolderPath = 'plugins/nodejs-mobile-cordova/libs/android/libnode/bin/';
+const libFolderPath = 'plugins/@red-mobile/nodejs-mobile-cordova/libs/android/libnode/bin/';
const path_armv7 = libFolderPath + 'armeabi-v7a/';
-const path_x86 = libFolderPath + 'x86/'
const path_arm64 = libFolderPath + 'arm64-v8a/';
const path_x64 = libFolderPath + 'x86_64/'
const lib_name = 'libnode.so';
@@ -27,11 +26,9 @@ function unzip(libFolderPath, callback) {
function unzipAll(callback) {
unzip(path_armv7, function() {
- unzip(path_x86, function() {
- unzip(path_arm64, function() {
- unzip(path_x64, function() {
- callback(null);
- });
+ unzip(path_arm64, function() {
+ unzip(path_x64, function() {
+ callback(null);
});
});
});
diff --git a/install/hooks/ios/after-plugin-install.js b/install/hooks/ios/after-plugin-install.js
index dbd23dff..c39528ba 100644
--- a/install/hooks/ios/after-plugin-install.js
+++ b/install/hooks/ios/after-plugin-install.js
@@ -52,14 +52,14 @@ find "$CODESIGNING_FOLDER_PATH/www/nodejs-project/" -name "*.framework" -type d
find "$CODESIGNING_FOLDER_PATH/www/nodejs-project/" -path "*/.bin/*" -delete
find "$CODESIGNING_FOLDER_PATH/www/nodejs-project/" -name ".bin" -type d -delete
# Get the nodejs-mobile-gyp location
-if [ -d "$PROJECT_DIR/../../plugins/nodejs-mobile-cordova/node_modules/nodejs-mobile-gyp/" ]; then
-NODEJS_MOBILE_GYP_DIR="$( cd "$PROJECT_DIR" && cd ../../plugins/nodejs-mobile-cordova/node_modules/nodejs-mobile-gyp/ && pwd )"
+if [ -d "$PROJECT_DIR/../../plugins/@red-mobile/nodejs-mobile-cordova/node_modules/nodejs-mobile-gyp/" ]; then
+NODEJS_MOBILE_GYP_DIR="$( cd "$PROJECT_DIR" && cd ../../plugins/@red-mobile/nodejs-mobile-cordova/node_modules/nodejs-mobile-gyp/ && pwd )"
else
NODEJS_MOBILE_GYP_DIR="$( cd "$PROJECT_DIR" && cd ../../node_modules/nodejs-mobile-gyp/ && pwd )"
fi
NODEJS_MOBILE_GYP_BIN_FILE="$NODEJS_MOBILE_GYP_DIR"/bin/node-gyp.js
# Rebuild modules with right environment
-NODEJS_HEADERS_DIR="$( cd "$( dirname "$PRODUCT_SETTINGS_PATH" )" && cd Plugins/nodejs-mobile-cordova/ && pwd )"
+NODEJS_HEADERS_DIR="$( cd "$( dirname "$PRODUCT_SETTINGS_PATH" )" && cd Plugins/@red-mobile/nodejs-mobile-cordova/ && pwd )"
# Adds the original project .bin to the path. It's a workaround
# to correctly build some modules that depend on symlinked modules,
# like node-pre-gyp.
@@ -115,7 +115,7 @@ if [ "1" != "$NODEJS_MOBILE_BUILD_NATIVE_MODULES" ]; then exit 0; fi
find "$CODESIGNING_FOLDER_PATH/www/nodejs-project/" -name "*.o" -type f -delete
find "$CODESIGNING_FOLDER_PATH/www/nodejs-project/" -name "*.a" -type f -delete
# Create Info.plist for each framework built and loader override.
-PATCH_SCRIPT_DIR="$( cd "$PROJECT_DIR" && cd ../../Plugins/nodejs-mobile-cordova/install/helper-scripts/ && pwd )"
+PATCH_SCRIPT_DIR="$( cd "$PROJECT_DIR" && cd ../../Plugins/@red-mobile/nodejs-mobile-cordova/install/helper-scripts/ && pwd )"
NODEJS_PROJECT_DIR="$( cd "$CODESIGNING_FOLDER_PATH" && cd www/nodejs-project/ && pwd )"
node "$PATCH_SCRIPT_DIR"/ios-create-plists-and-dlopen-override.js $NODEJS_PROJECT_DIR
# Embed every resulting .framework in the application and delete them afterwards.
diff --git a/install/hooks/ios/before-plugin-install.js b/install/hooks/ios/before-plugin-install.js
index bf9d705d..14f4c7c3 100644
--- a/install/hooks/ios/before-plugin-install.js
+++ b/install/hooks/ios/before-plugin-install.js
@@ -2,7 +2,7 @@ var fs = require('fs');
var targz2 = require('tar.gz2');
const nodeProjectFolder = 'www/nodejs-project';
-const nodeMobileFolderPath = 'plugins/nodejs-mobile-cordova/libs/ios/nodemobile/';
+const nodeMobileFolderPath = 'plugins/@red-mobile/nodejs-mobile-cordova/libs/ios/nodemobile/';
const nodeMobileFileName = 'NodeMobile.xcframework';
const nodeMobileFilePath = nodeMobileFolderPath + nodeMobileFileName;
const zipFileName = nodeMobileFileName + '.tar.zip';
diff --git a/install/sample-project/copy-sample-project.sh b/install/sample-project/copy-sample-project.sh
index 075de21b..2e447932 100755
--- a/install/sample-project/copy-sample-project.sh
+++ b/install/sample-project/copy-sample-project.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-SRC_PATH="plugins/nodejs-mobile-cordova/install/sample-project"
+SRC_PATH="plugins/@red-mobile/nodejs-mobile-cordova/install/sample-project"
copySampleFile () {
cp -i "$SRC_PATH/$1" $1
@@ -9,4 +9,4 @@ mkdir -p "www/nodejs-project"
copySampleFile "www/js/index.js"
copySampleFile "www/nodejs-project/main.js"
-copySampleFile "www/nodejs-project/package.json"
\ No newline at end of file
+copySampleFile "www/nodejs-project/package.json"
diff --git a/libs/android/libnode/bin/arm64-v8a/libnode.so.gz b/libs/android/libnode/bin/arm64-v8a/libnode.so.gz
index f58a44cb..b59c58d6 100644
Binary files a/libs/android/libnode/bin/arm64-v8a/libnode.so.gz and b/libs/android/libnode/bin/arm64-v8a/libnode.so.gz differ
diff --git a/libs/android/libnode/bin/armeabi-v7a/libnode.so.gz b/libs/android/libnode/bin/armeabi-v7a/libnode.so.gz
index 3c281244..e3a8c869 100644
Binary files a/libs/android/libnode/bin/armeabi-v7a/libnode.so.gz and b/libs/android/libnode/bin/armeabi-v7a/libnode.so.gz differ
diff --git a/libs/android/libnode/bin/x86/libnode.so.gz b/libs/android/libnode/bin/x86/libnode.so.gz
deleted file mode 100644
index df789bd6..00000000
Binary files a/libs/android/libnode/bin/x86/libnode.so.gz and /dev/null differ
diff --git a/libs/android/libnode/bin/x86_64/libnode.so.gz b/libs/android/libnode/bin/x86_64/libnode.so.gz
index 7e65ae7b..13ec961f 100644
Binary files a/libs/android/libnode/bin/x86_64/libnode.so.gz and b/libs/android/libnode/bin/x86_64/libnode.so.gz differ
diff --git a/libs/android/libnode/include/node/common.gypi b/libs/android/libnode/include/node/common.gypi
index 84be79f9..70e825f0 100644
--- a/libs/android/libnode/include/node/common.gypi
+++ b/libs/android/libnode/include/node/common.gypi
@@ -26,21 +26,20 @@
'uv_library%': 'static_library',
'clang%': 0,
+ 'error_on_warn%': 'false',
'openssl_fips%': '',
+ 'openssl_no_asm%': 0,
# Don't use ICU data file (icudtl.dat) from V8, we use our own.
'icu_use_data_file_flag%': 0,
# Reset this number to 0 on major V8 upgrades.
# Increment by one for each non-official patch applied to deps/v8.
- 'v8_embedder_string': '-node.44',
+ 'v8_embedder_string': '-node.22',
##### V8 defaults for Node.js #####
- # Old time default, now explicitly stated.
- 'v8_use_snapshot': 1,
-
# Turn on SipHash for hash seed generation, addresses HashWick
'v8_use_siphash': 'true',
@@ -61,10 +60,19 @@
# https://github.com/nodejs/node/pull/22920/files#r222779926
'v8_enable_handle_zapping': 0,
+ # Disable pointer compression. Can be enabled at build time via configure
+ # options but default values are required here as this file is also used by
+ # node-gyp to build addons.
+ 'v8_enable_pointer_compression%': 0,
+ 'v8_enable_31bit_smis_on_64bit_arch%': 0,
+
# Disable V8 untrusted code mitigations.
# See https://github.com/v8/v8/wiki/Untrusted-code-mitigations
'v8_untrusted_code_mitigations': 0,
+ # Disable v8 hugepage by default.
+ 'v8_enable_hugepage%': 0,
+
# This is more of a V8 dev setting
# https://github.com/nodejs/node/pull/22920/files#r222779926
'v8_enable_fast_mksnapshot': 0,
@@ -77,67 +85,47 @@
##### end V8 defaults #####
'conditions': [
- ['target_arch=="arm64"', {
- # Disabled pending https://github.com/nodejs/node/issues/23913.
- 'openssl_no_asm%': 1,
- }, {
- 'openssl_no_asm%': 0,
- }],
['OS == "win"', {
'os_posix': 0,
'v8_postmortem_support%': 0,
+ 'obj_dir': '<(PRODUCT_DIR)/obj',
+ 'v8_base': '<(PRODUCT_DIR)/lib/libv8_snapshot.a',
}, {
'os_posix': 1,
'v8_postmortem_support%': 1,
}],
- ['v8_use_snapshot==1', {
- 'conditions': [
- ['GENERATOR == "ninja"', {
- 'obj_dir': '<(PRODUCT_DIR)/obj',
- 'v8_base': '<(PRODUCT_DIR)/obj/tools/v8_gypfiles/libv8_snapshot.a',
- }, {
- 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
- 'v8_base': '<(PRODUCT_DIR)/obj.target/tools/v8_gypfiles/libv8_snapshot.a',
- }],
- ['OS == "win"', {
- 'obj_dir': '<(PRODUCT_DIR)/obj',
- 'v8_base': '<(PRODUCT_DIR)/lib/libv8_snapshot.a',
- }],
- ['OS == "mac" or OS == "ios"', {
- 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
- 'v8_base': '<(PRODUCT_DIR)/libv8_snapshot.a',
- }],
- ],
+ ['GENERATOR == "ninja"', {
+ 'obj_dir': '<(PRODUCT_DIR)/obj',
+ 'v8_base': '<(PRODUCT_DIR)/obj/tools/v8_gypfiles/libv8_snapshot.a',
}, {
- 'conditions': [
- ['GENERATOR == "ninja"', {
- 'obj_dir': '<(PRODUCT_DIR)/obj',
- 'v8_base': '<(PRODUCT_DIR)/obj/tools/v8_gypfiles/libv8_nosnapshot.a',
- }, {
- 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
- 'v8_base': '<(PRODUCT_DIR)/obj.target/tools/v8_gypfiles/libv8_nosnapshot.a',
- }],
- ['OS == "win"', {
- 'obj_dir': '<(PRODUCT_DIR)/obj',
- 'v8_base': '<(PRODUCT_DIR)/lib/libv8_nosnapshot.a',
- }],
- ['OS == "mac" or OS == "ios"', {
- 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
- 'v8_base': '<(PRODUCT_DIR)/libv8_nosnapshot.a',
- }],
- ],
+ 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
+ 'v8_base': '<(PRODUCT_DIR)/obj.target/tools/v8_gypfiles/libv8_snapshot.a',
}],
['openssl_fips != ""', {
- 'openssl_product': '<(STATIC_LIB_PREFIX)crypto<(STATIC_LIB_SUFFIX)',
+ 'openssl_product': '<(STATIC_LIB_PREFIX)openssl<(STATIC_LIB_SUFFIX)',
}, {
'openssl_product': '<(STATIC_LIB_PREFIX)openssl<(STATIC_LIB_SUFFIX)',
}],
['OS=="mac" or OS == "ios"', {
'clang%': 1,
+ 'obj_dir%': '<(PRODUCT_DIR)/obj.target',
+ 'v8_base': '<(PRODUCT_DIR)/libv8_snapshot.a',
+ }],
+ # V8 pointer compression only supports 64bit architectures.
+ ['target_arch in "arm ia32 mips mipsel ppc"', {
+ 'v8_enable_pointer_compression': 0,
+ 'v8_enable_31bit_smis_on_64bit_arch': 0,
}],
['target_arch in "ppc64 s390x"', {
'v8_enable_backtrace': 1,
}],
+ ['OS=="linux"', {
+ 'node_section_ordering_info%': ''
+ }],
+ ['OS == "zos"', {
+ # use ICU data file on z/OS
+ 'icu_use_data_file_flag%': 1
+ }]
],
},
@@ -188,22 +176,51 @@
'v8_enable_handle_zapping': 0,
'pgo_generate': ' -fprofile-generate ',
'pgo_use': ' -fprofile-use -fprofile-correction ',
- 'lto': ' -flto=4 -fuse-linker-plugin -ffat-lto-objects ',
'conditions': [
['node_shared != "true"', {
'MSVC_runtimeType': 0 # MultiThreaded (/MT)
}, {
'MSVC_runtimeType': 2 # MultiThreadedDLL (/MD)
}],
+ ['llvm_version=="0.0"', {
+ 'lto': ' -flto=4 -fuse-linker-plugin -ffat-lto-objects ', # GCC
+ }, {
+ 'lto': ' -flto ', # Clang
+ }],
],
},
'cflags': [ '-O3' ],
'conditions': [
+ ['enable_lto=="true"', {
+ 'cflags': ['<(lto)'],
+ 'ldflags': ['<(lto)'],
+ 'xcode_settings': {
+ 'LLVM_LTO': 'YES',
+ },
+ }],
+ ['OS=="linux"', {
+ 'conditions': [
+ ['node_section_ordering_info!=""', {
+ 'cflags': [
+ '-fuse-ld=gold',
+ '-ffunction-sections',
+ ],
+ 'ldflags': [
+ '-fuse-ld=gold',
+ '-Wl,--section-ordering-file=<(node_section_ordering_info)',
+ ],
+ }],
+ ],
+ }],
['OS=="solaris"', {
# pull in V8's postmortem metadata
'ldflags': [ '-Wl,-z,allextract' ]
}],
- ['OS!="mac" and OS!="ios" and OS!="win"', {
+ ['OS=="zos"', {
+ # increase performance, number from experimentation
+ 'cflags': [ '-qINLINE=::150:100000' ]
+ }],
+ ['OS!="mac" and OS!="ios" and OS!="win" and OS!="zos"', {
'cflags': [ '-fno-omit-frame-pointer' ],
}],
['OS=="linux"', {
@@ -216,10 +233,6 @@
'cflags': ['<(pgo_use)'],
'ldflags': ['<(pgo_use)'],
},],
- ['enable_lto=="true"', {
- 'cflags': ['<(lto)'],
- 'ldflags': ['<(lto)'],
- },],
],
},],
['OS == "android"', {
@@ -229,6 +242,11 @@
],
'msvs_settings': {
'VCCLCompilerTool': {
+ 'conditions': [
+ ['target_arch=="arm64"', {
+ 'FloatingPointModel': 1 # /fp:strict
+ }]
+ ],
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'FavorSizeOrSpeed': 1, # /Ot, favor speed over size
@@ -250,16 +268,29 @@
'defines': [
'V8_DEPRECATION_WARNINGS',
'V8_IMMINENT_DEPRECATION_WARNINGS',
+ '_GLIBCXX_USE_CXX11_ABI=1',
],
# Forcibly disable -Werror. We support a wide range of compilers, it's
# simply not feasible to squelch all warnings, never mind that the
# libraries in deps/ are not under our control.
- 'cflags!': ['-Werror'],
+ 'conditions': [
+ [ 'error_on_warn=="false"', {
+ 'cflags!': ['-Werror'],
+ }, '(_target_name!="<(node_lib_target_name)" or '
+ '_target_name!="<(node_core_target_name)")', {
+ 'cflags!': ['-Werror'],
+ }],
+ ],
'msvs_settings': {
'VCCLCompilerTool': {
+ 'AdditionalOptions': ['/Zc:__cplusplus'],
'BufferSecurityCheck': 'true',
- 'DebugInformationFormat': 1, # /Z7 embed info in .obj files
+ 'target_conditions': [
+ ['_toolset=="target"', {
+ 'DebugInformationFormat': 1 # /Z7 embed info in .obj files
+ }],
+ ],
'ExceptionHandling': 0, # /EHsc
'MultiProcessorCompilation': 'true',
'StringPooling': 'true', # pool string literals
@@ -317,7 +348,7 @@
[ 'target_arch=="arm64"', {
'msvs_configuration_platform': 'arm64',
}],
- ['asan == 1 and OS != "mac" and OS !="ios"', {
+ ['asan == 1 and OS != "mac" and OS != "ios" and OS != "zos"', {
'cflags+': [
'-fno-omit-frame-pointer',
'-fsanitize=address',
@@ -345,6 +376,15 @@
}],
],
}],
+ ['v8_enable_pointer_compression == 1', {
+ 'defines': [
+ 'V8_COMPRESS_POINTERS',
+ 'V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE',
+ ],
+ }],
+ ['v8_enable_pointer_compression == 1 or v8_enable_31bit_smis_on_64bit_arch == 1', {
+ 'defines': ['V8_31BIT_SMIS_ON_64BIT_ARCH'],
+ }],
['OS == "win"', {
'defines': [
'WIN32',
@@ -366,7 +406,7 @@
}],
[ 'OS in "linux freebsd openbsd solaris android aix cloudabi"', {
'cflags': [ '-Wall', '-Wextra', '-Wno-unused-parameter', ],
- 'cflags_cc': [ '-fno-rtti', '-fno-exceptions', '-std=gnu++1y' ],
+ 'cflags_cc': [ '-fno-rtti', '-fno-exceptions', '-std=gnu++14' ],
'defines': [ '__STDC_FORMAT_MACROS' ],
'ldflags': [ '-rdynamic' ],
'target_conditions': [
@@ -384,10 +424,6 @@
'cflags': [ '-m32' ],
'ldflags': [ '-m32' ],
}],
- [ 'target_arch=="x32"', {
- 'cflags': [ '-mx32' ],
- 'ldflags': [ '-mx32' ],
- }],
[ 'target_arch=="x64"', {
'cflags': [ '-m64' ],
'ldflags': [ '-m64' ],
@@ -400,7 +436,7 @@
'cflags': [ '-m64', '-mminimal-toc' ],
'ldflags': [ '-m64' ],
}],
- [ 'target_arch=="s390x"', {
+ [ 'target_arch=="s390x" and OS=="linux"', {
'cflags': [ '-m64', '-march=z196' ],
'ldflags': [ '-m64', '-march=z196' ],
}],
@@ -488,7 +524,7 @@
'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti
'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings
'PREBINDING': 'NO', # No -Wl,-prebind
- 'MACOSX_DEPLOYMENT_TARGET': '10.10', # -mmacosx-version-min=10.10
+ 'MACOSX_DEPLOYMENT_TARGET': '10.13', # -mmacosx-version-min=10.13
'USE_HEADERMAP': 'NO',
'OTHER_CFLAGS': [
'-fno-strict-aliasing',
@@ -504,8 +540,7 @@
['_type!="static_library"', {
'xcode_settings': {
'OTHER_LDFLAGS': [
- '-Wl,-no_pie',
- '-Wl,-search_paths_first',
+ '-Wl,-search_paths_first'
],
},
}],
@@ -528,7 +563,7 @@
['clang==1', {
'xcode_settings': {
'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
- 'CLANG_CXX_LANGUAGE_STANDARD': 'gnu++1y', # -std=gnu++1y
+ 'CLANG_CXX_LANGUAGE_STANDARD': 'gnu++14', # -std=gnu++14
'CLANG_CXX_LIBRARY': 'libc++',
},
}],
@@ -545,7 +580,7 @@
'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti
'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings
'PREBINDING': 'NO', # No -Wl,-prebind
- 'IPHONEOS_DEPLOYMENT_TARGET': '9.0', # -miphoneos-version-min=9.0
+ 'IPHONEOS_DEPLOYMENT_TARGET': '11.0', # -miphoneos-version-min=11.0
'USE_HEADERMAP': 'NO',
'OTHER_CFLAGS': [
'-fno-strict-aliasing',
@@ -638,6 +673,50 @@
'OPENSSL_NO_ASM',
],
}],
+ ['OS == "zos"', {
+ 'defines': [
+ '_XOPEN_SOURCE_EXTENDED',
+ '_XOPEN_SOURCE=600',
+ '_UNIX03_THREADS',
+ '_UNIX03_WITHDRAWN',
+ '_UNIX03_SOURCE',
+ '_OPEN_SYS_SOCK_IPV6',
+ '_OPEN_SYS_FILE_EXT=1',
+ '_POSIX_SOURCE',
+ '_OPEN_SYS',
+ '_OPEN_SYS_IF_EXT',
+ '_OPEN_SYS_SOCK_IPV6',
+ '_OPEN_MSGQ_EXT',
+ '_LARGE_TIME_API',
+ '_ALL_SOURCE',
+ '_AE_BIMODAL=1',
+ '__IBMCPP_TR1__',
+ 'NODE_PLATFORM="os390"',
+ 'PATH_MAX=1024',
+ '_ENHANCED_ASCII_EXT=0xFFFFFFFF',
+ '_Export=extern',
+ '__static_assert=static_assert',
+ ],
+ 'cflags': [
+ '-q64',
+ '-Wc,DLL',
+ '-Wa,GOFF',
+ '-qARCH=10',
+ '-qASCII',
+ '-qTUNE=12',
+ '-qENUM=INT',
+ '-qEXPORTALL',
+ '-qASM',
+ ],
+ 'cflags_cc': [
+ '-qxclang=-std=c++14',
+ ],
+ 'ldflags': [
+ '-q64',
+ ],
+ # for addons due to v8config.h include of "zos-base.h":
+ 'include_dirs': ['<(zoslib_include_dir)'],
+ }],
],
}
}
diff --git a/libs/android/libnode/include/node/config.gypi b/libs/android/libnode/include/node/config.gypi
index da56cb98..60915ac9 100644
--- a/libs/android/libnode/include/node/config.gypi
+++ b/libs/android/libnode/include/node/config.gypi
@@ -1,12 +1,11 @@
# Do not edit. Generated by the configure script.
-{ 'target_defaults': { 'cflags': [],
- 'default_configuration': 'Release',
- 'defines': [],
- 'include_dirs': [],
- 'libraries': []},
+{ 'target_defaults': {'cflags': [], 'default_configuration': 'Release', 'defines': ['NODE_OPENSSL_CONF_NAME=nodejs_conf'], 'include_dirs': [], 'libraries': []},
'variables': { 'OS': 'android',
+ 'arm_float_abi': 'default',
+ 'arm_fpu': 'vfpv3',
+ 'arm_thumb': 0,
+ 'arm_version': '7',
'asan': 0,
- 'build_v8_with_gn': 'false',
'coverage': 'false',
'dcheck_always_on': 0,
'debug_nghttp2': 'false',
@@ -14,26 +13,311 @@
'enable_lto': 'false',
'enable_pgo_generate': 'false',
'enable_pgo_use': 'false',
+ 'error_on_warn': 'false',
'force_dynamic_crt': 1,
'host_arch': 'x64',
'icu_small': 'false',
'is_debug': 0,
- 'llvm_version': '0.0',
- 'napi_build_version': '7',
+ 'llvm_version': '9.0',
+ 'napi_build_version': '8',
'node_byteorder': 'little',
'node_debug_lib': 'false',
'node_enable_d8': 'false',
+ 'node_install_corepack': 'true',
'node_install_npm': 'true',
- 'node_module_version': 72,
+ 'node_library_files': [ 'lib/tls.js',
+ 'lib/constants.js',
+ 'lib/async_hooks.js',
+ 'lib/_http_outgoing.js',
+ 'lib/vm.js',
+ 'lib/punycode.js',
+ 'lib/tty.js',
+ 'lib/worker_threads.js',
+ 'lib/querystring.js',
+ 'lib/_stream_writable.js',
+ 'lib/readline.js',
+ 'lib/path.js',
+ 'lib/module.js',
+ 'lib/string_decoder.js',
+ 'lib/perf_hooks.js',
+ 'lib/http.js',
+ 'lib/net.js',
+ 'lib/child_process.js',
+ 'lib/sys.js',
+ 'lib/wasi.js',
+ 'lib/fs.js',
+ 'lib/v8.js',
+ 'lib/zlib.js',
+ 'lib/dgram.js',
+ 'lib/cluster.js',
+ 'lib/_stream_transform.js',
+ 'lib/console.js',
+ 'lib/url.js',
+ 'lib/_stream_readable.js',
+ 'lib/trace_events.js',
+ 'lib/_stream_duplex.js',
+ 'lib/_http_common.js',
+ 'lib/_stream_passthrough.js',
+ 'lib/buffer.js',
+ 'lib/http2.js',
+ 'lib/_http_incoming.js',
+ 'lib/_stream_wrap.js',
+ 'lib/events.js',
+ 'lib/_http_client.js',
+ 'lib/crypto.js',
+ 'lib/diagnostics_channel.js',
+ 'lib/timers.js',
+ 'lib/inspector.js',
+ 'lib/_http_agent.js',
+ 'lib/os.js',
+ 'lib/https.js',
+ 'lib/test.js',
+ 'lib/assert.js',
+ 'lib/_tls_wrap.js',
+ 'lib/util.js',
+ 'lib/stream.js',
+ 'lib/dns.js',
+ 'lib/_tls_common.js',
+ 'lib/_http_server.js',
+ 'lib/repl.js',
+ 'lib/process.js',
+ 'lib/domain.js',
+ 'lib/assert/strict.js',
+ 'lib/internal/constants.js',
+ 'lib/internal/async_hooks.js',
+ 'lib/internal/priority_queue.js',
+ 'lib/internal/tty.js',
+ 'lib/internal/dtrace.js',
+ 'lib/internal/cli_table.js',
+ 'lib/internal/querystring.js',
+ 'lib/internal/options.js',
+ 'lib/internal/worker.js',
+ 'lib/internal/trace_events_async_hooks.js',
+ 'lib/internal/http.js',
+ 'lib/internal/net.js',
+ 'lib/internal/child_process.js',
+ 'lib/internal/js_stream_socket.js',
+ 'lib/internal/socketaddress.js',
+ 'lib/internal/dgram.js',
+ 'lib/internal/url.js',
+ 'lib/internal/abort_controller.js',
+ 'lib/internal/fixed_queue.js',
+ 'lib/internal/buffer.js',
+ 'lib/internal/validators.js',
+ 'lib/internal/stream_base_commons.js',
+ 'lib/internal/timers.js',
+ 'lib/internal/errors.js',
+ 'lib/internal/encoding.js',
+ 'lib/internal/blob.js',
+ 'lib/internal/v8_prof_processor.js',
+ 'lib/internal/freelist.js',
+ 'lib/internal/heap_utils.js',
+ 'lib/internal/linkedlist.js',
+ 'lib/internal/error_serdes.js',
+ 'lib/internal/blocklist.js',
+ 'lib/internal/idna.js',
+ 'lib/internal/v8_prof_polyfill.js',
+ 'lib/internal/histogram.js',
+ 'lib/internal/watchdog.js',
+ 'lib/internal/assert.js',
+ 'lib/internal/util.js',
+ 'lib/internal/socket_list.js',
+ 'lib/internal/inspector_async_hook.js',
+ 'lib/internal/promise_hooks.js',
+ 'lib/internal/event_target.js',
+ 'lib/internal/repl.js',
+ 'lib/internal/freeze_intrinsics.js',
+ 'lib/internal/modules/run_main.js',
+ 'lib/internal/modules/package_json_reader.js',
+ 'lib/internal/modules/esm/translators.js',
+ 'lib/internal/modules/esm/fetch_module.js',
+ 'lib/internal/modules/esm/initialize_import_meta.js',
+ 'lib/internal/modules/esm/formats.js',
+ 'lib/internal/modules/esm/create_dynamic_module.js',
+ 'lib/internal/modules/esm/get_format.js',
+ 'lib/internal/modules/esm/loader.js',
+ 'lib/internal/modules/esm/module_map.js',
+ 'lib/internal/modules/esm/handle_process_exit.js',
+ 'lib/internal/modules/esm/load.js',
+ 'lib/internal/modules/esm/module_job.js',
+ 'lib/internal/modules/esm/resolve.js',
+ 'lib/internal/modules/esm/assert.js',
+ 'lib/internal/modules/cjs/loader.js',
+ 'lib/internal/modules/cjs/helpers.js',
+ 'lib/internal/assert/assertion_error.js',
+ 'lib/internal/assert/calltracker.js',
+ 'lib/internal/tls/parse-cert-string.js',
+ 'lib/internal/tls/secure-pair.js',
+ 'lib/internal/tls/secure-context.js',
+ 'lib/internal/test_runner/utils.js',
+ 'lib/internal/test_runner/test.js',
+ 'lib/internal/test_runner/harness.js',
+ 'lib/internal/test_runner/tap_stream.js',
+ 'lib/internal/vm/module.js',
+ 'lib/internal/child_process/serialization.js',
+ 'lib/internal/policy/manifest.js',
+ 'lib/internal/policy/sri.js',
+ 'lib/internal/bootstrap/environment.js',
+ 'lib/internal/bootstrap/loaders.js',
+ 'lib/internal/bootstrap/pre_execution.js',
+ 'lib/internal/bootstrap/node.js',
+ 'lib/internal/bootstrap/switches/is_not_main_thread.js',
+ 'lib/internal/bootstrap/switches/is_main_thread.js',
+ 'lib/internal/bootstrap/switches/does_own_process_state.js',
+ 'lib/internal/bootstrap/switches/does_not_own_process_state.js',
+ 'lib/internal/fs/read_file_context.js',
+ 'lib/internal/fs/utils.js',
+ 'lib/internal/fs/watchers.js',
+ 'lib/internal/fs/sync_write_stream.js',
+ 'lib/internal/fs/streams.js',
+ 'lib/internal/fs/promises.js',
+ 'lib/internal/fs/rimraf.js',
+ 'lib/internal/fs/dir.js',
+ 'lib/internal/fs/cp/cp.js',
+ 'lib/internal/fs/cp/cp-sync.js',
+ 'lib/internal/source_map/source_map.js',
+ 'lib/internal/source_map/prepare_stack_trace.js',
+ 'lib/internal/source_map/source_map_cache.js',
+ 'lib/internal/http2/compat.js',
+ 'lib/internal/http2/util.js',
+ 'lib/internal/http2/core.js',
+ 'lib/internal/console/constructor.js',
+ 'lib/internal/console/global.js',
+ 'lib/internal/webstreams/transfer.js',
+ 'lib/internal/webstreams/transformstream.js',
+ 'lib/internal/webstreams/compression.js',
+ 'lib/internal/webstreams/queuingstrategies.js',
+ 'lib/internal/webstreams/encoding.js',
+ 'lib/internal/webstreams/adapters.js',
+ 'lib/internal/webstreams/writablestream.js',
+ 'lib/internal/webstreams/readablestream.js',
+ 'lib/internal/webstreams/util.js',
+ 'lib/internal/cluster/child.js',
+ 'lib/internal/cluster/worker.js',
+ 'lib/internal/cluster/utils.js',
+ 'lib/internal/cluster/shared_handle.js',
+ 'lib/internal/cluster/round_robin_handle.js',
+ 'lib/internal/cluster/primary.js',
+ 'lib/internal/crypto/scrypt.js',
+ 'lib/internal/crypto/x509.js',
+ 'lib/internal/crypto/diffiehellman.js',
+ 'lib/internal/crypto/keygen.js',
+ 'lib/internal/crypto/aes.js',
+ 'lib/internal/crypto/rsa.js',
+ 'lib/internal/crypto/hash.js',
+ 'lib/internal/crypto/random.js',
+ 'lib/internal/crypto/mac.js',
+ 'lib/internal/crypto/cipher.js',
+ 'lib/internal/crypto/sig.js',
+ 'lib/internal/crypto/webcrypto.js',
+ 'lib/internal/crypto/certificate.js',
+ 'lib/internal/crypto/pbkdf2.js',
+ 'lib/internal/crypto/hkdf.js',
+ 'lib/internal/crypto/cfrg.js',
+ 'lib/internal/crypto/util.js',
+ 'lib/internal/crypto/keys.js',
+ 'lib/internal/crypto/hashnames.js',
+ 'lib/internal/crypto/ec.js',
+ 'lib/internal/perf/performance_entry.js',
+ 'lib/internal/perf/event_loop_utilization.js',
+ 'lib/internal/perf/event_loop_delay.js',
+ 'lib/internal/perf/utils.js',
+ 'lib/internal/perf/performance.js',
+ 'lib/internal/perf/timerify.js',
+ 'lib/internal/perf/observe.js',
+ 'lib/internal/perf/usertiming.js',
+ 'lib/internal/perf/resource_timing.js',
+ 'lib/internal/perf/nodetiming.js',
+ 'lib/internal/process/worker_thread_only.js',
+ 'lib/internal/process/execution.js',
+ 'lib/internal/process/report.js',
+ 'lib/internal/process/policy.js',
+ 'lib/internal/process/task_queues.js',
+ 'lib/internal/process/signal.js',
+ 'lib/internal/process/esm_loader.js',
+ 'lib/internal/process/warning.js',
+ 'lib/internal/process/per_thread.js',
+ 'lib/internal/process/promises.js',
+ 'lib/internal/dns/utils.js',
+ 'lib/internal/dns/promises.js',
+ 'lib/internal/streams/transform.js',
+ 'lib/internal/streams/pipeline.js',
+ 'lib/internal/streams/end-of-stream.js',
+ 'lib/internal/streams/destroy.js',
+ 'lib/internal/streams/utils.js',
+ 'lib/internal/streams/lazy_transform.js',
+ 'lib/internal/streams/add-abort-signal.js',
+ 'lib/internal/streams/legacy.js',
+ 'lib/internal/streams/buffer_list.js',
+ 'lib/internal/streams/writable.js',
+ 'lib/internal/streams/state.js',
+ 'lib/internal/streams/duplexify.js',
+ 'lib/internal/streams/from.js',
+ 'lib/internal/streams/readable.js',
+ 'lib/internal/streams/passthrough.js',
+ 'lib/internal/streams/compose.js',
+ 'lib/internal/streams/duplex.js',
+ 'lib/internal/streams/operators.js',
+ 'lib/internal/per_context/primordials.js',
+ 'lib/internal/per_context/domexception.js',
+ 'lib/internal/per_context/messageport.js',
+ 'lib/internal/readline/utils.js',
+ 'lib/internal/readline/emitKeypressEvents.js',
+ 'lib/internal/readline/callbacks.js',
+ 'lib/internal/readline/interface.js',
+ 'lib/internal/test/transfer.js',
+ 'lib/internal/test/binding.js',
+ 'lib/internal/legacy/processbinding.js',
+ 'lib/internal/util/comparisons.js',
+ 'lib/internal/util/inspect.js',
+ 'lib/internal/util/iterable_weak_map.js',
+ 'lib/internal/util/debuglog.js',
+ 'lib/internal/util/types.js',
+ 'lib/internal/util/inspector.js',
+ 'lib/internal/util/parse_args/utils.js',
+ 'lib/internal/util/parse_args/parse_args.js',
+ 'lib/internal/v8/startup_snapshot.js',
+ 'lib/internal/main/test_runner.js',
+ 'lib/internal/main/prof_process.js',
+ 'lib/internal/main/print_help.js',
+ 'lib/internal/main/eval_string.js',
+ 'lib/internal/main/check_syntax.js',
+ 'lib/internal/main/inspect.js',
+ 'lib/internal/main/eval_stdin.js',
+ 'lib/internal/main/run_main_module.js',
+ 'lib/internal/main/mksnapshot.js',
+ 'lib/internal/main/worker_thread.js',
+ 'lib/internal/main/repl.js',
+ 'lib/internal/repl/await.js',
+ 'lib/internal/repl/utils.js',
+ 'lib/internal/repl/history.js',
+ 'lib/internal/worker/js_transferable.js',
+ 'lib/internal/worker/io.js',
+ 'lib/internal/debugger/inspect_repl.js',
+ 'lib/internal/debugger/inspect_client.js',
+ 'lib/internal/debugger/inspect.js',
+ 'lib/fs/promises.js',
+ 'lib/timers/promises.js',
+ 'lib/stream/web.js',
+ 'lib/stream/consumers.js',
+ 'lib/stream/promises.js',
+ 'lib/dns/promises.js',
+ 'lib/path/posix.js',
+ 'lib/path/win32.js',
+ 'lib/util/types.js'],
+ 'node_module_version': 93,
'node_no_browser_globals': 'false',
- 'node_prefix': '/',
+ 'node_prefix': '/usr/local',
'node_release_urlbase': '',
+ 'node_section_ordering_info': '',
'node_shared': 'true',
'node_shared_brotli': 'false',
'node_shared_cares': 'false',
'node_shared_http_parser': 'false',
'node_shared_libuv': 'false',
'node_shared_nghttp2': 'false',
+ 'node_shared_nghttp3': 'false',
+ 'node_shared_ngtcp2': 'false',
'node_shared_openssl': 'false',
'node_shared_zlib': 'false',
'node_tag': '',
@@ -50,19 +334,23 @@
'openssl_fips': '',
'openssl_is_fips': 'false',
'openssl_no_asm': 1,
+ 'openssl_quic': 'true',
'ossfuzz': 'false',
'shlib_suffix': 'so',
- 'target_arch': 'arm64',
+ 'target_arch': 'arm',
+ 'v8_enable_31bit_smis_on_64bit_arch': 0,
'v8_enable_gdbjit': 0,
+ 'v8_enable_hugepage': 0,
'v8_enable_i18n_support': 0,
'v8_enable_inspector': 0,
'v8_enable_lite_mode': 0,
'v8_enable_object_print': 1,
+ 'v8_enable_pointer_compression': 0,
+ 'v8_enable_webassembly': 1,
'v8_no_strict_aliasing': 1,
'v8_optimized_debug': 1,
'v8_promise_internal_field_count': 1,
'v8_random_seed': 0,
'v8_trace_maps': 0,
'v8_use_siphash': 1,
- 'v8_use_snapshot': 1,
'want_separate_host_toolset': 1}}
diff --git a/libs/android/libnode/include/node/cppgc/allocation.h b/libs/android/libnode/include/node/cppgc/allocation.h
new file mode 100644
index 00000000..d75f1a97
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/allocation.h
@@ -0,0 +1,233 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_ALLOCATION_H_
+#define INCLUDE_CPPGC_ALLOCATION_H_
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "cppgc/custom-space.h"
+#include "cppgc/internal/api-constants.h"
+#include "cppgc/internal/gc-info.h"
+#include "cppgc/type-traits.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+/**
+ * AllocationHandle is used to allocate garbage-collected objects.
+ */
+class AllocationHandle;
+
+namespace internal {
+
+class V8_EXPORT MakeGarbageCollectedTraitInternal {
+ protected:
+ static inline void MarkObjectAsFullyConstructed(const void* payload) {
+ // See api_constants for an explanation of the constants.
+ std::atomic* atomic_mutable_bitfield =
+ reinterpret_cast*>(
+ const_cast(reinterpret_cast(
+ reinterpret_cast(payload) -
+ api_constants::kFullyConstructedBitFieldOffsetFromPayload)));
+ atomic_mutable_bitfield->fetch_or(api_constants::kFullyConstructedBitMask,
+ std::memory_order_release);
+ }
+
+ template
+ struct SpacePolicy {
+ static void* Allocate(AllocationHandle& handle, size_t size) {
+ // Custom space.
+ static_assert(std::is_base_of::value,
+ "Custom space must inherit from CustomSpaceBase.");
+ return MakeGarbageCollectedTraitInternal::Allocate(
+ handle, size, internal::GCInfoTrait::Index(),
+ CustomSpace::kSpaceIndex);
+ }
+ };
+
+ template
+ struct SpacePolicy {
+ static void* Allocate(AllocationHandle& handle, size_t size) {
+ // Default space.
+ return MakeGarbageCollectedTraitInternal::Allocate(
+ handle, size, internal::GCInfoTrait::Index());
+ }
+ };
+
+ private:
+ static void* Allocate(cppgc::AllocationHandle& handle, size_t size,
+ GCInfoIndex index);
+ static void* Allocate(cppgc::AllocationHandle& handle, size_t size,
+ GCInfoIndex index, CustomSpaceIndex space_index);
+
+ friend class HeapObjectHeader;
+};
+
+} // namespace internal
+
+/**
+ * Base trait that provides utilities for advancers users that have custom
+ * allocation needs (e.g., overriding size). It's expected that users override
+ * MakeGarbageCollectedTrait (see below) and inherit from
+ * MakeGarbageCollectedTraitBase and make use of the low-level primitives
+ * offered to allocate and construct an object.
+ */
+template
+class MakeGarbageCollectedTraitBase
+ : private internal::MakeGarbageCollectedTraitInternal {
+ private:
+ static_assert(internal::IsGarbageCollectedType::value,
+ "T needs to be a garbage collected object");
+ static_assert(!IsGarbageCollectedWithMixinTypeV ||
+ sizeof(T) <=
+ internal::api_constants::kLargeObjectSizeThreshold,
+ "GarbageCollectedMixin may not be a large object");
+
+ protected:
+ /**
+ * Allocates memory for an object of type T.
+ *
+ * \param handle AllocationHandle identifying the heap to allocate the object
+ * on.
+ * \param size The size that should be reserved for the object.
+ * \returns the memory to construct an object of type T on.
+ */
+ V8_INLINE static void* Allocate(AllocationHandle& handle, size_t size) {
+ static_assert(
+ std::is_base_of::value,
+ "U of GarbageCollected must be a base of T. Check "
+ "GarbageCollected base class inheritance.");
+ return SpacePolicy<
+ typename internal::GCInfoFolding<
+ T, typename T::ParentMostGarbageCollectedType>::ResultType,
+ typename SpaceTrait::Space>::Allocate(handle, size);
+ }
+
+ /**
+ * Marks an object as fully constructed, resulting in precise handling by the
+ * garbage collector.
+ *
+ * \param payload The base pointer the object is allocated at.
+ */
+ V8_INLINE static void MarkObjectAsFullyConstructed(const void* payload) {
+ internal::MakeGarbageCollectedTraitInternal::MarkObjectAsFullyConstructed(
+ payload);
+ }
+};
+
+/**
+ * Passed to MakeGarbageCollected to specify how many bytes should be appended
+ * to the allocated object.
+ *
+ * Example:
+ * \code
+ * class InlinedArray final : public GarbageCollected {
+ * public:
+ * explicit InlinedArray(size_t bytes) : size(bytes), byte_array(this + 1) {}
+ * void Trace(Visitor*) const {}
+
+ * size_t size;
+ * char* byte_array;
+ * };
+ *
+ * auto* inlined_array = MakeGarbageCollectedbyte_array[i]);
+ * }
+ * \endcode
+ */
+struct AdditionalBytes {
+ constexpr explicit AdditionalBytes(size_t bytes) : value(bytes) {}
+ const size_t value;
+};
+
+/**
+ * Default trait class that specifies how to construct an object of type T.
+ * Advanced users may override how an object is constructed using the utilities
+ * that are provided through MakeGarbageCollectedTraitBase.
+ *
+ * Any trait overriding construction must
+ * - allocate through `MakeGarbageCollectedTraitBase::Allocate`;
+ * - mark the object as fully constructed using
+ * `MakeGarbageCollectedTraitBase::MarkObjectAsFullyConstructed`;
+ */
+template
+class MakeGarbageCollectedTrait : public MakeGarbageCollectedTraitBase {
+ public:
+ template
+ static T* Call(AllocationHandle& handle, Args&&... args) {
+ void* memory =
+ MakeGarbageCollectedTraitBase::Allocate(handle, sizeof(T));
+ T* object = ::new (memory) T(std::forward(args)...);
+ MakeGarbageCollectedTraitBase::MarkObjectAsFullyConstructed(object);
+ return object;
+ }
+
+ template
+ static T* Call(AllocationHandle& handle, AdditionalBytes additional_bytes,
+ Args&&... args) {
+ void* memory = MakeGarbageCollectedTraitBase::Allocate(
+ handle, sizeof(T) + additional_bytes.value);
+ T* object = ::new (memory) T(std::forward(args)...);
+ MakeGarbageCollectedTraitBase::MarkObjectAsFullyConstructed(object);
+ return object;
+ }
+};
+
+/**
+ * Allows users to specify a post-construction callback for specific types. The
+ * callback is invoked on the instance of type T right after it has been
+ * constructed. This can be useful when the callback requires a
+ * fully-constructed object to be able to dispatch to virtual methods.
+ */
+template
+struct PostConstructionCallbackTrait {
+ static void Call(T*) {}
+};
+
+/**
+ * Constructs a managed object of type T where T transitively inherits from
+ * GarbageCollected.
+ *
+ * \param args List of arguments with which an instance of T will be
+ * constructed.
+ * \returns an instance of type T.
+ */
+template
+T* MakeGarbageCollected(AllocationHandle& handle, Args&&... args) {
+ T* object =
+ MakeGarbageCollectedTrait::Call(handle, std::forward(args)...);
+ PostConstructionCallbackTrait::Call(object);
+ return object;
+}
+
+/**
+ * Constructs a managed object of type T where T transitively inherits from
+ * GarbageCollected. Created objects will have additional bytes appended to
+ * it. Allocated memory would suffice for `sizeof(T) + additional_bytes`.
+ *
+ * \param additional_bytes Denotes how many bytes to append to T.
+ * \param args List of arguments with which an instance of T will be
+ * constructed.
+ * \returns an instance of type T.
+ */
+template
+T* MakeGarbageCollected(AllocationHandle& handle,
+ AdditionalBytes additional_bytes, Args&&... args) {
+ T* object = MakeGarbageCollectedTrait::Call(handle, additional_bytes,
+ std::forward(args)...);
+ PostConstructionCallbackTrait::Call(object);
+ return object;
+}
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_ALLOCATION_H_
diff --git a/libs/android/libnode/include/node/cppgc/common.h b/libs/android/libnode/include/node/cppgc/common.h
new file mode 100644
index 00000000..b6dbff3d
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/common.h
@@ -0,0 +1,29 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_COMMON_H_
+#define INCLUDE_CPPGC_COMMON_H_
+
+// TODO(chromium:1056170): Remove dependency on v8.
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+/**
+ * Indicator for the stack state of the embedder.
+ */
+enum class EmbedderStackState {
+ /**
+ * Stack may contain interesting heap pointers.
+ */
+ kMayContainHeapPointers,
+ /**
+ * Stack does not contain any interesting heap pointers.
+ */
+ kNoHeapPointers,
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_COMMON_H_
diff --git a/libs/android/libnode/include/node/cppgc/cross-thread-persistent.h b/libs/android/libnode/include/node/cppgc/cross-thread-persistent.h
new file mode 100644
index 00000000..0a9afdcd
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/cross-thread-persistent.h
@@ -0,0 +1,413 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_CROSS_THREAD_PERSISTENT_H_
+#define INCLUDE_CPPGC_CROSS_THREAD_PERSISTENT_H_
+
+#include
+
+#include "cppgc/internal/persistent-node.h"
+#include "cppgc/internal/pointer-policies.h"
+#include "cppgc/persistent.h"
+#include "cppgc/visitor.h"
+
+namespace cppgc {
+namespace internal {
+
+// Wrapper around PersistentBase that allows accessing poisoned memory when
+// using ASAN. This is needed as the GC of the heap that owns the value
+// of a CTP, may clear it (heap termination, weakness) while the object
+// holding the CTP may be poisoned as itself may be deemed dead.
+class CrossThreadPersistentBase : public PersistentBase {
+ public:
+ CrossThreadPersistentBase() = default;
+ explicit CrossThreadPersistentBase(const void* raw) : PersistentBase(raw) {}
+
+ V8_CLANG_NO_SANITIZE("address") const void* GetValueFromGC() const {
+ return raw_;
+ }
+
+ V8_CLANG_NO_SANITIZE("address")
+ PersistentNode* GetNodeFromGC() const { return node_; }
+
+ V8_CLANG_NO_SANITIZE("address")
+ void ClearFromGC() const {
+ raw_ = nullptr;
+ node_ = nullptr;
+ }
+};
+
+template
+class BasicCrossThreadPersistent final : public CrossThreadPersistentBase,
+ public LocationPolicy,
+ private WeaknessPolicy,
+ private CheckingPolicy {
+ public:
+ using typename WeaknessPolicy::IsStrongPersistent;
+ using PointeeType = T;
+
+ ~BasicCrossThreadPersistent() { Clear(); }
+
+ BasicCrossThreadPersistent(
+ const SourceLocation& loc = SourceLocation::Current())
+ : LocationPolicy(loc) {}
+
+ BasicCrossThreadPersistent(
+ std::nullptr_t, const SourceLocation& loc = SourceLocation::Current())
+ : LocationPolicy(loc) {}
+
+ BasicCrossThreadPersistent(
+ SentinelPointer s, const SourceLocation& loc = SourceLocation::Current())
+ : CrossThreadPersistentBase(s), LocationPolicy(loc) {}
+
+ BasicCrossThreadPersistent(
+ T* raw, const SourceLocation& loc = SourceLocation::Current())
+ : CrossThreadPersistentBase(raw), LocationPolicy(loc) {
+ if (!IsValid(raw)) return;
+ PersistentRegionLock guard;
+ CrossThreadPersistentRegion& region = this->GetPersistentRegion(raw);
+ SetNode(region.AllocateNode(this, &Trace));
+ this->CheckPointer(raw);
+ }
+
+ class UnsafeCtorTag {
+ private:
+ UnsafeCtorTag() = default;
+ template
+ friend class BasicCrossThreadPersistent;
+ };
+
+ BasicCrossThreadPersistent(
+ UnsafeCtorTag, T* raw,
+ const SourceLocation& loc = SourceLocation::Current())
+ : CrossThreadPersistentBase(raw), LocationPolicy(loc) {
+ if (!IsValid(raw)) return;
+ CrossThreadPersistentRegion& region = this->GetPersistentRegion(raw);
+ SetNode(region.AllocateNode(this, &Trace));
+ this->CheckPointer(raw);
+ }
+
+ BasicCrossThreadPersistent(
+ T& raw, const SourceLocation& loc = SourceLocation::Current())
+ : BasicCrossThreadPersistent(&raw, loc) {}
+
+ template ::value>>
+ BasicCrossThreadPersistent(
+ internal::BasicMember
+ member,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicCrossThreadPersistent(member.Get(), loc) {}
+
+ BasicCrossThreadPersistent(
+ const BasicCrossThreadPersistent& other,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicCrossThreadPersistent(loc) {
+ // Invoke operator=.
+ *this = other;
+ }
+
+ // Heterogeneous ctor.
+ template ::value>>
+ BasicCrossThreadPersistent(
+ const BasicCrossThreadPersistent& other,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicCrossThreadPersistent(loc) {
+ *this = other;
+ }
+
+ BasicCrossThreadPersistent(
+ BasicCrossThreadPersistent&& other,
+ const SourceLocation& loc = SourceLocation::Current()) noexcept {
+ // Invoke operator=.
+ *this = std::move(other);
+ }
+
+ BasicCrossThreadPersistent& operator=(
+ const BasicCrossThreadPersistent& other) {
+ PersistentRegionLock guard;
+ AssignUnsafe(other.Get());
+ return *this;
+ }
+
+ template ::value>>
+ BasicCrossThreadPersistent& operator=(
+ const BasicCrossThreadPersistent& other) {
+ PersistentRegionLock guard;
+ AssignUnsafe(other.Get());
+ return *this;
+ }
+
+ BasicCrossThreadPersistent& operator=(BasicCrossThreadPersistent&& other) {
+ if (this == &other) return *this;
+ Clear();
+ PersistentRegionLock guard;
+ PersistentBase::operator=(std::move(other));
+ LocationPolicy::operator=(std::move(other));
+ if (!IsValid(GetValue())) return *this;
+ GetNode()->UpdateOwner(this);
+ other.SetValue(nullptr);
+ other.SetNode(nullptr);
+ this->CheckPointer(Get());
+ return *this;
+ }
+
+ BasicCrossThreadPersistent& operator=(T* other) {
+ Assign(other);
+ return *this;
+ }
+
+ // Assignment from member.
+ template ::value>>
+ BasicCrossThreadPersistent& operator=(
+ internal::BasicMember
+ member) {
+ return operator=(member.Get());
+ }
+
+ BasicCrossThreadPersistent& operator=(std::nullptr_t) {
+ Clear();
+ return *this;
+ }
+
+ BasicCrossThreadPersistent& operator=(SentinelPointer s) {
+ Assign(s);
+ return *this;
+ }
+
+ /**
+ * Returns a pointer to the stored object.
+ *
+ * Note: **Not thread-safe.**
+ *
+ * \returns a pointer to the stored object.
+ */
+ // CFI cast exemption to allow passing SentinelPointer through T* and support
+ // heterogeneous assignments between different Member and Persistent handles
+ // based on their actual types.
+ V8_CLANG_NO_SANITIZE("cfi-unrelated-cast") T* Get() const {
+ return static_cast(const_cast(GetValue()));
+ }
+
+ /**
+ * Clears the stored object.
+ */
+ void Clear() {
+ // Simplified version of `Assign()` to allow calling without a complete type
+ // `T`.
+ const void* old_value = GetValue();
+ if (IsValid(old_value)) {
+ PersistentRegionLock guard;
+ old_value = GetValue();
+ // The fast path check (IsValid()) does not acquire the lock. Reload
+ // the value to ensure the reference has not been cleared.
+ if (IsValid(old_value)) {
+ CrossThreadPersistentRegion& region =
+ this->GetPersistentRegion(old_value);
+ region.FreeNode(GetNode());
+ SetNode(nullptr);
+ } else {
+ CPPGC_DCHECK(!GetNode());
+ }
+ }
+ SetValue(nullptr);
+ }
+
+ /**
+ * Returns a pointer to the stored object and releases it.
+ *
+ * Note: **Not thread-safe.**
+ *
+ * \returns a pointer to the stored object.
+ */
+ T* Release() {
+ T* result = Get();
+ Clear();
+ return result;
+ }
+
+ /**
+ * Conversio to boolean.
+ *
+ * Note: **Not thread-safe.**
+ *
+ * \returns true if an actual object has been stored and false otherwise.
+ */
+ explicit operator bool() const { return Get(); }
+
+ /**
+ * Conversion to object of type T.
+ *
+ * Note: **Not thread-safe.**
+ *
+ * \returns the object.
+ */
+ operator T*() const { return Get(); }
+
+ /**
+ * Dereferences the stored object.
+ *
+ * Note: **Not thread-safe.**
+ */
+ T* operator->() const { return Get(); }
+ T& operator*() const { return *Get(); }
+
+ template
+ BasicCrossThreadPersistent
+ To() const {
+ using OtherBasicCrossThreadPersistent =
+ BasicCrossThreadPersistent;
+ PersistentRegionLock guard;
+ return OtherBasicCrossThreadPersistent(
+ typename OtherBasicCrossThreadPersistent::UnsafeCtorTag(),
+ static_cast(Get()));
+ }
+
+ template ::IsStrongPersistent::value>::type>
+ BasicCrossThreadPersistent
+ Lock() const {
+ return BasicCrossThreadPersistent<
+ U, internal::StrongCrossThreadPersistentPolicy>(*this);
+ }
+
+ private:
+ static bool IsValid(const void* ptr) {
+ return ptr && ptr != kSentinelPointer;
+ }
+
+ static void Trace(Visitor* v, const void* ptr) {
+ const auto* handle = static_cast(ptr);
+ v->TraceRoot(*handle, handle->Location());
+ }
+
+ void Assign(T* ptr) {
+ const void* old_value = GetValue();
+ if (IsValid(old_value)) {
+ PersistentRegionLock guard;
+ old_value = GetValue();
+ // The fast path check (IsValid()) does not acquire the lock. Reload
+ // the value to ensure the reference has not been cleared.
+ if (IsValid(old_value)) {
+ CrossThreadPersistentRegion& region =
+ this->GetPersistentRegion(old_value);
+ if (IsValid(ptr) && (®ion == &this->GetPersistentRegion(ptr))) {
+ SetValue(ptr);
+ this->CheckPointer(ptr);
+ return;
+ }
+ region.FreeNode(GetNode());
+ SetNode(nullptr);
+ } else {
+ CPPGC_DCHECK(!GetNode());
+ }
+ }
+ SetValue(ptr);
+ if (!IsValid(ptr)) return;
+ PersistentRegionLock guard;
+ SetNode(this->GetPersistentRegion(ptr).AllocateNode(this, &Trace));
+ this->CheckPointer(ptr);
+ }
+
+ void AssignUnsafe(T* ptr) {
+ PersistentRegionLock::AssertLocked();
+ const void* old_value = GetValue();
+ if (IsValid(old_value)) {
+ CrossThreadPersistentRegion& region =
+ this->GetPersistentRegion(old_value);
+ if (IsValid(ptr) && (®ion == &this->GetPersistentRegion(ptr))) {
+ SetValue(ptr);
+ this->CheckPointer(ptr);
+ return;
+ }
+ region.FreeNode(GetNode());
+ SetNode(nullptr);
+ }
+ SetValue(ptr);
+ if (!IsValid(ptr)) return;
+ SetNode(this->GetPersistentRegion(ptr).AllocateNode(this, &Trace));
+ this->CheckPointer(ptr);
+ }
+
+ void ClearFromGC() const {
+ if (IsValid(GetValueFromGC())) {
+ WeaknessPolicy::GetPersistentRegion(GetValueFromGC())
+ .FreeNode(GetNodeFromGC());
+ CrossThreadPersistentBase::ClearFromGC();
+ }
+ }
+
+ // See Get() for details.
+ V8_CLANG_NO_SANITIZE("cfi-unrelated-cast")
+ T* GetFromGC() const {
+ return static_cast(const_cast(GetValueFromGC()));
+ }
+
+ friend class cppgc::Visitor;
+};
+
+template
+struct IsWeak<
+ BasicCrossThreadPersistent>
+ : std::true_type {};
+
+} // namespace internal
+
+namespace subtle {
+
+/**
+ * **DO NOT USE: Has known caveats, see below.**
+ *
+ * CrossThreadPersistent allows retaining objects from threads other than the
+ * thread the owning heap is operating on.
+ *
+ * Known caveats:
+ * - Does not protect the heap owning an object from terminating.
+ * - Reaching transitively through the graph is unsupported as objects may be
+ * moved concurrently on the thread owning the object.
+ */
+template
+using CrossThreadPersistent = internal::BasicCrossThreadPersistent<
+ T, internal::StrongCrossThreadPersistentPolicy>;
+
+/**
+ * **DO NOT USE: Has known caveats, see below.**
+ *
+ * CrossThreadPersistent allows weakly retaining objects from threads other than
+ * the thread the owning heap is operating on.
+ *
+ * Known caveats:
+ * - Does not protect the heap owning an object from terminating.
+ * - Reaching transitively through the graph is unsupported as objects may be
+ * moved concurrently on the thread owning the object.
+ */
+template
+using WeakCrossThreadPersistent = internal::BasicCrossThreadPersistent<
+ T, internal::WeakCrossThreadPersistentPolicy>;
+
+} // namespace subtle
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_CROSS_THREAD_PERSISTENT_H_
diff --git a/libs/android/libnode/include/node/cppgc/custom-space.h b/libs/android/libnode/include/node/cppgc/custom-space.h
new file mode 100644
index 00000000..757c4fde
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/custom-space.h
@@ -0,0 +1,97 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_CUSTOM_SPACE_H_
+#define INCLUDE_CPPGC_CUSTOM_SPACE_H_
+
+#include
+
+namespace cppgc {
+
+/**
+ * Index identifying a custom space.
+ */
+struct CustomSpaceIndex {
+ constexpr CustomSpaceIndex(size_t value) : value(value) {} // NOLINT
+ size_t value;
+};
+
+/**
+ * Top-level base class for custom spaces. Users must inherit from CustomSpace
+ * below.
+ */
+class CustomSpaceBase {
+ public:
+ virtual ~CustomSpaceBase() = default;
+ virtual CustomSpaceIndex GetCustomSpaceIndex() const = 0;
+ virtual bool IsCompactable() const = 0;
+};
+
+/**
+ * Base class custom spaces should directly inherit from. The class inheriting
+ * from `CustomSpace` must define `kSpaceIndex` as unique space index. These
+ * indices need for form a sequence starting at 0.
+ *
+ * Example:
+ * \code
+ * class CustomSpace1 : public CustomSpace {
+ * public:
+ * static constexpr CustomSpaceIndex kSpaceIndex = 0;
+ * };
+ * class CustomSpace2 : public CustomSpace {
+ * public:
+ * static constexpr CustomSpaceIndex kSpaceIndex = 1;
+ * };
+ * \endcode
+ */
+template
+class CustomSpace : public CustomSpaceBase {
+ public:
+ /**
+ * Compaction is only supported on spaces that manually manage slots
+ * recording.
+ */
+ static constexpr bool kSupportsCompaction = false;
+
+ CustomSpaceIndex GetCustomSpaceIndex() const final {
+ return ConcreteCustomSpace::kSpaceIndex;
+ }
+ bool IsCompactable() const final {
+ return ConcreteCustomSpace::kSupportsCompaction;
+ }
+};
+
+/**
+ * User-overridable trait that allows pinning types to custom spaces.
+ */
+template
+struct SpaceTrait {
+ using Space = void;
+};
+
+namespace internal {
+
+template
+struct IsAllocatedOnCompactableSpaceImpl {
+ static constexpr bool value = CustomSpace::kSupportsCompaction;
+};
+
+template <>
+struct IsAllocatedOnCompactableSpaceImpl {
+ // Non-custom spaces are by default not compactable.
+ static constexpr bool value = false;
+};
+
+template
+struct IsAllocatedOnCompactableSpace {
+ public:
+ static constexpr bool value =
+ IsAllocatedOnCompactableSpaceImpl::Space>::value;
+};
+
+} // namespace internal
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_CUSTOM_SPACE_H_
diff --git a/libs/android/libnode/include/node/cppgc/default-platform.h b/libs/android/libnode/include/node/cppgc/default-platform.h
new file mode 100644
index 00000000..2ccdeddd
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/default-platform.h
@@ -0,0 +1,75 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_DEFAULT_PLATFORM_H_
+#define INCLUDE_CPPGC_DEFAULT_PLATFORM_H_
+
+#include
+#include
+
+#include "cppgc/platform.h"
+#include "libplatform/libplatform.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+/**
+ * Platform provided by cppgc. Uses V8's DefaultPlatform provided by
+ * libplatform internally. Exception: `GetForegroundTaskRunner()`, see below.
+ */
+class V8_EXPORT DefaultPlatform : public Platform {
+ public:
+ /**
+ * Use this method instead of 'cppgc::InitializeProcess' when using
+ * 'cppgc::DefaultPlatform'. 'cppgc::DefaultPlatform::InitializeProcess'
+ * will initialize cppgc and v8 if needed (for non-standalone builds).
+ *
+ * \param platform DefaultPlatform instance used to initialize cppgc/v8.
+ */
+ static void InitializeProcess(DefaultPlatform* platform);
+
+ using IdleTaskSupport = v8::platform::IdleTaskSupport;
+ explicit DefaultPlatform(
+ int thread_pool_size = 0,
+ IdleTaskSupport idle_task_support = IdleTaskSupport::kDisabled,
+ std::unique_ptr tracing_controller = {})
+ : v8_platform_(v8::platform::NewDefaultPlatform(
+ thread_pool_size, idle_task_support,
+ v8::platform::InProcessStackDumping::kDisabled,
+ std::move(tracing_controller))) {}
+
+ cppgc::PageAllocator* GetPageAllocator() override {
+ return v8_platform_->GetPageAllocator();
+ }
+
+ double MonotonicallyIncreasingTime() override {
+ return v8_platform_->MonotonicallyIncreasingTime();
+ }
+
+ std::shared_ptr GetForegroundTaskRunner() override {
+ // V8's default platform creates a new task runner when passed the
+ // `v8::Isolate` pointer the first time. For non-default platforms this will
+ // require getting the appropriate task runner.
+ return v8_platform_->GetForegroundTaskRunner(kNoIsolate);
+ }
+
+ std::unique_ptr PostJob(
+ cppgc::TaskPriority priority,
+ std::unique_ptr job_task) override {
+ return v8_platform_->PostJob(priority, std::move(job_task));
+ }
+
+ TracingController* GetTracingController() override {
+ return v8_platform_->GetTracingController();
+ }
+
+ protected:
+ static constexpr v8::Isolate* kNoIsolate = nullptr;
+
+ std::unique_ptr v8_platform_;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_DEFAULT_PLATFORM_H_
diff --git a/libs/android/libnode/include/node/cppgc/ephemeron-pair.h b/libs/android/libnode/include/node/cppgc/ephemeron-pair.h
new file mode 100644
index 00000000..e16cf1f0
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/ephemeron-pair.h
@@ -0,0 +1,30 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_EPHEMERON_PAIR_H_
+#define INCLUDE_CPPGC_EPHEMERON_PAIR_H_
+
+#include "cppgc/liveness-broker.h"
+#include "cppgc/member.h"
+
+namespace cppgc {
+
+/**
+ * An ephemeron pair is used to conditionally retain an object.
+ * The `value` will be kept alive only if the `key` is alive.
+ */
+template
+struct EphemeronPair {
+ EphemeronPair(K* k, V* v) : key(k), value(v) {}
+ WeakMember key;
+ Member value;
+
+ void ClearValueIfKeyIsDead(const LivenessBroker& broker) {
+ if (!broker.IsHeapObjectAlive(key)) value = nullptr;
+ }
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_EPHEMERON_PAIR_H_
diff --git a/libs/android/libnode/include/node/cppgc/explicit-management.h b/libs/android/libnode/include/node/cppgc/explicit-management.h
new file mode 100644
index 00000000..cdb6af48
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/explicit-management.h
@@ -0,0 +1,82 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_EXPLICIT_MANAGEMENT_H_
+#define INCLUDE_CPPGC_EXPLICIT_MANAGEMENT_H_
+
+#include
+
+#include "cppgc/allocation.h"
+#include "cppgc/internal/logging.h"
+#include "cppgc/type-traits.h"
+
+namespace cppgc {
+
+class HeapHandle;
+
+namespace internal {
+
+V8_EXPORT void FreeUnreferencedObject(HeapHandle&, void*);
+V8_EXPORT bool Resize(void*, size_t);
+
+} // namespace internal
+
+namespace subtle {
+
+/**
+ * Informs the garbage collector that `object` can be immediately reclaimed. The
+ * destructor may not be invoked immediately but only on next garbage
+ * collection.
+ *
+ * It is up to the embedder to guarantee that no other object holds a reference
+ * to `object` after calling `FreeUnreferencedObject()`. In case such a
+ * reference exists, it's use results in a use-after-free.
+ *
+ * To aid in using the API, `FreeUnreferencedObject()` may be called from
+ * destructors on objects that would be reclaimed in the same garbage collection
+ * cycle.
+ *
+ * \param heap_handle The corresponding heap.
+ * \param object Reference to an object that is of type `GarbageCollected` and
+ * should be immediately reclaimed.
+ */
+template
+void FreeUnreferencedObject(HeapHandle& heap_handle, T& object) {
+ static_assert(IsGarbageCollectedTypeV,
+ "Object must be of type GarbageCollected.");
+ internal::FreeUnreferencedObject(heap_handle, &object);
+}
+
+/**
+ * Tries to resize `object` of type `T` with additional bytes on top of
+ * sizeof(T). Resizing is only useful with trailing inlined storage, see e.g.
+ * `MakeGarbageCollected(AllocationHandle&, AdditionalBytes)`.
+ *
+ * `Resize()` performs growing or shrinking as needed and may skip the operation
+ * for internal reasons, see return value.
+ *
+ * It is up to the embedder to guarantee that in case of shrinking a larger
+ * object down, the reclaimed area is not used anymore. Any subsequent use
+ * results in a use-after-free.
+ *
+ * The `object` must be live when calling `Resize()`.
+ *
+ * \param object Reference to an object that is of type `GarbageCollected` and
+ * should be resized.
+ * \param additional_bytes Bytes in addition to sizeof(T) that the object should
+ * provide.
+ * \returns true when the operation was successful and the result can be relied
+ * on, and false otherwise.
+ */
+template
+bool Resize(T& object, AdditionalBytes additional_bytes) {
+ static_assert(IsGarbageCollectedTypeV,
+ "Object must be of type GarbageCollected.");
+ return internal::Resize(&object, sizeof(T) + additional_bytes.value);
+}
+
+} // namespace subtle
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_EXPLICIT_MANAGEMENT_H_
diff --git a/libs/android/libnode/include/node/cppgc/garbage-collected.h b/libs/android/libnode/include/node/cppgc/garbage-collected.h
new file mode 100644
index 00000000..a3839e1b
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/garbage-collected.h
@@ -0,0 +1,117 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_GARBAGE_COLLECTED_H_
+#define INCLUDE_CPPGC_GARBAGE_COLLECTED_H_
+
+#include
+
+#include "cppgc/internal/api-constants.h"
+#include "cppgc/platform.h"
+#include "cppgc/trace-trait.h"
+#include "cppgc/type-traits.h"
+
+namespace cppgc {
+
+class Visitor;
+
+namespace internal {
+
+class GarbageCollectedBase {
+ public:
+ // Must use MakeGarbageCollected.
+ void* operator new(size_t) = delete;
+ void* operator new[](size_t) = delete;
+ // The garbage collector is taking care of reclaiming the object. Also,
+ // virtual destructor requires an unambiguous, accessible 'operator delete'.
+ void operator delete(void*) {
+#ifdef V8_ENABLE_CHECKS
+ internal::Abort();
+#endif // V8_ENABLE_CHECKS
+ }
+ void operator delete[](void*) = delete;
+
+ protected:
+ GarbageCollectedBase() = default;
+};
+
+} // namespace internal
+
+/**
+ * Base class for managed objects. Only descendent types of `GarbageCollected`
+ * can be constructed using `MakeGarbageCollected()`. Must be inherited from as
+ * left-most base class.
+ *
+ * Types inheriting from GarbageCollected must provide a method of
+ * signature `void Trace(cppgc::Visitor*) const` that dispatchs all managed
+ * pointers to the visitor and delegates to garbage-collected base classes.
+ * The method must be virtual if the type is not directly a child of
+ * GarbageCollected and marked as final.
+ *
+ * \code
+ * // Example using final class.
+ * class FinalType final : public GarbageCollected {
+ * public:
+ * void Trace(cppgc::Visitor* visitor) const {
+ * // Dispatch using visitor->Trace(...);
+ * }
+ * };
+ *
+ * // Example using non-final base class.
+ * class NonFinalBase : public GarbageCollected {
+ * public:
+ * virtual void Trace(cppgc::Visitor*) const {}
+ * };
+ *
+ * class FinalChild final : public NonFinalBase {
+ * public:
+ * void Trace(cppgc::Visitor* visitor) const final {
+ * // Dispatch using visitor->Trace(...);
+ * NonFinalBase::Trace(visitor);
+ * }
+ * };
+ * \endcode
+ */
+template
+class GarbageCollected : public internal::GarbageCollectedBase {
+ public:
+ using IsGarbageCollectedTypeMarker = void;
+ using ParentMostGarbageCollectedType = T;
+
+ protected:
+ GarbageCollected() = default;
+};
+
+/**
+ * Base class for managed mixin objects. Such objects cannot be constructed
+ * directly but must be mixed into the inheritance hierarchy of a
+ * GarbageCollected object.
+ *
+ * Types inheriting from GarbageCollectedMixin must override a virtual method
+ * of signature `void Trace(cppgc::Visitor*) const` that dispatchs all managed
+ * pointers to the visitor and delegates to base classes.
+ *
+ * \code
+ * class Mixin : public GarbageCollectedMixin {
+ * public:
+ * void Trace(cppgc::Visitor* visitor) const override {
+ * // Dispatch using visitor->Trace(...);
+ * }
+ * };
+ * \endcode
+ */
+class GarbageCollectedMixin : public internal::GarbageCollectedBase {
+ public:
+ using IsGarbageCollectedMixinTypeMarker = void;
+
+ /**
+ * This Trace method must be overriden by objects inheriting from
+ * GarbageCollectedMixin.
+ */
+ virtual void Trace(cppgc::Visitor*) const {}
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_GARBAGE_COLLECTED_H_
diff --git a/libs/android/libnode/include/node/cppgc/heap-consistency.h b/libs/android/libnode/include/node/cppgc/heap-consistency.h
new file mode 100644
index 00000000..8e603d5d
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/heap-consistency.h
@@ -0,0 +1,253 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_HEAP_CONSISTENCY_H_
+#define INCLUDE_CPPGC_HEAP_CONSISTENCY_H_
+
+#include
+
+#include "cppgc/internal/write-barrier.h"
+#include "cppgc/macros.h"
+#include "cppgc/trace-trait.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class HeapHandle;
+
+namespace subtle {
+
+/**
+ * **DO NOT USE: Use the appropriate managed types.**
+ *
+ * Consistency helpers that aid in maintaining a consistent internal state of
+ * the garbage collector.
+ */
+class HeapConsistency final {
+ public:
+ using WriteBarrierParams = internal::WriteBarrier::Params;
+ using WriteBarrierType = internal::WriteBarrier::Type;
+
+ /**
+ * Gets the required write barrier type for a specific write.
+ *
+ * \param slot Slot containing the pointer to the object. The slot itself
+ * must reside in an object that has been allocated using
+ * `MakeGarbageCollected()`.
+ * \param value The pointer to the object. May be an interior pointer to an
+ * interface of the actual object.
+ * \param params Parameters that may be used for actual write barrier calls.
+ * Only filled if return value indicates that a write barrier is needed. The
+ * contents of the `params` are an implementation detail.
+ * \returns whether a write barrier is needed and which barrier to invoke.
+ */
+ static V8_INLINE WriteBarrierType GetWriteBarrierType(
+ const void* slot, const void* value, WriteBarrierParams& params) {
+ return internal::WriteBarrier::GetWriteBarrierType(slot, value, params);
+ }
+
+ /**
+ * Gets the required write barrier type for a specific write.
+ *
+ * \param slot Slot to some part of an object. The object must not necessarily
+ have been allocated using `MakeGarbageCollected()` but can also live
+ off-heap or on stack.
+ * \param params Parameters that may be used for actual write barrier calls.
+ * Only filled if return value indicates that a write barrier is needed. The
+ * contents of the `params` are an implementation detail.
+ * \param callback Callback returning the corresponding heap handle. The
+ * callback is only invoked if the heap cannot otherwise be figured out. The
+ * callback must not allocate.
+ * \returns whether a write barrier is needed and which barrier to invoke.
+ */
+ template
+ static V8_INLINE WriteBarrierType
+ GetWriteBarrierType(const void* slot, WriteBarrierParams& params,
+ HeapHandleCallback callback) {
+ return internal::WriteBarrier::GetWriteBarrierType(slot, params, callback);
+ }
+
+ /**
+ * Gets the required write barrier type for a specific write.
+ * This version is meant to be used in conjunction with with a marking write
+ * barrier barrier which doesn't consider the slot.
+ *
+ * \param value The pointer to the object. May be an interior pointer to an
+ * interface of the actual object.
+ * \param params Parameters that may be used for actual write barrier calls.
+ * Only filled if return value indicates that a write barrier is needed. The
+ * contents of the `params` are an implementation detail.
+ * \returns whether a write barrier is needed and which barrier to invoke.
+ */
+ static V8_INLINE WriteBarrierType
+ GetWriteBarrierType(const void* value, WriteBarrierParams& params) {
+ return internal::WriteBarrier::GetWriteBarrierType(value, params);
+ }
+
+ /**
+ * Conservative Dijkstra-style write barrier that processes an object if it
+ * has not yet been processed.
+ *
+ * \param params The parameters retrieved from `GetWriteBarrierType()`.
+ * \param object The pointer to the object. May be an interior pointer to a
+ * an interface of the actual object.
+ */
+ static V8_INLINE void DijkstraWriteBarrier(const WriteBarrierParams& params,
+ const void* object) {
+ internal::WriteBarrier::DijkstraMarkingBarrier(params, object);
+ }
+
+ /**
+ * Conservative Dijkstra-style write barrier that processes a range of
+ * elements if they have not yet been processed.
+ *
+ * \param params The parameters retrieved from `GetWriteBarrierType()`.
+ * \param first_element Pointer to the first element that should be processed.
+ * The slot itself must reside in an object that has been allocated using
+ * `MakeGarbageCollected()`.
+ * \param element_size Size of the element in bytes.
+ * \param number_of_elements Number of elements that should be processed,
+ * starting with `first_element`.
+ * \param trace_callback The trace callback that should be invoked for each
+ * element if necessary.
+ */
+ static V8_INLINE void DijkstraWriteBarrierRange(
+ const WriteBarrierParams& params, const void* first_element,
+ size_t element_size, size_t number_of_elements,
+ TraceCallback trace_callback) {
+ internal::WriteBarrier::DijkstraMarkingBarrierRange(
+ params, first_element, element_size, number_of_elements,
+ trace_callback);
+ }
+
+ /**
+ * Steele-style write barrier that re-processes an object if it has already
+ * been processed.
+ *
+ * \param params The parameters retrieved from `GetWriteBarrierType()`.
+ * \param object The pointer to the object which must point to an object that
+ * has been allocated using `MakeGarbageCollected()`. Interior pointers are
+ * not supported.
+ */
+ static V8_INLINE void SteeleWriteBarrier(const WriteBarrierParams& params,
+ const void* object) {
+ internal::WriteBarrier::SteeleMarkingBarrier(params, object);
+ }
+
+ /**
+ * Generational barrier for maintaining consistency when running with multiple
+ * generations.
+ *
+ * \param params The parameters retrieved from `GetWriteBarrierType()`.
+ * \param slot Slot containing the pointer to the object. The slot itself
+ * must reside in an object that has been allocated using
+ * `MakeGarbageCollected()`.
+ */
+ static V8_INLINE void GenerationalBarrier(const WriteBarrierParams& params,
+ const void* slot) {
+ internal::WriteBarrier::GenerationalBarrier(params, slot);
+ }
+
+ private:
+ HeapConsistency() = delete;
+};
+
+/**
+ * Disallows garbage collection finalizations. Any garbage collection triggers
+ * result in a crash when in this scope.
+ *
+ * Note that the garbage collector already covers paths that can lead to garbage
+ * collections, so user code does not require checking
+ * `IsGarbageCollectionAllowed()` before allocations.
+ */
+class V8_EXPORT V8_NODISCARD DisallowGarbageCollectionScope final {
+ CPPGC_STACK_ALLOCATED();
+
+ public:
+ /**
+ * \returns whether garbage collections are currently allowed.
+ */
+ static bool IsGarbageCollectionAllowed(HeapHandle& heap_handle);
+
+ /**
+ * Enters a disallow garbage collection scope. Must be paired with `Leave()`.
+ * Prefer a scope instance of `DisallowGarbageCollectionScope`.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ static void Enter(HeapHandle& heap_handle);
+
+ /**
+ * Leaves a disallow garbage collection scope. Must be paired with `Enter()`.
+ * Prefer a scope instance of `DisallowGarbageCollectionScope`.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ static void Leave(HeapHandle& heap_handle);
+
+ /**
+ * Constructs a scoped object that automatically enters and leaves a disallow
+ * garbage collection scope based on its lifetime.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ explicit DisallowGarbageCollectionScope(HeapHandle& heap_handle);
+ ~DisallowGarbageCollectionScope();
+
+ DisallowGarbageCollectionScope(const DisallowGarbageCollectionScope&) =
+ delete;
+ DisallowGarbageCollectionScope& operator=(
+ const DisallowGarbageCollectionScope&) = delete;
+
+ private:
+ HeapHandle& heap_handle_;
+};
+
+/**
+ * Avoids invoking garbage collection finalizations. Already running garbage
+ * collection phase are unaffected by this scope.
+ *
+ * Should only be used temporarily as the scope has an impact on memory usage
+ * and follow up garbage collections.
+ */
+class V8_EXPORT V8_NODISCARD NoGarbageCollectionScope final {
+ CPPGC_STACK_ALLOCATED();
+
+ public:
+ /**
+ * Enters a no garbage collection scope. Must be paired with `Leave()`. Prefer
+ * a scope instance of `NoGarbageCollectionScope`.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ static void Enter(HeapHandle& heap_handle);
+
+ /**
+ * Leaves a no garbage collection scope. Must be paired with `Enter()`. Prefer
+ * a scope instance of `NoGarbageCollectionScope`.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ static void Leave(HeapHandle& heap_handle);
+
+ /**
+ * Constructs a scoped object that automatically enters and leaves a no
+ * garbage collection scope based on its lifetime.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ explicit NoGarbageCollectionScope(HeapHandle& heap_handle);
+ ~NoGarbageCollectionScope();
+
+ NoGarbageCollectionScope(const NoGarbageCollectionScope&) = delete;
+ NoGarbageCollectionScope& operator=(const NoGarbageCollectionScope&) = delete;
+
+ private:
+ HeapHandle& heap_handle_;
+};
+
+} // namespace subtle
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_HEAP_CONSISTENCY_H_
diff --git a/libs/android/libnode/include/node/cppgc/heap-state.h b/libs/android/libnode/include/node/cppgc/heap-state.h
new file mode 100644
index 00000000..3fd6b54a
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/heap-state.h
@@ -0,0 +1,70 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_HEAP_STATE_H_
+#define INCLUDE_CPPGC_HEAP_STATE_H_
+
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class HeapHandle;
+
+namespace subtle {
+
+/**
+ * Helpers to peek into heap-internal state.
+ */
+class V8_EXPORT HeapState final {
+ public:
+ /**
+ * Returns whether the garbage collector is marking. This API is experimental
+ * and is expected to be removed in future.
+ *
+ * \param heap_handle The corresponding heap.
+ * \returns true if the garbage collector is currently marking, and false
+ * otherwise.
+ */
+ static bool IsMarking(const HeapHandle& heap_handle);
+
+ /*
+ * Returns whether the garbage collector is sweeping. This API is experimental
+ * and is expected to be removed in future.
+ *
+ * \param heap_handle The corresponding heap.
+ * \returns true if the garbage collector is currently sweeping, and false
+ * otherwise.
+ */
+ static bool IsSweeping(const HeapHandle& heap_handle);
+
+ /**
+ * Returns whether the garbage collector is in the atomic pause, i.e., the
+ * mutator is stopped from running. This API is experimental and is expected
+ * to be removed in future.
+ *
+ * \param heap_handle The corresponding heap.
+ * \returns true if the garbage collector is currently in the atomic pause,
+ * and false otherwise.
+ */
+ static bool IsInAtomicPause(const HeapHandle& heap_handle);
+
+ /**
+ * Returns whether the last garbage collection was finalized conservatively
+ * (i.e., with a non-empty stack). This API is experimental and is expected to
+ * be removed in future.
+ *
+ * \param heap_handle The corresponding heap.
+ * \returns true if the last garbage collection was finalized conservatively,
+ * and false otherwise.
+ */
+ static bool PreviousGCWasConservative(const HeapHandle& heap_handle);
+
+ private:
+ HeapState() = delete;
+};
+
+} // namespace subtle
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_HEAP_STATE_H_
diff --git a/libs/android/libnode/include/node/cppgc/heap-statistics.h b/libs/android/libnode/include/node/cppgc/heap-statistics.h
new file mode 100644
index 00000000..8e626596
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/heap-statistics.h
@@ -0,0 +1,120 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_HEAP_STATISTICS_H_
+#define INCLUDE_CPPGC_HEAP_STATISTICS_H_
+
+#include
+#include
+#include
+#include
+
+namespace cppgc {
+
+/**
+ * `HeapStatistics` contains memory consumption and utilization statistics for a
+ * cppgc heap.
+ */
+struct HeapStatistics final {
+ /**
+ * Specifies the detail level of the heap statistics. Brief statistics contain
+ * only the top-level allocated and used memory statistics for the entire
+ * heap. Detailed statistics also contain a break down per space and page, as
+ * well as freelist statistics and object type histograms. Note that used
+ * memory reported by brief statistics and detailed statistics might differ
+ * slightly.
+ */
+ enum DetailLevel : uint8_t {
+ kBrief,
+ kDetailed,
+ };
+
+ /**
+ * Object statistics for a single type.
+ */
+ struct ObjectStatsEntry {
+ /**
+ * Number of allocated bytes.
+ */
+ size_t allocated_bytes;
+ /**
+ * Number of allocated objects.
+ */
+ size_t object_count;
+ };
+
+ /**
+ * Page granularity statistics. For each page the statistics record the
+ * allocated memory size and overall used memory size for the page.
+ */
+ struct PageStatistics {
+ /** Overall committed amount of memory for the page. */
+ size_t committed_size_bytes = 0;
+ /** Resident amount of memory held by the page. */
+ size_t resident_size_bytes = 0;
+ /** Amount of memory actually used on the page. */
+ size_t used_size_bytes = 0;
+ /** Statistics for object allocated on the page. Filled only when
+ * NameProvider::HideInternalNames() is false. */
+ std::vector object_statistics;
+ };
+
+ /**
+ * Statistics of the freelist (used only in non-large object spaces). For
+ * each bucket in the freelist the statistics record the bucket size, the
+ * number of freelist entries in the bucket, and the overall allocated memory
+ * consumed by these freelist entries.
+ */
+ struct FreeListStatistics {
+ /** bucket sizes in the freelist. */
+ std::vector bucket_size;
+ /** number of freelist entries per bucket. */
+ std::vector free_count;
+ /** memory size consumed by freelist entries per size. */
+ std::vector free_size;
+ };
+
+ /**
+ * Space granularity statistics. For each space the statistics record the
+ * space name, the amount of allocated memory and overall used memory for the
+ * space. The statistics also contain statistics for each of the space's
+ * pages, its freelist and the objects allocated on the space.
+ */
+ struct SpaceStatistics {
+ /** The space name */
+ std::string name;
+ /** Overall committed amount of memory for the heap. */
+ size_t committed_size_bytes = 0;
+ /** Resident amount of memory held by the heap. */
+ size_t resident_size_bytes = 0;
+ /** Amount of memory actually used on the space. */
+ size_t used_size_bytes = 0;
+ /** Statistics for each of the pages in the space. */
+ std::vector page_stats;
+ /** Statistics for the freelist of the space. */
+ FreeListStatistics free_list_stats;
+ };
+
+ /** Overall committed amount of memory for the heap. */
+ size_t committed_size_bytes = 0;
+ /** Resident amount of memory help by the heap. */
+ size_t resident_size_bytes = 0;
+ /** Amount of memory actually used on the heap. */
+ size_t used_size_bytes = 0;
+ /** Detail level of this HeapStatistics. */
+ DetailLevel detail_level;
+
+ /** Statistics for each of the spaces in the heap. Filled only when
+ * `detail_level` is `DetailLevel::kDetailed`. */
+ std::vector space_stats;
+
+ /**
+ * Vector of `cppgc::GarbageCollected` type names.
+ */
+ std::vector type_names;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_HEAP_STATISTICS_H_
diff --git a/libs/android/libnode/include/node/cppgc/heap.h b/libs/android/libnode/include/node/cppgc/heap.h
new file mode 100644
index 00000000..136c4fb4
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/heap.h
@@ -0,0 +1,201 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_HEAP_H_
+#define INCLUDE_CPPGC_HEAP_H_
+
+#include
+#include
+#include
+#include
+
+#include "cppgc/common.h"
+#include "cppgc/custom-space.h"
+#include "cppgc/platform.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+/**
+ * cppgc - A C++ garbage collection library.
+ */
+namespace cppgc {
+
+class AllocationHandle;
+
+/**
+ * Implementation details of cppgc. Those details are considered internal and
+ * may change at any point in time without notice. Users should never rely on
+ * the contents of this namespace.
+ */
+namespace internal {
+class Heap;
+} // namespace internal
+
+/**
+ * Used for additional heap APIs.
+ */
+class HeapHandle;
+
+class V8_EXPORT Heap {
+ public:
+ /**
+ * Specifies the stack state the embedder is in.
+ */
+ using StackState = EmbedderStackState;
+
+ /**
+ * Specifies whether conservative stack scanning is supported.
+ */
+ enum class StackSupport : uint8_t {
+ /**
+ * Conservative stack scan is supported.
+ */
+ kSupportsConservativeStackScan,
+ /**
+ * Conservative stack scan is not supported. Embedders may use this option
+ * when using custom infrastructure that is unsupported by the library.
+ */
+ kNoConservativeStackScan,
+ };
+
+ /**
+ * Specifies supported marking types
+ */
+ enum class MarkingType : uint8_t {
+ /**
+ * Atomic stop-the-world marking. This option does not require any write
+ * barriers but is the most intrusive in terms of jank.
+ */
+ kAtomic,
+ /**
+ * Incremental marking, i.e. interleave marking is the rest of the
+ * application on the same thread.
+ */
+ kIncremental,
+ /**
+ * Incremental and concurrent marking.
+ */
+ kIncrementalAndConcurrent
+ };
+
+ /**
+ * Specifies supported sweeping types
+ */
+ enum class SweepingType : uint8_t {
+ /**
+ * Atomic stop-the-world sweeping. All of sweeping is performed at once.
+ */
+ kAtomic,
+ /**
+ * Incremental and concurrent sweeping. Sweeping is split and interleaved
+ * with the rest of the application.
+ */
+ kIncrementalAndConcurrent
+ };
+
+ /**
+ * Constraints for a Heap setup.
+ */
+ struct ResourceConstraints {
+ /**
+ * Allows the heap to grow to some initial size in bytes before triggering
+ * garbage collections. This is useful when it is known that applications
+ * need a certain minimum heap to run to avoid repeatedly invoking the
+ * garbage collector when growing the heap.
+ */
+ size_t initial_heap_size_bytes = 0;
+ };
+
+ /**
+ * Options specifying Heap properties (e.g. custom spaces) when initializing a
+ * heap through `Heap::Create()`.
+ */
+ struct HeapOptions {
+ /**
+ * Creates reasonable defaults for instantiating a Heap.
+ *
+ * \returns the HeapOptions that can be passed to `Heap::Create()`.
+ */
+ static HeapOptions Default() { return {}; }
+
+ /**
+ * Custom spaces added to heap are required to have indices forming a
+ * numbered sequence starting at 0, i.e., their `kSpaceIndex` must
+ * correspond to the index they reside in the vector.
+ */
+ std::vector> custom_spaces;
+
+ /**
+ * Specifies whether conservative stack scan is supported. When conservative
+ * stack scan is not supported, the collector may try to invoke
+ * garbage collections using non-nestable task, which are guaranteed to have
+ * no interesting stack, through the provided Platform. If such tasks are
+ * not supported by the Platform, the embedder must take care of invoking
+ * the GC through `ForceGarbageCollectionSlow()`.
+ */
+ StackSupport stack_support = StackSupport::kSupportsConservativeStackScan;
+
+ /**
+ * Specifies which types of marking are supported by the heap.
+ */
+ MarkingType marking_support = MarkingType::kIncrementalAndConcurrent;
+
+ /**
+ * Specifies which types of sweeping are supported by the heap.
+ */
+ SweepingType sweeping_support = SweepingType::kIncrementalAndConcurrent;
+
+ /**
+ * Resource constraints specifying various properties that the internal
+ * GC scheduler follows.
+ */
+ ResourceConstraints resource_constraints;
+ };
+
+ /**
+ * Creates a new heap that can be used for object allocation.
+ *
+ * \param platform implemented and provided by the embedder.
+ * \param options HeapOptions specifying various properties for the Heap.
+ * \returns a new Heap instance.
+ */
+ static std::unique_ptr Create(
+ std::shared_ptr platform,
+ HeapOptions options = HeapOptions::Default());
+
+ virtual ~Heap() = default;
+
+ /**
+ * Forces garbage collection.
+ *
+ * \param source String specifying the source (or caller) triggering a
+ * forced garbage collection.
+ * \param reason String specifying the reason for the forced garbage
+ * collection.
+ * \param stack_state The embedder stack state, see StackState.
+ */
+ void ForceGarbageCollectionSlow(
+ const char* source, const char* reason,
+ StackState stack_state = StackState::kMayContainHeapPointers);
+
+ /**
+ * \returns the opaque handle for allocating objects using
+ * `MakeGarbageCollected()`.
+ */
+ AllocationHandle& GetAllocationHandle();
+
+ /**
+ * \returns the opaque heap handle which may be used to refer to this heap in
+ * other APIs. Valid as long as the underlying `Heap` is alive.
+ */
+ HeapHandle& GetHeapHandle();
+
+ private:
+ Heap() = default;
+
+ friend class internal::Heap;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_HEAP_H_
diff --git a/libs/android/libnode/include/node/cppgc/liveness-broker.h b/libs/android/libnode/include/node/cppgc/liveness-broker.h
new file mode 100644
index 00000000..c94eef0d
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/liveness-broker.h
@@ -0,0 +1,77 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_LIVENESS_BROKER_H_
+#define INCLUDE_CPPGC_LIVENESS_BROKER_H_
+
+#include "cppgc/heap.h"
+#include "cppgc/member.h"
+#include "cppgc/trace-trait.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+namespace internal {
+class LivenessBrokerFactory;
+} // namespace internal
+
+/**
+ * The broker is passed to weak callbacks to allow (temporarily) querying
+ * the liveness state of an object. References to non-live objects must be
+ * cleared when `IsHeapObjectAlive()` returns false.
+ *
+ * \code
+ * class GCedWithCustomWeakCallback final
+ * : public GarbageCollected {
+ * public:
+ * UntracedMember bar;
+ *
+ * void CustomWeakCallbackMethod(const LivenessBroker& broker) {
+ * if (!broker.IsHeapObjectAlive(bar))
+ * bar = nullptr;
+ * }
+ *
+ * void Trace(cppgc::Visitor* visitor) const {
+ * visitor->RegisterWeakCallbackMethod<
+ * GCedWithCustomWeakCallback,
+ * &GCedWithCustomWeakCallback::CustomWeakCallbackMethod>(this);
+ * }
+ * };
+ * \endcode
+ */
+class V8_EXPORT LivenessBroker final {
+ public:
+ template
+ bool IsHeapObjectAlive(const T* object) const {
+ // nullptr objects are considered alive to allow weakness to be used from
+ // stack while running into a conservative GC. Treating nullptr as dead
+ // would mean that e.g. custom collectins could not be strongified on stack.
+ return !object ||
+ IsHeapObjectAliveImpl(
+ TraceTrait::GetTraceDescriptor(object).base_object_payload);
+ }
+
+ template
+ bool IsHeapObjectAlive(const WeakMember& weak_member) const {
+ return (weak_member != kSentinelPointer) &&
+ IsHeapObjectAlive(weak_member.Get());
+ }
+
+ template
+ bool IsHeapObjectAlive(const UntracedMember& untraced_member) const {
+ return (untraced_member != kSentinelPointer) &&
+ IsHeapObjectAlive(untraced_member.Get());
+ }
+
+ private:
+ LivenessBroker() = default;
+
+ bool IsHeapObjectAliveImpl(const void*) const;
+
+ friend class internal::LivenessBrokerFactory;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_LIVENESS_BROKER_H_
diff --git a/libs/android/libnode/include/node/cppgc/macros.h b/libs/android/libnode/include/node/cppgc/macros.h
new file mode 100644
index 00000000..030f397e
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/macros.h
@@ -0,0 +1,26 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_MACROS_H_
+#define INCLUDE_CPPGC_MACROS_H_
+
+#include
+
+#include "cppgc/internal/compiler-specific.h"
+
+namespace cppgc {
+
+// Use if the object is only stack allocated.
+#define CPPGC_STACK_ALLOCATED() \
+ public: \
+ using IsStackAllocatedTypeMarker CPPGC_UNUSED = int; \
+ \
+ private: \
+ void* operator new(size_t) = delete; \
+ void* operator new(size_t, void*) = delete; \
+ static_assert(true, "Force semicolon.")
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_MACROS_H_
diff --git a/libs/android/libnode/include/node/cppgc/member.h b/libs/android/libnode/include/node/cppgc/member.h
new file mode 100644
index 00000000..38105b8e
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/member.h
@@ -0,0 +1,288 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_MEMBER_H_
+#define INCLUDE_CPPGC_MEMBER_H_
+
+#include
+#include
+#include
+
+#include "cppgc/internal/pointer-policies.h"
+#include "cppgc/sentinel-pointer.h"
+#include "cppgc/type-traits.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class Visitor;
+
+namespace internal {
+
+// MemberBase always refers to the object as const object and defers to
+// BasicMember on casting to the right type as needed.
+class MemberBase {
+ protected:
+ struct AtomicInitializerTag {};
+
+ MemberBase() = default;
+ explicit MemberBase(const void* value) : raw_(value) {}
+ MemberBase(const void* value, AtomicInitializerTag) { SetRawAtomic(value); }
+
+ const void** GetRawSlot() const { return &raw_; }
+ const void* GetRaw() const { return raw_; }
+ void SetRaw(void* value) { raw_ = value; }
+
+ const void* GetRawAtomic() const {
+ return reinterpret_cast*>(&raw_)->load(
+ std::memory_order_relaxed);
+ }
+ void SetRawAtomic(const void* value) {
+ reinterpret_cast*>(&raw_)->store(
+ value, std::memory_order_relaxed);
+ }
+
+ void ClearFromGC() const { raw_ = nullptr; }
+
+ private:
+ mutable const void* raw_ = nullptr;
+};
+
+// The basic class from which all Member classes are 'generated'.
+template
+class BasicMember final : private MemberBase, private CheckingPolicy {
+ public:
+ using PointeeType = T;
+
+ constexpr BasicMember() = default;
+ constexpr BasicMember(std::nullptr_t) {} // NOLINT
+ BasicMember(SentinelPointer s) : MemberBase(s) {} // NOLINT
+ BasicMember(T* raw) : MemberBase(raw) { // NOLINT
+ InitializingWriteBarrier();
+ this->CheckPointer(Get());
+ }
+ BasicMember(T& raw) : BasicMember(&raw) {} // NOLINT
+ // Atomic ctor. Using the AtomicInitializerTag forces BasicMember to
+ // initialize using atomic assignments. This is required for preventing
+ // data races with concurrent marking.
+ using AtomicInitializerTag = MemberBase::AtomicInitializerTag;
+ BasicMember(std::nullptr_t, AtomicInitializerTag atomic)
+ : MemberBase(nullptr, atomic) {}
+ BasicMember(SentinelPointer s, AtomicInitializerTag atomic)
+ : MemberBase(s, atomic) {}
+ BasicMember(T* raw, AtomicInitializerTag atomic) : MemberBase(raw, atomic) {
+ InitializingWriteBarrier();
+ this->CheckPointer(Get());
+ }
+ BasicMember(T& raw, AtomicInitializerTag atomic)
+ : BasicMember(&raw, atomic) {}
+ // Copy ctor.
+ BasicMember(const BasicMember& other) : BasicMember(other.Get()) {}
+ // Allow heterogeneous construction.
+ template ::value>>
+ BasicMember( // NOLINT
+ const BasicMember& other)
+ : BasicMember(other.Get()) {}
+ // Move ctor.
+ BasicMember(BasicMember&& other) noexcept : BasicMember(other.Get()) {
+ other.Clear();
+ }
+ // Allow heterogeneous move construction.
+ template ::value>>
+ BasicMember(BasicMember&& other) noexcept
+ : BasicMember(other.Get()) {
+ other.Clear();
+ }
+ // Construction from Persistent.
+ template ::value>>
+ BasicMember(const BasicPersistent& p)
+ : BasicMember(p.Get()) {}
+
+ // Copy assignment.
+ BasicMember& operator=(const BasicMember& other) {
+ return operator=(other.Get());
+ }
+ // Allow heterogeneous copy assignment.
+ template ::value>>
+ BasicMember& operator=(
+ const BasicMember& other) {
+ return operator=(other.Get());
+ }
+ // Move assignment.
+ BasicMember& operator=(BasicMember&& other) noexcept {
+ operator=(other.Get());
+ other.Clear();
+ return *this;
+ }
+ // Heterogeneous move assignment.
+ template ::value>>
+ BasicMember& operator=(BasicMember&& other) noexcept {
+ operator=(other.Get());
+ other.Clear();
+ return *this;
+ }
+ // Assignment from Persistent.
+ template ::value>>
+ BasicMember& operator=(
+ const BasicPersistent&
+ other) {
+ return operator=(other.Get());
+ }
+ BasicMember& operator=(T* other) {
+ SetRawAtomic(other);
+ AssigningWriteBarrier();
+ this->CheckPointer(Get());
+ return *this;
+ }
+ BasicMember& operator=(std::nullptr_t) {
+ Clear();
+ return *this;
+ }
+ BasicMember& operator=(SentinelPointer s) {
+ SetRawAtomic(s);
+ return *this;
+ }
+
+ template
+ void Swap(BasicMember& other) {
+ T* tmp = Get();
+ *this = other;
+ other = tmp;
+ }
+
+ explicit operator bool() const { return Get(); }
+ operator T*() const { return Get(); }
+ T* operator->() const { return Get(); }
+ T& operator*() const { return *Get(); }
+
+ // CFI cast exemption to allow passing SentinelPointer through T* and support
+ // heterogeneous assignments between different Member and Persistent handles
+ // based on their actual types.
+ V8_CLANG_NO_SANITIZE("cfi-unrelated-cast") T* Get() const {
+ // Executed by the mutator, hence non atomic load.
+ //
+ // The const_cast below removes the constness from MemberBase storage. The
+ // following static_cast re-adds any constness if specified through the
+ // user-visible template parameter T.
+ return static_cast(const_cast(MemberBase::GetRaw()));
+ }
+
+ void Clear() { SetRawAtomic(nullptr); }
+
+ T* Release() {
+ T* result = Get();
+ Clear();
+ return result;
+ }
+
+ const T** GetSlotForTesting() const {
+ return reinterpret_cast(GetRawSlot());
+ }
+
+ private:
+ const T* GetRawAtomic() const {
+ return static_cast(MemberBase::GetRawAtomic());
+ }
+
+ void InitializingWriteBarrier() const {
+ WriteBarrierPolicy::InitializingBarrier(GetRawSlot(), GetRaw());
+ }
+ void AssigningWriteBarrier() const {
+ WriteBarrierPolicy::AssigningBarrier(GetRawSlot(), GetRaw());
+ }
+
+ void ClearFromGC() const { MemberBase::ClearFromGC(); }
+
+ T* GetFromGC() const { return Get(); }
+
+ friend class cppgc::Visitor;
+ template
+ friend struct cppgc::TraceTrait;
+};
+
+template
+bool operator==(const BasicMember& member1,
+ const BasicMember& member2) {
+ return member1.Get() == member2.Get();
+}
+
+template
+bool operator!=(const BasicMember& member1,
+ const BasicMember& member2) {
+ return !(member1 == member2);
+}
+
+template
+struct IsWeak<
+ internal::BasicMember>
+ : std::true_type {};
+
+} // namespace internal
+
+/**
+ * Members are used in classes to contain strong pointers to other garbage
+ * collected objects. All Member fields of a class must be traced in the class'
+ * trace method.
+ */
+template
+using Member = internal::BasicMember;
+
+/**
+ * WeakMember is similar to Member in that it is used to point to other garbage
+ * collected objects. However instead of creating a strong pointer to the
+ * object, the WeakMember creates a weak pointer, which does not keep the
+ * pointee alive. Hence if all pointers to to a heap allocated object are weak
+ * the object will be garbage collected. At the time of GC the weak pointers
+ * will automatically be set to null.
+ */
+template
+using WeakMember = internal::BasicMember;
+
+/**
+ * UntracedMember is a pointer to an on-heap object that is not traced for some
+ * reason. Do not use this unless you know what you are doing. Keeping raw
+ * pointers to on-heap objects is prohibited unless used from stack. Pointee
+ * must be kept alive through other means.
+ */
+template
+using UntracedMember = internal::BasicMember;
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_MEMBER_H_
diff --git a/libs/android/libnode/include/node/cppgc/name-provider.h b/libs/android/libnode/include/node/cppgc/name-provider.h
new file mode 100644
index 00000000..224dd4b5
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/name-provider.h
@@ -0,0 +1,65 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_NAME_PROVIDER_H_
+#define INCLUDE_CPPGC_NAME_PROVIDER_H_
+
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+/**
+ * NameProvider allows for providing a human-readable name for garbage-collected
+ * objects.
+ *
+ * There's two cases of names to distinguish:
+ * a. Explicitly specified names via using NameProvider. Such names are always
+ * preserved in the system.
+ * b. Internal names that Oilpan infers from a C++ type on the class hierarchy
+ * of the object. This is not necessarily the type of the actually
+ * instantiated object.
+ *
+ * Depending on the build configuration, Oilpan may hide names, i.e., represent
+ * them with kHiddenName, of case b. to avoid exposing internal details.
+ */
+class V8_EXPORT NameProvider {
+ public:
+ /**
+ * Name that is used when hiding internals.
+ */
+ static constexpr const char kHiddenName[] = "InternalNode";
+
+ /**
+ * Name that is used in case compiler support is missing for composing a name
+ * from C++ types.
+ */
+ static constexpr const char kNoNameDeducible[] = "";
+
+ /**
+ * Indicating whether internal names are hidden or not.
+ *
+ * @returns true if C++ names should be hidden and represented by kHiddenName.
+ */
+ static constexpr bool HideInternalNames() {
+#if CPPGC_SUPPORTS_OBJECT_NAMES
+ return false;
+#else // !CPPGC_SUPPORTS_OBJECT_NAMES
+ return true;
+#endif // !CPPGC_SUPPORTS_OBJECT_NAMES
+ }
+
+ virtual ~NameProvider() = default;
+
+ /**
+ * Specifies a name for the garbage-collected object. Such names will never
+ * be hidden, as they are explicitly specified by the user of this API.
+ *
+ * @returns a human readable name for the object.
+ */
+ virtual const char* GetHumanReadableName() const = 0;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_NAME_PROVIDER_H_
diff --git a/libs/android/libnode/include/node/cppgc/object-size-trait.h b/libs/android/libnode/include/node/cppgc/object-size-trait.h
new file mode 100644
index 00000000..35795596
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/object-size-trait.h
@@ -0,0 +1,58 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_OBJECT_SIZE_TRAIT_H_
+#define INCLUDE_CPPGC_OBJECT_SIZE_TRAIT_H_
+
+#include
+
+#include "cppgc/type-traits.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+namespace internal {
+
+struct V8_EXPORT BaseObjectSizeTrait {
+ protected:
+ static size_t GetObjectSizeForGarbageCollected(const void*);
+ static size_t GetObjectSizeForGarbageCollectedMixin(const void*);
+};
+
+} // namespace internal
+
+namespace subtle {
+
+/**
+ * Trait specifying how to get the size of an object that was allocated using
+ * `MakeGarbageCollected()`. Also supports querying the size with an inner
+ * pointer to a mixin.
+ */
+template >
+struct ObjectSizeTrait;
+
+template
+struct ObjectSizeTrait : cppgc::internal::BaseObjectSizeTrait {
+ static_assert(sizeof(T), "T must be fully defined");
+ static_assert(IsGarbageCollectedTypeV,
+ "T must be of type GarbageCollected or GarbageCollectedMixin");
+
+ static size_t GetSize(const T& object) {
+ return GetObjectSizeForGarbageCollected(&object);
+ }
+};
+
+template
+struct ObjectSizeTrait : cppgc::internal::BaseObjectSizeTrait {
+ static_assert(sizeof(T), "T must be fully defined");
+
+ static size_t GetSize(const T& object) {
+ return GetObjectSizeForGarbageCollectedMixin(&object);
+ }
+};
+
+} // namespace subtle
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_OBJECT_SIZE_TRAIT_H_
diff --git a/libs/android/libnode/include/node/cppgc/persistent.h b/libs/android/libnode/include/node/cppgc/persistent.h
new file mode 100644
index 00000000..b83a4645
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/persistent.h
@@ -0,0 +1,371 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_PERSISTENT_H_
+#define INCLUDE_CPPGC_PERSISTENT_H_
+
+#include
+
+#include "cppgc/internal/persistent-node.h"
+#include "cppgc/internal/pointer-policies.h"
+#include "cppgc/sentinel-pointer.h"
+#include "cppgc/source-location.h"
+#include "cppgc/type-traits.h"
+#include "cppgc/visitor.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class Visitor;
+
+namespace internal {
+
+// PersistentBase always refers to the object as const object and defers to
+// BasicPersistent on casting to the right type as needed.
+class PersistentBase {
+ protected:
+ PersistentBase() = default;
+ explicit PersistentBase(const void* raw) : raw_(raw) {}
+
+ const void* GetValue() const { return raw_; }
+ void SetValue(const void* value) { raw_ = value; }
+
+ PersistentNode* GetNode() const { return node_; }
+ void SetNode(PersistentNode* node) { node_ = node; }
+
+ // Performs a shallow clear which assumes that internal persistent nodes are
+ // destroyed elsewhere.
+ void ClearFromGC() const {
+ raw_ = nullptr;
+ node_ = nullptr;
+ }
+
+ protected:
+ mutable const void* raw_ = nullptr;
+ mutable PersistentNode* node_ = nullptr;
+
+ friend class PersistentRegion;
+};
+
+// The basic class from which all Persistent classes are generated.
+template
+class BasicPersistent final : public PersistentBase,
+ public LocationPolicy,
+ private WeaknessPolicy,
+ private CheckingPolicy {
+ public:
+ using typename WeaknessPolicy::IsStrongPersistent;
+ using PointeeType = T;
+
+ // Null-state/sentinel constructors.
+ BasicPersistent( // NOLINT
+ const SourceLocation& loc = SourceLocation::Current())
+ : LocationPolicy(loc) {}
+
+ BasicPersistent(std::nullptr_t, // NOLINT
+ const SourceLocation& loc = SourceLocation::Current())
+ : LocationPolicy(loc) {}
+
+ BasicPersistent( // NOLINT
+ SentinelPointer s, const SourceLocation& loc = SourceLocation::Current())
+ : PersistentBase(s), LocationPolicy(loc) {}
+
+ // Raw value constructors.
+ BasicPersistent(T* raw, // NOLINT
+ const SourceLocation& loc = SourceLocation::Current())
+ : PersistentBase(raw), LocationPolicy(loc) {
+ if (!IsValid()) return;
+ SetNode(WeaknessPolicy::GetPersistentRegion(GetValue())
+ .AllocateNode(this, &BasicPersistent::Trace));
+ this->CheckPointer(Get());
+ }
+
+ BasicPersistent(T& raw, // NOLINT
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicPersistent(&raw, loc) {}
+
+ // Copy ctor.
+ BasicPersistent(const BasicPersistent& other,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicPersistent(other.Get(), loc) {}
+
+ // Heterogeneous ctor.
+ template ::value>>
+ BasicPersistent(
+ const BasicPersistent& other,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicPersistent(other.Get(), loc) {}
+
+ // Move ctor. The heterogeneous move ctor is not supported since e.g.
+ // persistent can't reuse persistent node from weak persistent.
+ BasicPersistent(
+ BasicPersistent&& other,
+ const SourceLocation& loc = SourceLocation::Current()) noexcept
+ : PersistentBase(std::move(other)), LocationPolicy(std::move(other)) {
+ if (!IsValid()) return;
+ GetNode()->UpdateOwner(this);
+ other.SetValue(nullptr);
+ other.SetNode(nullptr);
+ this->CheckPointer(Get());
+ }
+
+ // Constructor from member.
+ template ::value>>
+ BasicPersistent(internal::BasicMember
+ member,
+ const SourceLocation& loc = SourceLocation::Current())
+ : BasicPersistent(member.Get(), loc) {}
+
+ ~BasicPersistent() { Clear(); }
+
+ // Copy assignment.
+ BasicPersistent& operator=(const BasicPersistent& other) {
+ return operator=(other.Get());
+ }
+
+ template ::value>>
+ BasicPersistent& operator=(
+ const BasicPersistent& other) {
+ return operator=(other.Get());
+ }
+
+ // Move assignment.
+ BasicPersistent& operator=(BasicPersistent&& other) noexcept {
+ if (this == &other) return *this;
+ Clear();
+ PersistentBase::operator=(std::move(other));
+ LocationPolicy::operator=(std::move(other));
+ if (!IsValid()) return *this;
+ GetNode()->UpdateOwner(this);
+ other.SetValue(nullptr);
+ other.SetNode(nullptr);
+ this->CheckPointer(Get());
+ return *this;
+ }
+
+ // Assignment from member.
+ template ::value>>
+ BasicPersistent& operator=(
+ internal::BasicMember
+ member) {
+ return operator=(member.Get());
+ }
+
+ BasicPersistent& operator=(T* other) {
+ Assign(other);
+ return *this;
+ }
+
+ BasicPersistent& operator=(std::nullptr_t) {
+ Clear();
+ return *this;
+ }
+
+ BasicPersistent& operator=(SentinelPointer s) {
+ Assign(s);
+ return *this;
+ }
+
+ explicit operator bool() const { return Get(); }
+ operator T*() const { return Get(); }
+ T* operator->() const { return Get(); }
+ T& operator*() const { return *Get(); }
+
+ // CFI cast exemption to allow passing SentinelPointer through T* and support
+ // heterogeneous assignments between different Member and Persistent handles
+ // based on their actual types.
+ V8_CLANG_NO_SANITIZE("cfi-unrelated-cast") T* Get() const {
+ // The const_cast below removes the constness from PersistentBase storage.
+ // The following static_cast re-adds any constness if specified through the
+ // user-visible template parameter T.
+ return static_cast(const_cast(GetValue()));
+ }
+
+ void Clear() {
+ // Simplified version of `Assign()` to allow calling without a complete type
+ // `T`.
+ if (IsValid()) {
+ WeaknessPolicy::GetPersistentRegion(GetValue()).FreeNode(GetNode());
+ SetNode(nullptr);
+ }
+ SetValue(nullptr);
+ }
+
+ T* Release() {
+ T* result = Get();
+ Clear();
+ return result;
+ }
+
+ template
+ BasicPersistent
+ To() const {
+ return BasicPersistent(static_cast(Get()));
+ }
+
+ private:
+ static void Trace(Visitor* v, const void* ptr) {
+ const auto* persistent = static_cast(ptr);
+ v->TraceRoot(*persistent, persistent->Location());
+ }
+
+ bool IsValid() const {
+ // Ideally, handling kSentinelPointer would be done by the embedder. On the
+ // other hand, having Persistent aware of it is beneficial since no node
+ // gets wasted.
+ return GetValue() != nullptr && GetValue() != kSentinelPointer;
+ }
+
+ void Assign(T* ptr) {
+ if (IsValid()) {
+ if (ptr && ptr != kSentinelPointer) {
+ // Simply assign the pointer reusing the existing node.
+ SetValue(ptr);
+ this->CheckPointer(ptr);
+ return;
+ }
+ WeaknessPolicy::GetPersistentRegion(GetValue()).FreeNode(GetNode());
+ SetNode(nullptr);
+ }
+ SetValue(ptr);
+ if (!IsValid()) return;
+ SetNode(WeaknessPolicy::GetPersistentRegion(GetValue())
+ .AllocateNode(this, &BasicPersistent::Trace));
+ this->CheckPointer(Get());
+ }
+
+ void ClearFromGC() const {
+ if (IsValid()) {
+ WeaknessPolicy::GetPersistentRegion(GetValue()).FreeNode(GetNode());
+ PersistentBase::ClearFromGC();
+ }
+ }
+
+ // Set Get() for details.
+ V8_CLANG_NO_SANITIZE("cfi-unrelated-cast")
+ T* GetFromGC() const {
+ return static_cast(const_cast(GetValue()));
+ }
+
+ friend class cppgc::Visitor;
+};
+
+template
+bool operator==(const BasicPersistent& p1,
+ const BasicPersistent& p2) {
+ return p1.Get() == p2.Get();
+}
+
+template
+bool operator!=(const BasicPersistent& p1,
+ const BasicPersistent& p2) {
+ return !(p1 == p2);
+}
+
+template
+bool operator==(const BasicPersistent& p,
+ BasicMember
+ m) {
+ return p.Get() == m.Get();
+}
+
+template
+bool operator!=(const BasicPersistent& p,
+ BasicMember
+ m) {
+ return !(p == m);
+}
+
+template
+bool operator==(BasicMember
+ m,
+ const BasicPersistent& p) {
+ return m.Get() == p.Get();
+}
+
+template
+bool operator!=(BasicMember
+ m,
+ const BasicPersistent& p) {
+ return !(m == p);
+}
+
+template
+struct IsWeak> : std::true_type {};
+} // namespace internal
+
+/**
+ * Persistent is a way to create a strong pointer from an off-heap object to
+ * another on-heap object. As long as the Persistent handle is alive the GC will
+ * keep the object pointed to alive. The Persistent handle is always a GC root
+ * from the point of view of the GC. Persistent must be constructed and
+ * destructed in the same thread.
+ */
+template
+using Persistent =
+ internal::BasicPersistent;
+
+/**
+ * WeakPersistent is a way to create a weak pointer from an off-heap object to
+ * an on-heap object. The pointer is automatically cleared when the pointee gets
+ * collected. WeakPersistent must be constructed and destructed in the same
+ * thread.
+ */
+template
+using WeakPersistent =
+ internal::BasicPersistent;
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_PERSISTENT_H_
diff --git a/libs/android/libnode/include/node/cppgc/platform.h b/libs/android/libnode/include/node/cppgc/platform.h
new file mode 100644
index 00000000..3276a26b
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/platform.h
@@ -0,0 +1,154 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_PLATFORM_H_
+#define INCLUDE_CPPGC_PLATFORM_H_
+
+#include
+
+#include "v8-platform.h" // NOLINT(build/include_directory)
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+// TODO(v8:10346): Create separate includes for concepts that are not
+// V8-specific.
+using IdleTask = v8::IdleTask;
+using JobHandle = v8::JobHandle;
+using JobDelegate = v8::JobDelegate;
+using JobTask = v8::JobTask;
+using PageAllocator = v8::PageAllocator;
+using Task = v8::Task;
+using TaskPriority = v8::TaskPriority;
+using TaskRunner = v8::TaskRunner;
+using TracingController = v8::TracingController;
+
+/**
+ * Platform interface used by Heap. Contains allocators and executors.
+ */
+class V8_EXPORT Platform {
+ public:
+ virtual ~Platform() = default;
+
+ /**
+ * Returns the allocator used by cppgc to allocate its heap and various
+ * support structures.
+ */
+ virtual PageAllocator* GetPageAllocator() = 0;
+
+ /**
+ * Monotonically increasing time in seconds from an arbitrary fixed point in
+ * the past. This function is expected to return at least
+ * millisecond-precision values. For this reason,
+ * it is recommended that the fixed point be no further in the past than
+ * the epoch.
+ **/
+ virtual double MonotonicallyIncreasingTime() = 0;
+
+ /**
+ * Foreground task runner that should be used by a Heap.
+ */
+ virtual std::shared_ptr GetForegroundTaskRunner() {
+ return nullptr;
+ }
+
+ /**
+ * Posts `job_task` to run in parallel. Returns a `JobHandle` associated with
+ * the `Job`, which can be joined or canceled.
+ * This avoids degenerate cases:
+ * - Calling `CallOnWorkerThread()` for each work item, causing significant
+ * overhead.
+ * - Fixed number of `CallOnWorkerThread()` calls that split the work and
+ * might run for a long time. This is problematic when many components post
+ * "num cores" tasks and all expect to use all the cores. In these cases,
+ * the scheduler lacks context to be fair to multiple same-priority requests
+ * and/or ability to request lower priority work to yield when high priority
+ * work comes in.
+ * A canonical implementation of `job_task` looks like:
+ * \code
+ * class MyJobTask : public JobTask {
+ * public:
+ * MyJobTask(...) : worker_queue_(...) {}
+ * // JobTask implementation.
+ * void Run(JobDelegate* delegate) override {
+ * while (!delegate->ShouldYield()) {
+ * // Smallest unit of work.
+ * auto work_item = worker_queue_.TakeWorkItem(); // Thread safe.
+ * if (!work_item) return;
+ * ProcessWork(work_item);
+ * }
+ * }
+ *
+ * size_t GetMaxConcurrency() const override {
+ * return worker_queue_.GetSize(); // Thread safe.
+ * }
+ * };
+ *
+ * // ...
+ * auto handle = PostJob(TaskPriority::kUserVisible,
+ * std::make_unique(...));
+ * handle->Join();
+ * \endcode
+ *
+ * `PostJob()` and methods of the returned JobHandle/JobDelegate, must never
+ * be called while holding a lock that could be acquired by `JobTask::Run()`
+ * or `JobTask::GetMaxConcurrency()` -- that could result in a deadlock. This
+ * is because (1) `JobTask::GetMaxConcurrency()` may be invoked while holding
+ * internal lock (A), hence `JobTask::GetMaxConcurrency()` can only use a lock
+ * (B) if that lock is *never* held while calling back into `JobHandle` from
+ * any thread (A=>B/B=>A deadlock) and (2) `JobTask::Run()` or
+ * `JobTask::GetMaxConcurrency()` may be invoked synchronously from
+ * `JobHandle` (B=>JobHandle::foo=>B deadlock).
+ *
+ * A sufficient `PostJob()` implementation that uses the default Job provided
+ * in libplatform looks like:
+ * \code
+ * std::unique_ptr PostJob(
+ * TaskPriority priority, std::unique_ptr job_task) override {
+ * return std::make_unique(
+ * std::make_shared(
+ * this, std::move(job_task), kNumThreads));
+ * }
+ * \endcode
+ */
+ virtual std::unique_ptr PostJob(
+ TaskPriority priority, std::unique_ptr job_task) {
+ return nullptr;
+ }
+
+ /**
+ * Returns an instance of a `TracingController`. This must be non-nullptr. The
+ * default implementation returns an empty `TracingController` that consumes
+ * trace data without effect.
+ */
+ virtual TracingController* GetTracingController();
+};
+
+/**
+ * Process-global initialization of the garbage collector. Must be called before
+ * creating a Heap.
+ *
+ * Can be called multiple times when paired with `ShutdownProcess()`.
+ *
+ * \param page_allocator The allocator used for maintaining meta data. Must not
+ * change between multiple calls to InitializeProcess.
+ */
+V8_EXPORT void InitializeProcess(PageAllocator* page_allocator);
+
+/**
+ * Must be called after destroying the last used heap. Some process-global
+ * metadata may not be returned and reused upon a subsequent
+ * `InitializeProcess()` call.
+ */
+V8_EXPORT void ShutdownProcess();
+
+namespace internal {
+
+V8_EXPORT void Abort();
+
+} // namespace internal
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_PLATFORM_H_
diff --git a/libs/android/libnode/include/node/cppgc/prefinalizer.h b/libs/android/libnode/include/node/cppgc/prefinalizer.h
new file mode 100644
index 00000000..29b18bef
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/prefinalizer.h
@@ -0,0 +1,52 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_PREFINALIZER_H_
+#define INCLUDE_CPPGC_PREFINALIZER_H_
+
+#include "cppgc/internal/compiler-specific.h"
+#include "cppgc/internal/prefinalizer-handler.h"
+#include "cppgc/liveness-broker.h"
+
+namespace cppgc {
+
+namespace internal {
+
+template
+class PrefinalizerRegistration final {
+ public:
+ explicit PrefinalizerRegistration(T* self) {
+ static_assert(sizeof(&T::InvokePreFinalizer) > 0,
+ "USING_PRE_FINALIZER(T) must be defined.");
+
+ cppgc::internal::PreFinalizerRegistrationDispatcher::RegisterPrefinalizer(
+ {self, T::InvokePreFinalizer});
+ }
+
+ void* operator new(size_t, void* location) = delete;
+ void* operator new(size_t) = delete;
+};
+
+} // namespace internal
+
+#define CPPGC_USING_PRE_FINALIZER(Class, PreFinalizer) \
+ public: \
+ static bool InvokePreFinalizer(const cppgc::LivenessBroker& liveness_broker, \
+ void* object) { \
+ static_assert(cppgc::IsGarbageCollectedOrMixinTypeV, \
+ "Only garbage collected objects can have prefinalizers"); \
+ Class* self = static_cast(object); \
+ if (liveness_broker.IsHeapObjectAlive(self)) return false; \
+ self->Class::PreFinalizer(); \
+ return true; \
+ } \
+ \
+ private: \
+ CPPGC_NO_UNIQUE_ADDRESS cppgc::internal::PrefinalizerRegistration \
+ prefinalizer_dummy_{this}; \
+ static_assert(true, "Force semicolon.")
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_PREFINALIZER_H_
diff --git a/libs/android/libnode/include/node/cppgc/process-heap-statistics.h b/libs/android/libnode/include/node/cppgc/process-heap-statistics.h
new file mode 100644
index 00000000..774cc92f
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/process-heap-statistics.h
@@ -0,0 +1,36 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_PROCESS_HEAP_STATISTICS_H_
+#define INCLUDE_CPPGC_PROCESS_HEAP_STATISTICS_H_
+
+#include
+#include
+
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+namespace internal {
+class ProcessHeapStatisticsUpdater;
+} // namespace internal
+
+class V8_EXPORT ProcessHeapStatistics final {
+ public:
+ static size_t TotalAllocatedObjectSize() {
+ return total_allocated_object_size_.load(std::memory_order_relaxed);
+ }
+ static size_t TotalAllocatedSpace() {
+ return total_allocated_space_.load(std::memory_order_relaxed);
+ }
+
+ private:
+ static std::atomic_size_t total_allocated_space_;
+ static std::atomic_size_t total_allocated_object_size_;
+
+ friend class internal::ProcessHeapStatisticsUpdater;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_PROCESS_HEAP_STATISTICS_H_
diff --git a/libs/android/libnode/include/node/cppgc/sentinel-pointer.h b/libs/android/libnode/include/node/cppgc/sentinel-pointer.h
new file mode 100644
index 00000000..b049d1a2
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/sentinel-pointer.h
@@ -0,0 +1,32 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_SENTINEL_POINTER_H_
+#define INCLUDE_CPPGC_SENTINEL_POINTER_H_
+
+#include
+
+namespace cppgc {
+namespace internal {
+
+// Special tag type used to denote some sentinel member. The semantics of the
+// sentinel is defined by the embedder.
+struct SentinelPointer {
+ template
+ operator T*() const {
+ static constexpr intptr_t kSentinelValue = 1;
+ return reinterpret_cast(kSentinelValue);
+ }
+ // Hidden friends.
+ friend bool operator==(SentinelPointer, SentinelPointer) { return true; }
+ friend bool operator!=(SentinelPointer, SentinelPointer) { return false; }
+};
+
+} // namespace internal
+
+constexpr internal::SentinelPointer kSentinelPointer;
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_SENTINEL_POINTER_H_
diff --git a/libs/android/libnode/include/node/cppgc/source-location.h b/libs/android/libnode/include/node/cppgc/source-location.h
new file mode 100644
index 00000000..da5a5ede
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/source-location.h
@@ -0,0 +1,92 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_SOURCE_LOCATION_H_
+#define INCLUDE_CPPGC_SOURCE_LOCATION_H_
+
+#include
+#include
+
+#include "v8config.h" // NOLINT(build/include_directory)
+
+#if defined(__has_builtin)
+#define CPPGC_SUPPORTS_SOURCE_LOCATION \
+ (__has_builtin(__builtin_FUNCTION) && __has_builtin(__builtin_FILE) && \
+ __has_builtin(__builtin_LINE)) // NOLINT
+#elif defined(V8_CC_GNU) && __GNUC__ >= 7
+#define CPPGC_SUPPORTS_SOURCE_LOCATION 1
+#elif defined(V8_CC_INTEL) && __ICC >= 1800
+#define CPPGC_SUPPORTS_SOURCE_LOCATION 1
+#else
+#define CPPGC_SUPPORTS_SOURCE_LOCATION 0
+#endif
+
+namespace cppgc {
+
+/**
+ * Encapsulates source location information. Mimics C++20's
+ * `std::source_location`.
+ */
+class V8_EXPORT SourceLocation final {
+ public:
+ /**
+ * Construct source location information corresponding to the location of the
+ * call site.
+ */
+#if CPPGC_SUPPORTS_SOURCE_LOCATION
+ static constexpr SourceLocation Current(
+ const char* function = __builtin_FUNCTION(),
+ const char* file = __builtin_FILE(), size_t line = __builtin_LINE()) {
+ return SourceLocation(function, file, line);
+ }
+#else
+ static constexpr SourceLocation Current() { return SourceLocation(); }
+#endif // CPPGC_SUPPORTS_SOURCE_LOCATION
+
+ /**
+ * Constructs unspecified source location information.
+ */
+ constexpr SourceLocation() = default;
+
+ /**
+ * Returns the name of the function associated with the position represented
+ * by this object, if any.
+ *
+ * \returns the function name as cstring.
+ */
+ constexpr const char* Function() const { return function_; }
+
+ /**
+ * Returns the name of the current source file represented by this object.
+ *
+ * \returns the file name as cstring.
+ */
+ constexpr const char* FileName() const { return file_; }
+
+ /**
+ * Returns the line number represented by this object.
+ *
+ * \returns the line number.
+ */
+ constexpr size_t Line() const { return line_; }
+
+ /**
+ * Returns a human-readable string representing this object.
+ *
+ * \returns a human-readable string representing source location information.
+ */
+ std::string ToString() const;
+
+ private:
+ constexpr SourceLocation(const char* function, const char* file, size_t line)
+ : function_(function), file_(file), line_(line) {}
+
+ const char* function_ = nullptr;
+ const char* file_ = nullptr;
+ size_t line_ = 0u;
+};
+
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_SOURCE_LOCATION_H_
diff --git a/libs/android/libnode/include/node/cppgc/testing.h b/libs/android/libnode/include/node/cppgc/testing.h
new file mode 100644
index 00000000..229ce140
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/testing.h
@@ -0,0 +1,99 @@
+// Copyright 2021 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_TESTING_H_
+#define INCLUDE_CPPGC_TESTING_H_
+
+#include "cppgc/common.h"
+#include "cppgc/macros.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class HeapHandle;
+
+/**
+ * Namespace contains testing helpers.
+ */
+namespace testing {
+
+/**
+ * Overrides the state of the stack with the provided value. Takes precedence
+ * over other parameters that set the stack state. Must no be nested.
+ */
+class V8_EXPORT V8_NODISCARD OverrideEmbedderStackStateScope final {
+ CPPGC_STACK_ALLOCATED();
+
+ public:
+ /**
+ * Constructs a scoped object that automatically enters and leaves the scope.
+ *
+ * \param heap_handle The corresponding heap.
+ */
+ explicit OverrideEmbedderStackStateScope(HeapHandle& heap_handle,
+ EmbedderStackState state);
+ ~OverrideEmbedderStackStateScope();
+
+ OverrideEmbedderStackStateScope(const OverrideEmbedderStackStateScope&) =
+ delete;
+ OverrideEmbedderStackStateScope& operator=(
+ const OverrideEmbedderStackStateScope&) = delete;
+
+ private:
+ HeapHandle& heap_handle_;
+};
+
+/**
+ * Testing interface for managed heaps that allows for controlling garbage
+ * collection timings. Embedders should use this class when testing the
+ * interaction of their code with incremental/concurrent garbage collection.
+ */
+class V8_EXPORT StandaloneTestingHeap final {
+ public:
+ explicit StandaloneTestingHeap(HeapHandle&);
+
+ /**
+ * Start an incremental garbage collection.
+ */
+ void StartGarbageCollection();
+
+ /**
+ * Perform an incremental step. This will also schedule concurrent steps if
+ * needed.
+ *
+ * \param stack_state The state of the stack during the step.
+ */
+ bool PerformMarkingStep(EmbedderStackState stack_state);
+
+ /**
+ * Finalize the current garbage collection cycle atomically.
+ * Assumes that garbage collection is in progress.
+ *
+ * \param stack_state The state of the stack for finalizing the garbage
+ * collection cycle.
+ */
+ void FinalizeGarbageCollection(EmbedderStackState stack_state);
+
+ /**
+ * Toggle main thread marking on/off. Allows to stress concurrent marking
+ * (e.g. to better detect data races).
+ *
+ * \param should_mark Denotes whether the main thread should contribute to
+ * marking. Defaults to true.
+ */
+ void ToggleMainThreadMarking(bool should_mark);
+
+ /**
+ * Force enable compaction for the next garbage collection cycle.
+ */
+ void ForceCompactionForNextGarbageCollection();
+
+ private:
+ HeapHandle& heap_handle_;
+};
+
+} // namespace testing
+} // namespace cppgc
+
+#endif // INCLUDE_CPPGC_TESTING_H_
diff --git a/libs/android/libnode/include/node/cppgc/trace-trait.h b/libs/android/libnode/include/node/cppgc/trace-trait.h
new file mode 100644
index 00000000..83619b1d
--- /dev/null
+++ b/libs/android/libnode/include/node/cppgc/trace-trait.h
@@ -0,0 +1,116 @@
+// Copyright 2020 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CPPGC_TRACE_TRAIT_H_
+#define INCLUDE_CPPGC_TRACE_TRAIT_H_
+
+#include
+
+#include "cppgc/type-traits.h"
+#include "v8config.h" // NOLINT(build/include_directory)
+
+namespace cppgc {
+
+class Visitor;
+
+namespace internal {
+
+// Implementation of the default TraceTrait handling GarbageCollected and
+// GarbageCollectedMixin.
+template ::type>>
+struct TraceTraitImpl;
+
+} // namespace internal
+
+/**
+ * Callback for invoking tracing on a given object.
+ *
+ * \param visitor The visitor to dispatch to.
+ * \param object The object to invoke tracing on.
+ */
+using TraceCallback = void (*)(Visitor* visitor, const void* object);
+
+/**
+ * Describes how to trace an object, i.e., how to visit all Oilpan-relevant
+ * fields of an object.
+ */
+struct TraceDescriptor {
+ /**
+ * Adjusted base pointer, i.e., the pointer to the class inheriting directly
+ * from GarbageCollected, of the object that is being traced.
+ */
+ const void* base_object_payload;
+ /**
+ * Callback for tracing the object.
+ */
+ TraceCallback callback;
+};
+
+namespace internal {
+
+struct V8_EXPORT TraceTraitFromInnerAddressImpl {
+ static TraceDescriptor GetTraceDescriptor(const void* address);
+};
+
+/**
+ * Trait specifying how the garbage collector processes an object of type T.
+ *
+ * Advanced users may override handling by creating a specialization for their
+ * type.
+ */
+template
+struct TraceTraitBase {
+ static_assert(internal::IsTraceableV, "T must have a Trace() method");
+
+ /**
+ * Accessor for retrieving a TraceDescriptor to process an object of type T.
+ *
+ * \param self The object to be processed.
+ * \returns a TraceDescriptor to process the object.
+ */
+ static TraceDescriptor GetTraceDescriptor(const void* self) {
+ return internal::TraceTraitImpl::GetTraceDescriptor(
+ static_cast(self));
+ }
+
+ /**
+ * Function invoking the tracing for an object of type T.
+ *
+ * \param visitor The visitor to dispatch to.
+ * \param self The object to invoke tracing on.
+ */
+ static void Trace(Visitor* visitor, const void* self) {
+ static_cast(self)->Trace(visitor);
+ }
+};
+
+} // namespace internal
+
+template
+struct TraceTrait : public internal::TraceTraitBase {};
+
+namespace internal {
+
+template
+struct TraceTraitImpl {
+ static_assert(IsGarbageCollectedTypeV,
+ "T must be of type GarbageCollected or GarbageCollectedMixin");
+ static TraceDescriptor GetTraceDescriptor(const void* self) {
+ return {self, TraceTrait