From aed5cc422ffaa757ac40b307f3d992544db0eed8 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sat, 28 Nov 2026 15:12:12 +0000 Subject: [PATCH 1/6] [refactor] Align observable subscriptions with node entity lifecycle --- lib/node.js | 33 +++++- lib/observable_subscription.js | 63 ++++++++---- lib/subscription.js | 2 +- test/test-observable-subscription.js | 144 +++++++++++++++++++++++++-- types/node.d.ts | 2 + types/observable_subscription.d.ts | 12 ++- 6 files changed, 218 insertions(+), 38 deletions(-) diff --git a/lib/node.js b/lib/node.js index 00115c0ab..dfa720527 100644 --- a/lib/node.js +++ b/lib/node.js @@ -42,7 +42,9 @@ import QoS from './qos.js'; import * as Rates from './rate.js'; import Service from './service.js'; import Subscription from './subscription.js'; -import ObservableSubscription from './observable_subscription.js'; +import ObservableSubscription, { + ObservableSubscriptionEntity, +} from './observable_subscription.js'; import MessageInfo from './message_info.js'; import ActionEndpointInfo from './action/endpoint_info.js'; import { declareQosParameters, _resolveQoS } from './qos_overriding_options.js'; @@ -910,6 +912,25 @@ class Node extends rclnodejs.ShadowNode { * @see {@link https://www.omg.org/spec/DDS/1.4/PDF|Content-filter details at DDS 1.4 specification, Annex B} */ createSubscription(typeClass, topic, options, callback, eventCallbacks) { + const subscription = this._createSubscription( + Subscription, + typeClass, + topic, + options, + callback, + eventCallbacks + ); + return this._registerEntity('subscriptions', subscription); + } + + _createSubscription( + SubscriptionClass, + typeClass, + topic, + options, + callback, + eventCallbacks + ) { if (typeof typeClass === 'string' || typeof typeClass === 'object') { typeClass = loader.loadInterface(typeClass); } @@ -970,7 +991,7 @@ class Node extends rclnodejs.ShadowNode { ); } - let subscription = Subscription.createSubscription( + let subscription = SubscriptionClass.createSubscription( this, typeClass, topic, @@ -979,12 +1000,14 @@ class Node extends rclnodejs.ShadowNode { eventCallbacks ); debug('Finish creating subscription, topic = %s.', topic); - return this._registerEntity('subscriptions', subscription); + return subscription; } /** * Create a Subscription that returns an RxJS Observable. * This allows using reactive programming patterns with ROS 2 messages. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. * * @param {function|string|object} typeClass - The ROS message class, * OR a string representing the message class, e.g. 'std_msgs/msg/String', @@ -1002,7 +1025,8 @@ class Node extends rclnodejs.ShadowNode { createObservableSubscription(typeClass, topic, options, eventCallbacks) { let observableSubscription = null; - const subscription = this.createSubscription( + const subscription = this._createSubscription( + ObservableSubscriptionEntity, typeClass, topic, options, @@ -1015,6 +1039,7 @@ class Node extends rclnodejs.ShadowNode { ); observableSubscription = new ObservableSubscription(subscription, this); + this._registerEntity('subscriptions', subscription); return observableSubscription; } diff --git a/lib/observable_subscription.js b/lib/observable_subscription.js index 2dd4f1b81..b735e0548 100644 --- a/lib/observable_subscription.js +++ b/lib/observable_subscription.js @@ -13,29 +13,55 @@ // limitations under the License. import { Subject } from 'rxjs'; +import Subscription from './subscription.js'; + +/** + * Native-backed subscription that finalizes its observable with the entity. + * @ignore + */ +export class ObservableSubscriptionEntity extends Subscription { + #subject = new Subject(); + + get observable() { + return this.#subject.asObservable(); + } + + _emit(message) { + if (!this.isDestroyed()) { + this.#subject.next(message); + } + } + + finalizeDestruction() { + if (this.isDestroyed()) return; + + try { + super.finalizeDestruction(); + } finally { + this.#subject.complete(); + } + } +} /** * A wrapper that provides RxJS Observable support for ROS 2 subscriptions. - * This class wraps a standard Subscription and emits messages through an Observable. + * The node owns the underlying subscription and completes the observable when + * that subscription or the node is destroyed. * * @class ObservableSubscription * @hideconstructor */ class ObservableSubscription { #subscription; - #subject; - #destroyed; #node; /** * Create an ObservableSubscription wrapper. - * @param {Subscription} subscription - The underlying ROS 2 subscription + * @param {ObservableSubscriptionEntity} subscription - The underlying ROS 2 subscription * @param {Node} node - The node that owns the subscription, used to destroy it */ constructor(subscription, node) { this.#subscription = subscription; - this.#subject = new Subject(); - this.#destroyed = false; this.#node = node; } @@ -45,7 +71,7 @@ class ObservableSubscription { * @type {Observable} */ get observable() { - return this.#subject.asObservable(); + return this.#subscription.observable; } /** @@ -65,11 +91,12 @@ class ObservableSubscription { } /** - * Check if this observable subscription has been destroyed. + * Check if the underlying subscription has been destroyed, including by + * node teardown. * @type {boolean} */ get isDestroyed() { - return this.#destroyed; + return this.#subscription.isDestroyed(); } /** @@ -79,23 +106,17 @@ class ObservableSubscription { * @param {any} message - The message to emit */ _emit(message) { - if (!this.#destroyed) { - this.#subject.next(message); - } + this.#subscription._emit(message); } /** - * Complete the observable and clean up resources. - * After calling this, no more messages will be emitted, and the underlying - * ROS 2 subscription is destroyed so it stops receiving and deserializing - * messages. + * Destroy the underlying ROS 2 subscription through its node and complete + * the observable. Destruction is idempotent and can be retried if handle + * synchronization fails before native cleanup. + * Unsubscribing from the observable alone does not destroy the subscription. */ complete() { - if (!this.#destroyed) { - this.#destroyed = true; - this.#subject.complete(); - this.#node.destroySubscription(this.#subscription); - } + this.#node.destroySubscription(this.#subscription); } /** diff --git a/lib/subscription.js b/lib/subscription.js index ac7769602..324c2722d 100644 --- a/lib/subscription.js +++ b/lib/subscription.js @@ -111,7 +111,7 @@ class Subscription extends Entity { topic, options ); - return new Subscription( + return new this( handle, typeClass, topic, diff --git a/test/test-observable-subscription.js b/test/test-observable-subscription.js index ff38c36c1..96dca5aa8 100644 --- a/test/test-observable-subscription.js +++ b/test/test-observable-subscription.js @@ -15,8 +15,10 @@ import assert from 'assert'; import rclnodejs from '../index.js'; import rxjs from 'rxjs'; +import DistroUtils from '../lib/distro.js'; +import { SubscriptionEventCallbacks } from '../lib/event_handler.js'; -const { take, map, filter, toArray } = rxjs; +const { take, map, filter, toArray, finalize } = rxjs; describe('rclnodejs observable subscription test suite', function () { this.timeout(60 * 1000); @@ -32,6 +34,8 @@ describe('rclnodejs observable subscription test suite', function () { it('createObservableSubscription returns an ObservableSubscription', function () { const node = new rclnodejs.Node('test_node'); const String = 'std_msgs/msg/String'; + const subscriptions = node._subscriptions; + const subscriptionCount = subscriptions.length; const obsSub = node.createObservableSubscription(String, 'test_topic'); @@ -40,6 +44,8 @@ describe('rclnodejs observable subscription test suite', function () { assert.ok(obsSub.subscription, 'Should have a subscription property'); assert.ok(obsSub.topic.includes('test_topic')); assert.strictEqual(obsSub.isDestroyed, false); + assert.strictEqual(subscriptions.length, subscriptionCount + 1); + assert.ok(subscriptions.includes(obsSub.subscription)); node.destroy(); }); @@ -209,16 +215,138 @@ describe('rclnodejs observable subscription test suite', function () { it('underlying subscription can be destroyed via node', function () { const node = new rclnodejs.Node('test_node'); - const String = 'std_msgs/msg/String'; + try { + const obsSub = node.createObservableSubscription( + 'std_msgs/msg/String', + 'destroy_sub_test_topic' + ); + let completions = 0; + obsSub.observable.subscribe({ + complete: () => completions++, + }); - const obsSub = node.createObservableSubscription( - String, - 'destroy_sub_test_topic' - ); + node.destroySubscription(obsSub.subscription); + obsSub.destroy(); + obsSub.complete(); - node.destroySubscription(obsSub.subscription); + assert.strictEqual(obsSub.isDestroyed, true); + assert.strictEqual(completions, 1); + assert.ok(!node._subscriptions.includes(obsSub.subscription)); + } finally { + node.destroy(); + } + }); - node.destroy(); + it('node teardown completes observables after entity cleanup and runs finalizers once', function () { + const node = new rclnodejs.Node('test_node'); + const subscriptions = node._subscriptions; + try { + let eventCallbacks; + if (DistroUtils.getDistroId() >= DistroUtils.getDistroId('jazzy')) { + eventCallbacks = new SubscriptionEventCallbacks(); + eventCallbacks.deadline = () => {}; + } + const observables = ['first', 'second'].map((name) => + node.createObservableSubscription( + 'std_msgs/msg/String', + `node_teardown_${name}`, + undefined, + eventCallbacks + ) + ); + const events = observables.flatMap( + (obsSub) => obsSub.subscription.events || [] + ); + const completions = []; + let finalizations = 0; + for (const obsSub of observables) { + obsSub.observable + .pipe( + finalize(() => { + finalizations++; + obsSub.destroy(); + }) + ) + .subscribe({ + complete: () => { + completions.push({ + destroyed: obsSub.isDestroyed, + registered: subscriptions.includes(obsSub.subscription), + eventsDestroyed: events.every((event) => event.isDestroyed()), + }); + }, + }); + } + node.spin(-1); + node.destroy(); + for (const obsSub of observables) { + obsSub.destroy(); + obsSub.complete(); + } + + assert.strictEqual(node.spinning, false); + assert.strictEqual(subscriptions.length, 0); + assert.strictEqual(completions.length, observables.length); + assert.strictEqual(finalizations, observables.length); + for (const completion of completions) { + assert.deepStrictEqual(completion, { + destroyed: true, + registered: false, + eventsDestroyed: true, + }); + } + } finally { + node.destroy(); + } + }); + + it('retries destruction after handle synchronization fails', function () { + const node = new rclnodejs.Node('test_node'); + let obsSub; + try { + obsSub = node.createObservableSubscription( + 'std_msgs/msg/String', + 'retry_destruction_topic' + ); + let completions = 0; + obsSub.observable.subscribe({ + complete: () => completions++, + }); + node.spin(-1); + const nativeSync = node.syncHandles.bind(node); + let synchronizations = 0; + Object.defineProperty(node, 'syncHandles', { + configurable: true, + value: () => { + synchronizations++; + if (synchronizations === 1) { + throw new Error('Injected handle synchronization failure'); + } + nativeSync(); + }, + }); + + assert.throws( + () => obsSub.destroy(), + /Injected handle synchronization failure/ + ); + assert.strictEqual(obsSub.isDestroyed, false); + assert.strictEqual(obsSub.subscription.isDestroyed(), false); + assert.strictEqual(completions, 0); + + obsSub.destroy(); + obsSub.complete(); + + assert.strictEqual(obsSub.isDestroyed, true); + assert.strictEqual(obsSub.subscription.isDestroyed(), true); + assert.strictEqual(completions, 1); + assert.strictEqual(synchronizations, 2); + assert.ok(!node._subscriptions.includes(obsSub.subscription)); + } finally { + delete node.syncHandles; + if (obsSub) node.destroySubscription(obsSub.subscription); + node.destroy(); + } }); // Regression test: destroy()/complete() used to only complete the RxJS diff --git a/types/node.d.ts b/types/node.d.ts index 25b8f2124..330075a1f 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -432,6 +432,8 @@ declare module 'rclnodejs' { /** * Create a Subscription that returns an RxJS Observable. * This allows using reactive programming patterns with ROS 2 messages. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. * * @param typeClass - Type of ROS messages the subscription will subscribe to. * @param topic - Name of the topic the subscription will subscribe to. diff --git a/types/observable_subscription.d.ts b/types/observable_subscription.d.ts index c02138650..31d20a65e 100644 --- a/types/observable_subscription.d.ts +++ b/types/observable_subscription.d.ts @@ -1,7 +1,8 @@ declare module 'rclnodejs' { /** * A wrapper that provides RxJS Observable support for ROS 2 subscriptions. - * This class wraps a standard Subscription and emits messages through an Observable. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. */ class ObservableSubscription { /** @@ -21,13 +22,16 @@ declare module 'rclnodejs' { readonly topic: string; /** - * Check if this observable subscription has been destroyed. + * Check if the underlying subscription has been destroyed, including by + * node teardown. */ readonly isDestroyed: boolean; /** - * Complete the observable and clean up resources. - * After calling this, no more messages will be emitted. + * Destroy the underlying ROS 2 subscription through its node and complete + * the observable. Destruction is idempotent and can be retried if handle + * synchronization fails before native cleanup. + * Unsubscribing from the observable alone does not destroy the subscription. */ complete(): void; From 5b902e76a90dffcf6a930171b51b60f3a05bb750 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sun, 29 Nov 2026 14:18:18 +0000 Subject: [PATCH 2/6] Add opt-in Windows action crash diagnostics Trace action-client setup, teardown, and native-call boundaries. Log Windows first-chance exceptions and stack addresses without suppressing faults, and enable diagnostics for the Windows CI test step. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/windows-build-and-test.yml | 2 + src/executor.cpp | 93 +++++++++++++++++++- test/test-action-client.js | 48 ++++++++++ 3 files changed, 142 insertions(+), 1 deletion(-) diff --git a/.github/workflows/windows-build-and-test.yml b/.github/workflows/windows-build-and-test.yml index 570e765a7..b2a4e48b8 100644 --- a/.github/workflows/windows-build-and-test.yml +++ b/.github/workflows/windows-build-and-test.yml @@ -101,6 +101,8 @@ jobs: - name: Test rclnodejs if: ${{ matrix.run_tests }} uses: nick-fields/retry@v4 + env: + RCLNODEJS_ACTION_DIAGNOSTICS: '1' with: shell: cmd max_attempts: 2 diff --git a/src/executor.cpp b/src/executor.cpp index 11cac903e..2bad602c1 100644 --- a/src/executor.cpp +++ b/src/executor.cpp @@ -20,6 +20,16 @@ #include #include +#ifdef _WIN32 +#include + +#include +#include +#include +#include +#include +#endif + #include "handle_manager.h" #include "macros.h" #include "rcl_bindings.h" @@ -34,6 +44,76 @@ namespace rclnodejs { namespace { +#ifdef _WIN32 +void PrintDiagnosticAddress(const void* address) { + MEMORY_BASIC_INFORMATION memory = {}; + char module_path[MAX_PATH] = {}; + if (VirtualQuery(address, &memory, sizeof(memory)) == 0 || + GetModuleFileNameA(static_cast(memory.AllocationBase), + module_path, MAX_PATH) == 0) { + fprintf(stderr, "[native-diag] address=%p module=unknown\n", address); + return; + } + const char* name = strrchr(module_path, '\\'); + const auto offset = reinterpret_cast(address) - + reinterpret_cast(memory.AllocationBase); + fprintf(stderr, + "[native-diag] address=%p module=%s offset=0x%" PRIxPTR "\n", + address, name ? name + 1 : module_path, offset); +} + +void PrintDiagnosticStack() { + void* frames[32] = {}; + const USHORT count = CaptureStackBackTrace(0, 32, frames, nullptr); + for (USHORT index = 0; index < count; ++index) { + fprintf(stderr, "[native-diag] frame=%u\n", + static_cast(index)); + PrintDiagnosticAddress(frames[index]); + } + fflush(stderr); +} + +LONG CALLBACK TraceNativeException(EXCEPTION_POINTERS* exception) { + const DWORD code = exception->ExceptionRecord->ExceptionCode; + if (code != EXCEPTION_ACCESS_VIOLATION && + code != EXCEPTION_INT_DIVIDE_BY_ZERO) { + return EXCEPTION_CONTINUE_SEARCH; + } + static volatile LONG reporting = 0; + if (InterlockedCompareExchange(&reporting, 1, 0) != 0) { + return EXCEPTION_CONTINUE_SEARCH; + } + fprintf(stderr, + "[native-diag] first-chance code=0x%08" PRIx32 " thread=%" PRIu32 + "\n", + static_cast(code), + static_cast(GetCurrentThreadId())); + PrintDiagnosticAddress(exception->ExceptionRecord->ExceptionAddress); + PrintDiagnosticStack(); + InterlockedExchange(&reporting, 0); + return EXCEPTION_CONTINUE_SEARCH; +} + +void InstallNativeDiagnostics(Napi::Env env) { + const char* enabled = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); + if (!enabled || strcmp(enabled, "1") != 0) return; + static std::once_flag installed; + std::call_once(installed, [env] { + void* handler = AddVectoredExceptionHandler(1, TraceNativeException); + if (!handler) { + Napi::Error::New(env, "Failed to install native exception diagnostics") + .ThrowAsJavaScriptException(); + return; + } + env.AddCleanupHook( + [](void* registration) { + RemoveVectoredExceptionHandler(registration); + }, + handler); + }); +} +#endif + void ReportCallbackError(const Napi::Error& error) noexcept { try { Napi::HandleScope scope(error.Env()); @@ -67,7 +147,11 @@ Executor::Executor(Napi::Env env, HandleManager* handle_manager, env_(env), state_(ExecutorState::Stopped), js_dispatch_pending_(false), - callbacks_in_flight_(0) {} + callbacks_in_flight_(0) { +#ifdef _WIN32 + InstallNativeDiagnostics(env); +#endif +} Executor::~Executor() { // Note: don't free this->async_ in ctor @@ -315,6 +399,13 @@ void Executor::DoWork(uv_async_t* handle) { } catch (const std::exception& error) { Napi::Error::Fatal("Executor::DoWork", error.what()); } catch (...) { +#ifdef _WIN32 + const char* diagnostics = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); + if (diagnostics && strcmp(diagnostics, "1") == 0) { + fprintf(stderr, "[native-diag] executor catch-all exception\n"); + PrintDiagnosticStack(); + } +#endif Napi::Error::Fatal("Executor::DoWork", "Unknown native exception in executor callback"); } diff --git a/test/test-action-client.js b/test/test-action-client.js index c0624cbe6..e21c099c0 100644 --- a/test/test-action-client.js +++ b/test/test-action-client.js @@ -18,8 +18,44 @@ import * as assertUtils from './utils.js'; import rclnodejs from '../index.js'; import { isActionIntrospectionSupported } from './utils.js'; import nativeLoader from '../lib/native_loader.js'; +import { writeSync } from 'node:fs'; const { ActionUuid } = rclnodejs; +const diagnostics = process.env.RCLNODEJS_ACTION_DIAGNOSTICS === '1'; +let diagnosticSequence = 0; +function traceDiagnostic(message) { + if (diagnostics) { + writeSync(2, `[action-diag ${++diagnosticSequence}] ${message}\n`); + } +} + +if (diagnostics) { + for (const name of [ + 'actionCreateClient', + 'actionCreateServer', + 'actionSendGoalRequest', + 'actionTakeGoalResponse', + 'actionTakeFeedback', + 'actionTakeStatus', + 'actionConfigureFeedbackSubFilterAddGoalId', + 'actionConfigureFeedbackSubFilterRemoveGoalId', + ]) { + const original = nativeLoader[name]; + if (typeof original !== 'function') { + traceDiagnostic(`${name} unavailable`); + continue; + } + nativeLoader[name] = function (...args) { + traceDiagnostic(`${name} enter`); + try { + return original.apply(this, args); + } finally { + traceDiagnostic(`${name} leave`); + } + }; + } +} + describe('rclnodejs action client', function () { let node; let server; @@ -63,9 +99,12 @@ describe('rclnodejs action client', function () { }); beforeEach(function () { + traceDiagnostic(`beforeEach start: ${this.currentTest.fullTitle()}`); Fibonacci = rclnodejs.require(fibonacci); + traceDiagnostic('createNode enter'); node = rclnodejs.createNode('action_client_node'); + traceDiagnostic('createNode leave'); server = new rclnodejs.ActionServer( node, fibonacci, @@ -76,13 +115,22 @@ describe('rclnodejs action client', function () { () => rclnodejs.CancelResponse.ACCEPT ); + traceDiagnostic('spin enter'); rclnodejs.spin(node); + traceDiagnostic('spin leave'); + traceDiagnostic('beforeEach complete'); }); afterEach(function () { + traceDiagnostic(`afterEach start: ${this.currentTest.fullTitle()}`); publishFeedback = null; + traceDiagnostic('server.destroy enter'); server.destroy(); + traceDiagnostic('server.destroy leave'); + traceDiagnostic('node.destroy enter'); node.destroy(); + traceDiagnostic('node.destroy leave'); + traceDiagnostic('afterEach complete'); }); it('Test defaults', function () { From fd101a22212bc1a4b9625b859d746d437a239add Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sun, 29 Nov 2026 14:45:54 +0000 Subject: [PATCH 3/6] Fix Windows diagnostic cleanup hook capture Make the call_once lambda mutable so its captured Napi::Env can invoke the non-const AddCleanupHook API, addressing the C2662 diagnostic build error. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/executor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/executor.cpp b/src/executor.cpp index 2bad602c1..48b4ae466 100644 --- a/src/executor.cpp +++ b/src/executor.cpp @@ -98,7 +98,7 @@ void InstallNativeDiagnostics(Napi::Env env) { const char* enabled = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); if (!enabled || strcmp(enabled, "1") != 0) return; static std::once_flag installed; - std::call_once(installed, [env] { + std::call_once(installed, [env]() mutable { void* handler = AddVectoredExceptionHandler(1, TraceNativeException); if (!handler) { Napi::Error::New(env, "Failed to install native exception diagnostics") From ce1e14860634bbe93586b57b0f0672fcbcf26336 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sun, 29 Nov 2026 15:50:44 +0000 Subject: [PATCH 4/6] Add native-only Windows exception diagnostics Allow RCLNODEJS_ACTION_DIAGNOSTICS=native to capture first-chance exceptions without synchronous JS action-call wrappers. Log handler registration and use native-only mode in Windows CI to reduce timing perturbation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/windows-build-and-test.yml | 3 ++- src/executor.cpp | 14 ++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.github/workflows/windows-build-and-test.yml b/.github/workflows/windows-build-and-test.yml index b2a4e48b8..f36f50079 100644 --- a/.github/workflows/windows-build-and-test.yml +++ b/.github/workflows/windows-build-and-test.yml @@ -102,7 +102,8 @@ jobs: if: ${{ matrix.run_tests }} uses: nick-fields/retry@v4 env: - RCLNODEJS_ACTION_DIAGNOSTICS: '1' + # 'native' keeps exception tracing; '1' also enables synchronous JS logs. + RCLNODEJS_ACTION_DIAGNOSTICS: 'native' with: shell: cmd max_attempts: 2 diff --git a/src/executor.cpp b/src/executor.cpp index 48b4ae466..455806fb9 100644 --- a/src/executor.cpp +++ b/src/executor.cpp @@ -45,6 +45,12 @@ namespace rclnodejs { namespace { #ifdef _WIN32 +bool NativeDiagnosticsEnabled() { + const char* enabled = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); + return enabled && + (strcmp(enabled, "1") == 0 || strcmp(enabled, "native") == 0); +} + void PrintDiagnosticAddress(const void* address) { MEMORY_BASIC_INFORMATION memory = {}; char module_path[MAX_PATH] = {}; @@ -95,8 +101,7 @@ LONG CALLBACK TraceNativeException(EXCEPTION_POINTERS* exception) { } void InstallNativeDiagnostics(Napi::Env env) { - const char* enabled = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); - if (!enabled || strcmp(enabled, "1") != 0) return; + if (!NativeDiagnosticsEnabled()) return; static std::once_flag installed; std::call_once(installed, [env]() mutable { void* handler = AddVectoredExceptionHandler(1, TraceNativeException); @@ -110,6 +115,8 @@ void InstallNativeDiagnostics(Napi::Env env) { RemoveVectoredExceptionHandler(registration); }, handler); + fprintf(stderr, "[native-diag] first-chance handler installed\n"); + fflush(stderr); }); } #endif @@ -400,8 +407,7 @@ void Executor::DoWork(uv_async_t* handle) { Napi::Error::Fatal("Executor::DoWork", error.what()); } catch (...) { #ifdef _WIN32 - const char* diagnostics = getenv("RCLNODEJS_ACTION_DIAGNOSTICS"); - if (diagnostics && strcmp(diagnostics, "1") == 0) { + if (NativeDiagnosticsEnabled()) { fprintf(stderr, "[native-diag] executor catch-all exception\n"); PrintDiagnosticStack(); } From 10a4862c58ef0f381a739127aa88e3cbdbd2dd51 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 09:34:37 +0000 Subject: [PATCH 5/6] Change to windows-2022 --- .github/workflows/windows-build-and-test.yml | 15 ++++++- src/executor.cpp | 47 ++++++++++++++++---- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/.github/workflows/windows-build-and-test.yml b/.github/workflows/windows-build-and-test.yml index f36f50079..ad54e8df9 100644 --- a/.github/workflows/windows-build-and-test.yml +++ b/.github/workflows/windows-build-and-test.yml @@ -10,7 +10,7 @@ on: jobs: build: - runs-on: windows-2025 + runs-on: windows-2022 strategy: fail-fast: false matrix: @@ -88,6 +88,7 @@ jobs: - uses: actions/checkout@v7 - name: Build rclnodejs + id: native-build shell: cmd run: | set PATH=C:\pixi_ws\.pixi\envs\default\Library\bin;C:\pixi_ws\.pixi\envs\default\Scripts;C:\pixi_ws\.pixi\envs\default\bin;%PATH% @@ -115,3 +116,15 @@ jobs: call "C:\pixi_ws\ros2-windows\setup.bat" && py -3 -m pip install "lark==1.1.9" && call npm test + + - name: Probe rcutils string boundaries + if: ${{ always() && matrix.run_tests && steps.native-build.outcome == 'success' }} + shell: cmd + run: | + set PATH=C:\pixi_ws\.pixi\envs\default\Library\bin;C:\pixi_ws\.pixi\envs\default\Scripts;C:\pixi_ws\.pixi\envs\default\bin;%PATH% + call "C:\pixi_ws\ros2-windows\setup.bat" + cl /nologo /EHsc /std:c++17 /MD /I"C:\pixi_ws\ros2-windows\include" /I"C:\pixi_ws\ros2-windows\include\rcutils" test\rcutils-string-boundary-probe.cpp /Fe:build\Release\rcutils-string-probe.exe /link /LIBPATH:"C:\pixi_ws\ros2-windows\lib" rcutils.lib + if errorlevel 1 exit /b 1 + build\Release\rcutils-string-probe.exe bounded + if errorlevel 1 exit /b 1 + build\Release\rcutils-string-probe.exe unbounded diff --git a/src/executor.cpp b/src/executor.cpp index 455806fb9..f79fc53f7 100644 --- a/src/executor.cpp +++ b/src/executor.cpp @@ -16,6 +16,7 @@ #include +#include #include #include #include @@ -63,8 +64,7 @@ void PrintDiagnosticAddress(const void* address) { const char* name = strrchr(module_path, '\\'); const auto offset = reinterpret_cast(address) - reinterpret_cast(memory.AllocationBase); - fprintf(stderr, - "[native-diag] address=%p module=%s offset=0x%" PRIxPTR "\n", + fprintf(stderr, "[native-diag] address=%p module=%s offset=0x%" PRIxPTR "\n", address, name ? name + 1 : module_path, offset); } @@ -72,13 +72,29 @@ void PrintDiagnosticStack() { void* frames[32] = {}; const USHORT count = CaptureStackBackTrace(0, 32, frames, nullptr); for (USHORT index = 0; index < count; ++index) { - fprintf(stderr, "[native-diag] frame=%u\n", - static_cast(index)); + fprintf(stderr, "[native-diag] frame=%u\n", static_cast(index)); PrintDiagnosticAddress(frames[index]); } fflush(stderr); } +void PrintRuntimeSymbols() { + HMODULE runtime = GetModuleHandleA("VCRUNTIME140.dll"); + if (!runtime) { + fprintf(stderr, "[native-diag] VCRUNTIME140.dll unavailable\n"); + return; + } + for (const char* name : {"memchr", "memcpy", "memmove"}) { + FARPROC symbol = GetProcAddress(runtime, name); + fprintf(stderr, "[native-diag] runtime symbol=%s\n", name); + if (symbol) { + PrintDiagnosticAddress(reinterpret_cast(symbol)); + } else { + fprintf(stderr, "[native-diag] runtime symbol unavailable\n"); + } + } +} + LONG CALLBACK TraceNativeException(EXCEPTION_POINTERS* exception) { const DWORD code = exception->ExceptionRecord->ExceptionCode; if (code != EXCEPTION_ACCESS_VIOLATION && @@ -89,12 +105,24 @@ LONG CALLBACK TraceNativeException(EXCEPTION_POINTERS* exception) { if (InterlockedCompareExchange(&reporting, 1, 0) != 0) { return EXCEPTION_CONTINUE_SEARCH; } - fprintf(stderr, - "[native-diag] first-chance code=0x%08" PRIx32 " thread=%" PRIu32 - "\n", - static_cast(code), - static_cast(GetCurrentThreadId())); + fprintf( + stderr, + "[native-diag] first-chance code=0x%08" PRIx32 " thread=%" PRIu32 "\n", + static_cast(code), static_cast(GetCurrentThreadId())); PrintDiagnosticAddress(exception->ExceptionRecord->ExceptionAddress); + if (code == EXCEPTION_ACCESS_VIOLATION && + exception->ExceptionRecord->NumberParameters >= 2) { + fprintf(stderr, "[native-diag] access=%" PRIuPTR " fault=0x%" PRIxPTR "\n", + static_cast( + exception->ExceptionRecord->ExceptionInformation[0]), + static_cast( + exception->ExceptionRecord->ExceptionInformation[1])); + } +#if defined(_M_X64) || defined(__x86_64__) + fprintf(stderr, "[native-diag] x64 arg1=0x%" PRIxPTR " arg3=0x%" PRIxPTR "\n", + static_cast(exception->ContextRecord->Rcx), + static_cast(exception->ContextRecord->R8)); +#endif PrintDiagnosticStack(); InterlockedExchange(&reporting, 0); return EXCEPTION_CONTINUE_SEARCH; @@ -116,6 +144,7 @@ void InstallNativeDiagnostics(Napi::Env env) { }, handler); fprintf(stderr, "[native-diag] first-chance handler installed\n"); + PrintRuntimeSymbols(); fflush(stderr); }); } From d6bf4f359187997126748929aeff1ab59c0af5b1 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 09:51:14 +0000 Subject: [PATCH 6/6] Add comments --- test/rcutils-string-boundary-probe.cpp | 140 +++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 test/rcutils-string-boundary-probe.cpp diff --git a/test/rcutils-string-boundary-probe.cpp b/test/rcutils-string-boundary-probe.cpp new file mode 100644 index 000000000..24a9b2c67 --- /dev/null +++ b/test/rcutils-string-boundary-probe.cpp @@ -0,0 +1,140 @@ +// Copyright (c) 2026, The Robot Web Tools Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#include +#include + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2 || + (strcmp(argv[1], "bounded") != 0 && strcmp(argv[1], "unbounded") != 0)) { + fprintf(stderr, "Usage: rcutils-string-probe bounded|unbounded\n"); + return EXIT_FAILURE; + } + const bool bounded = strcmp(argv[1], "bounded") == 0; + size_t page_size; + void* allocation; +#ifdef _WIN32 + SYSTEM_INFO system = {}; + GetSystemInfo(&system); + page_size = system.dwPageSize; + allocation = VirtualAlloc(nullptr, page_size * 2, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE); + if (!allocation) { + fprintf(stderr, "VirtualAlloc failed: %" PRIu32 "\n", + static_cast(GetLastError())); + return EXIT_FAILURE; + } + DWORD previous; + if (!VirtualProtect(static_cast(allocation) + page_size, page_size, + PAGE_NOACCESS, &previous)) { + fprintf(stderr, "VirtualProtect failed: %" PRIu32 "\n", + static_cast(GetLastError())); + VirtualFree(allocation, 0, MEM_RELEASE); + return EXIT_FAILURE; + } + HMODULE runtime = GetModuleHandleA("VCRUNTIME140.dll"); + if (runtime) { + for (const char* name : {"memchr", "memcpy"}) { + FARPROC symbol = GetProcAddress(runtime, name); + if (symbol) { + const auto offset = reinterpret_cast(symbol) - + reinterpret_cast(runtime); + printf("[rcutils-probe] %s offset=0x%" PRIxPTR "\n", name, offset); + } else { + printf("[rcutils-probe] %s unavailable\n", name); + } + } + } else { + printf("[rcutils-probe] VCRUNTIME140.dll unavailable\n"); + } +#else + const auto size = sysconf(_SC_PAGESIZE); + if (size <= 0) { + perror("sysconf"); + return EXIT_FAILURE; + } + page_size = static_cast(size); + allocation = mmap(nullptr, page_size * 2, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (allocation == MAP_FAILED) { + perror("mmap"); + return EXIT_FAILURE; + } + if (mprotect(static_cast(allocation) + page_size, page_size, + PROT_NONE) != 0) { + perror("mprotect"); + munmap(allocation, page_size * 2); + return EXIT_FAILURE; + } +#endif + + const rcutils_allocator_t allocator = rcutils_get_default_allocator(); + bool passed = true; + for (const bool guarded : {false, true}) { + if (!passed) break; + for (const size_t length : + {size_t{0}, size_t{1}, size_t{3}, size_t{31}, size_t{32}, size_t{63}, + size_t{64}, size_t{407}}) { + char sample[512] = {}; + memset(sample, '7', length); + char* value = sample; + if (guarded) { + value = static_cast(allocation) + page_size - length - 1; + memcpy(value, sample, length + 1); + } + printf("[rcutils-probe] mode=%s storage=%s length=%zu\n", argv[1], + guarded ? "guarded" : "ordinary", length); + fflush(stdout); + char* copy = bounded ? rcutils_strndup(value, length, allocator) + : rcutils_strdup(value, allocator); + if (!copy) { + fprintf(stderr, "[rcutils-probe] copy returned null\n"); + passed = false; + break; + } + passed = memcmp(copy, sample, length + 1) == 0; + allocator.deallocate(copy, allocator.state); + if (!passed) { + fprintf(stderr, "[rcutils-probe] copied string differs\n"); + break; + } + } + } +#ifdef _WIN32 + if (!VirtualFree(allocation, 0, MEM_RELEASE)) { + fprintf(stderr, "VirtualFree failed: %" PRIu32 "\n", + static_cast(GetLastError())); + return EXIT_FAILURE; + } +#else + if (munmap(allocation, page_size * 2) != 0) { + perror("munmap"); + return EXIT_FAILURE; + } +#endif + return passed ? EXIT_SUCCESS : EXIT_FAILURE; +}