Repository: nodejs/node
Pull request: build,test: add tests for binary linked with shared libnode

This adds tests to ensure the V8 parts (v8, libplatform, cppgc) in shared libnode works correctly.

Refs: https://github.com/nodejs/node/pull/61144


<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: node.gyp
patch: @@ -1424,6 +1424,61 @@
       ],
     }, # embedtest
 
+    {
+      'target_name': 'shared_embedtest',
+      'type': 'executable',
+
+      'dependencies': [
+        '<(node_lib_target_name)',
+      ],
+
+      # Don't depend on node.gypi - it otherwise links to
+      # the static libraries and resolve symbols at build time.
+      'include_dirs': [
+        'deps/v8/include',
+      ],
+
+      'sources': [
+        'test/embedding/shared_embedtest.cc',
+      ],
+      'conditions': [
+        [ 'node_shared=="true"', {
+          'defines': [
+            'USING_V8_SHARED',
+            'USING_V8_PLATFORM_SHARED',
+          ],
+          'defines!': [
+            'BUILDING_V8_PLATFORM_SHARED=1',
+            'BUILDING_V8_SHARED=1',
+          ],
+        }, {
+          # Only test shared embedding when Node is built as shared library.
+          'type': 'none',
+        }],
+        # Only test platforms known to work.
+        ['OS not in "mac win linux"', {
+          'type': 'none',
+        }],
+        ['OS=="win"', {
+          'libraries': [
+            'Dbghelp.lib',
+            'winmm.lib',
+            'Ws2_32.lib',
+          ],
+        }],
+        ['OS=="mac"', {
+          'xcode_settings': {
+            'OTHER_LDFLAGS': [ '-Wl,-rpath,@loader_path', ],
+          }
+        }],
+        ['OS=="linux"', {
+          'ldflags': [
+            '-Wl,-rpath,\\$$ORIGIN'
+          ],
+        }],
+      ],
+    }, # shared_embedtest
+
     {
       'target_name': 'overlapped-checker',
       'type': 'executable',

filename: test/common/index.js
patch: @@ -62,6 +62,8 @@ if (isMainThread)
 
 const noop = () => {};
 
+// Whether the executable is linked against the shared library i.e. libnode.
+const usesSharedLibrary = process.config.variables.node_shared;
 const hasCrypto = Boolean(process.versions.openssl) &&
                   !process.env.NODE_SKIP_CRYPTO;
 
@@ -949,6 +951,13 @@ function sleepSync(ms) {
   Atomics.wait(i32, 0, 0, ms);
 }
 
+function resolveBuiltBinary(binary) {
+  if (isWindows) {
+    binary += '.exe';
+  }
+  return path.join(path.dirname(process.execPath), binary);
+}
+
 const common = {
   allowGlobals,
   buildType,
@@ -994,6 +1003,7 @@ const common = {
   printSkipMessage,
   pwdCommand,
   requireNoPackageJSONAbove,
+  resolveBuiltBinary,
   runWithInvalidFD,
   skip,
   skipIf32Bits,
@@ -1002,6 +1012,7 @@ const common = {
   skipIfSQLiteMissing,
   spawnPromisified,
   sleepSync,
+  usesSharedLibrary,
 
   get enoughTestMem() {
     return require('os').totalmem() > 0x70000000; /* 1.75 Gb */

filename: test/embedding/shared_embedtest.cc
patch: @@ -0,0 +1,60 @@
+#include <libplatform/libplatform.h>
+#include <v8-cppgc.h>
+#include <v8.h>
+
+#include <cppgc/allocation.h>
+#include <cppgc/default-platform.h>
+#include <cppgc/garbage-collected.h>
+#include <cppgc/heap.h>
+#include <cppgc/member.h>
+#include <cppgc/platform.h>
+#include <cppgc/visitor.h>
+
+class Wrappable : public v8::Object::Wrappable {
+ public:
+  void Trace(cppgc::Visitor* visitor) const override {
+    v8::Object::Wrappable::Trace(visitor);
+  }
+};
+
+int main(int argc, char* argv[]) {
+  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
+  v8::V8::InitializePlatform(platform.get());
+  cppgc::InitializeProcess(platform->GetPageAllocator());
+  v8::V8::Initialize();
+
+  auto heap = v8::CppHeap::Create(platform.get(), v8::CppHeapCreateParams{{}});
+  v8::Isolate::CreateParams create_params;
+  create_params.array_buffer_allocator =
+      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
+  create_params.cpp_heap = heap.release();
+
+  v8::Isolate* isolate = v8::Isolate::New(create_params);
+  {
+    v8::Isolate::Scope isolate_scope(isolate);
+    v8::HandleScope handle_scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope context_scope(context);
+
+    v8::Local<v8::Object> obj = v8::Object::New(isolate);
+    Wrappable* wrappable = cppgc::MakeGarbageCollected<Wrappable>(
+        isolate->GetCppHeap()->GetAllocationHandle());
+    v8::Object::Wrap<v8::CppHeapPointerTag::kDefaultTag>(
+        isolate, obj, wrappable);
+    v8::Local<v8::String> source =
+        v8::String::NewFromUtf8Literal(isolate, "'Hello' + ', World!'");
+    v8::Local<v8::Script> script =
+        v8::Script::Compile(context, source).ToLocalChecked();
+    v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
+    v8::String::Utf8Value utf8(isolate, result);
+    printf("%s\n", *utf8);
+  }
+
+  isolate->Dispose();
+  cppgc::ShutdownProcess();
+  v8::V8::Dispose();
+  v8::V8::DisposePlatform();
+  delete create_params.array_buffer_allocator;
+
+  return 0;
+}

filename: test/embedding/test-embedding.js
patch: @@ -8,22 +8,14 @@ const {
   spawnSyncAndExit,
   spawnSyncAndExitWithoutError,
 } = require('../common/child_process');
-const path = require('path');
 const fs = require('fs');
 const os = require('os');
 
 tmpdir.refresh();
 common.allowGlobals(global.require);
 common.allowGlobals(global.embedVars);
 
-function resolveBuiltBinary(binary) {
-  if (common.isWindows) {
-    binary += '.exe';
-  }
-  return path.join(path.dirname(process.execPath), binary);
-}
-
-const binary = resolveBuiltBinary('embedtest');
+const binary = common.resolveBuiltBinary('embedtest');
 
 spawnSyncAndAssert(
   binary,

filename: test/embedding/test-shared-embedding-v8.js
patch: @@ -0,0 +1,25 @@
+'use strict';
+
+// This tests the V8 parts in the shared library work correctly.
+// TODO(joyeecheung): also test that the Node.js parts work correctly,
+// which can be done in embedtest just built in shared library mode.
+
+const common = require('../common');
+
+if (!common.usesSharedLibrary) {
+  common.skip('Only tests builds linking against Node.js shared library');
+}
+
+const { spawnSyncAndAssert } = require('../common/child_process');
+const fs = require('fs');
+
+const binary = common.resolveBuiltBinary('shared_embedtest');
+
+if (!fs.existsSync(binary)) {
+  common.skip('shared_embedtest binary not built');
+}
+
+spawnSyncAndAssert(binary, {
+  trim: true,
+  stdout: 'Hello, World!',
+});