Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a693826
[#12] Add CallbackContext for GCHandle-pinned FFI state
patdhlk Apr 23, 2026
8195dbb
[#12] CallbackContext: clarify Unpin return-value purpose
patdhlk Apr 23, 2026
b598400
[#12] Add CallbackContext edge-case and leak tests
patdhlk Apr 23, 2026
15ee67a
[#12] Stabilize leak test under Debug JIT local-lifetime extension
patdhlk Apr 23, 2026
afd721c
[#12] Add FfiAssert test helper for readable FFI failures
patdhlk Apr 23, 2026
e4df1c7
[#12] Add tripwire tests for FFI struct sizes
patdhlk Apr 23, 2026
6897459
[#12] Add concurrent Node.List() tests (demonstrates race)
patdhlk Apr 23, 2026
115556e
[#12] Fix IOX2_SERVICE_ID_LENGTH: 32 -> 64
patdhlk Apr 23, 2026
bf33601
[#12] Fix Node.List() callback race with CallbackContext
patdhlk Apr 23, 2026
c776c81
[#12] WaitAndProcessOnce: pin callback via CallbackContext
patdhlk Apr 23, 2026
514c7a1
[#12] WaitAndProcessOnce(timeout): pin callback via CallbackContext
patdhlk Apr 23, 2026
4a7b3ed
[#12] WaitAndProcess: pin callback context; remove _nativeCallback
patdhlk Apr 23, 2026
0805619
[#12] Add WaitSet concurrent-instance and trampoline tests
patdhlk Apr 23, 2026
014cb90
[#12] Update CHANGELOG with callback-safety bugfix
patdhlk Apr 23, 2026
d666dc9
[#12] WaitSet throw test: drop unneeded async/await
patdhlk Apr 23, 2026
8f1c44f
[#12] Apply dotnet format (using order, trailing newline)
patdhlk Apr 24, 2026
7bdd9fd
[#12] Bump new-file copyright headers 2025 -> 2026
patdhlk May 19, 2026
3f2d914
[#12] CHANGELOG: split bugfix entry into per-fix bullets
patdhlk May 19, 2026
708cc02
[#12] Node.List callback: restore offset/marshal comments
patdhlk May 19, 2026
493c2de
[#12] Node.List callback: log exception with stack trace
patdhlk May 19, 2026
eebaffe
[#12] NativeStructSizesTests: document why sizes are duplicated
patdhlk May 19, 2026
b2a8498
[#12] CallbackContext: tests for misuse + double-free contract
patdhlk May 27, 2026
6ded0f6
[#12] RuntimeTests: use FfiAssert.Ok for raw FFI return codes
patdhlk May 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Bugfixes

<!-- Bug fixes go here -->
* Fix race condition in `Node.List()` where concurrent calls shared a static
callback buffer; the callback now uses a per-call `GCHandle`-pinned context
[#12](https://github.com/eclipse-iceoryx/iceoryx2-csharp/issues/12)
* Fix cross-call overwrite in `WaitSet.WaitAndProcessOnce*` by removing the
`_nativeCallback` instance field; each call now pins its own context via
static trampolines
[#12](https://github.com/eclipse-iceoryx/iceoryx2-csharp/issues/12)
* Fix `IOX2_SERVICE_ID_LENGTH` (32 → 64) to match the cbindgen-generated C
header, correcting `Node.List()`'s manual marshal offsets
[#12](https://github.com/eclipse-iceoryx/iceoryx2-csharp/issues/12)

### Refactoring

Expand Down
99 changes: 99 additions & 0 deletions src/Iceoryx2/Native/CallbackContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright (c) 2026 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

using System;
using System.Runtime.InteropServices;

namespace Iceoryx2.Native;

/// <summary>
/// Pins managed state so it can be passed through an FFI boundary as an opaque
/// <see cref="IntPtr"/> context and recovered inside a native callback.
/// </summary>
/// <remarks>
/// <para>Usage:</para>
/// <code>
/// var ctx = CallbackContext.Pin(state);
/// try { NativeCall(..., Trampoline, ctx); }
/// finally { CallbackContext.Unpin&lt;TState&gt;(ctx); }
///
/// // Inside the static trampoline:
/// var state = CallbackContext.Peek&lt;TState&gt;(contextPtr);
/// </code>
/// <para>
/// <b>Safety contract.</b> The returned <see cref="IntPtr"/> is a raw handle into
/// the runtime's GC handle table; treat it like a C pointer to manually managed
/// storage. Every <see cref="Pin{T}"/> MUST be matched by exactly one
/// <see cref="Unpin{T}"/>, ideally in a <c>try</c>/<c>finally</c> wrapping the
/// native call. After <see cref="Unpin{T}"/> the token MUST NOT be used again
/// (no further <see cref="Peek{T}"/>, no second <see cref="Unpin{T}"/>): the
/// runtime recycles handle slots aggressively, so a re-used token can silently
/// resolve to an unrelated pin and double-free it — the .NET analogue of a C
/// use-after-free / double-free. The <c>IsAllocated</c> preliminary check
/// inside <see cref="Unpin{T}"/> defends against <see cref="IntPtr.Zero"/> only;
/// it cannot detect a recycled slot.
/// </para>
/// </remarks>
internal static class CallbackContext
{
/// <summary>
/// Allocates a normal <see cref="GCHandle"/> for <paramref name="state"/> and
/// returns its <see cref="IntPtr"/> token, suitable for passing through FFI.
/// </summary>
public static IntPtr Pin<T>(T state) where T : class
{
ArgumentNullException.ThrowIfNull(state);
var handle = GCHandle.Alloc(state, GCHandleType.Normal);
return GCHandle.ToIntPtr(handle);
}

/// <summary>
/// Recovers the pinned state without freeing the handle. Safe from a callback.
/// Returns <c>null</c> when <paramref name="token"/> is <see cref="IntPtr.Zero"/>
/// or the target is not of type <typeparamref name="T"/>.
/// </summary>
public static T? Peek<T>(IntPtr token) where T : class
{
if (token == IntPtr.Zero)
return null;
var handle = GCHandle.FromIntPtr(token);
return handle.IsAllocated ? handle.Target as T : null;
}

/// <summary>
/// Frees the <see cref="GCHandle"/> and returns the (now unrooted) state.
/// MUST be called exactly once per <see cref="Pin{T}"/>, in a <c>finally</c>.
Comment thread
dkroenke marked this conversation as resolved.
Resolved
/// </summary>
/// <remarks>
/// <para>
/// The returned value is provided to enable round-trip testing of the
/// pin/unpin contract. Production callers typically discard it because the
/// state object is already rooted on the calling stack frame.
/// </para>
/// <para>
/// If <typeparamref name="T"/> does not match the pinned state's actual
/// type, the underlying <see cref="GCHandle"/> is still freed (no leak) and
/// <c>null</c> is returned.
/// </para>
/// </remarks>
public static T? Unpin<T>(IntPtr token) where T : class
{
if (token == IntPtr.Zero)
return null;
var handle = GCHandle.FromIntPtr(token);
if (!handle.IsAllocated)
return null;
var target = handle.Target as T;
handle.Free();
Comment thread
dkroenke marked this conversation as resolved.
Resolved
return target;
}
}
2 changes: 1 addition & 1 deletion src/Iceoryx2/Native/Iox2NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private static IntPtr DllImportResolver(string libraryName, Assembly assembly, D
internal const int IOX2_OK = 0;
internal const int IOX2_NODE_NAME_LENGTH = 128;
internal const int IOX2_SERVICE_NAME_LENGTH = 255;
internal const int IOX2_SERVICE_ID_LENGTH = 32;
internal const int IOX2_SERVICE_ID_LENGTH = 64;
Comment thread
dkroenke marked this conversation as resolved.
Resolved

// ========================================
// Enums
Expand Down
42 changes: 20 additions & 22 deletions src/Iceoryx2/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,49 +51,50 @@ public sealed class Node : IDisposable
internal Iox2NativeMethods.iox2_service_type_e _serviceType;
private bool _disposed;

private static List<ServiceStaticConfig>? _tempServiceList;

internal Node(SafeNodeHandle handle, Iox2NativeMethods.iox2_service_type_e serviceType = Iox2NativeMethods.iox2_service_type_e.IPC)
{
_handle = handle ?? throw new ArgumentNullException(nameof(handle));
_serviceType = serviceType;
}

private static Iox2NativeMethods.iox2_callback_progression_e ServiceListCallbackStatic(IntPtr configPtr, IntPtr context)
private static Iox2NativeMethods.iox2_callback_progression_e ServiceListCallback(IntPtr configPtr, IntPtr context)
{
try
{
if (configPtr == IntPtr.Zero || _tempServiceList == null)
var list = CallbackContext.Peek<List<ServiceStaticConfig>>(context);
if (list is null || configPtr == IntPtr.Zero)
{
return Iox2NativeMethods.iox2_callback_progression_e.STOP;
}

// Read the basic fields directly from memory without creating the full struct
// to avoid issues with the union in iox2_static_config_t

// to avoid issues with the union in iox2_static_config_t.
byte[] id = new byte[Iox2NativeMethods.IOX2_SERVICE_ID_LENGTH];
byte[] name = new byte[Iox2NativeMethods.IOX2_SERVICE_NAME_LENGTH];

// Read the id array
// Read the id array.
Marshal.Copy(configPtr, id, 0, Iox2NativeMethods.IOX2_SERVICE_ID_LENGTH);

// Read the name array (offset by id size)
// Read the name array (offset by id size).
IntPtr namePtr = IntPtr.Add(configPtr, Iox2NativeMethods.IOX2_SERVICE_ID_LENGTH);
Marshal.Copy(namePtr, name, 0, Iox2NativeMethods.IOX2_SERVICE_NAME_LENGTH);

// Read the messaging pattern (offset by id + name)
// Read the messaging pattern (offset by id + name).
IntPtr patternPtr = IntPtr.Add(configPtr, Iox2NativeMethods.IOX2_SERVICE_ID_LENGTH + Iox2NativeMethods.IOX2_SERVICE_NAME_LENGTH);
var messagingPattern = (Iox2NativeMethods.iox2_messaging_pattern_e)Marshal.ReadInt32(patternPtr);

// Create a simplified service config without the problematic union
var serviceConfig = new ServiceStaticConfig(id, name, messagingPattern);
_tempServiceList.Add(serviceConfig);
// Create a simplified service config without the problematic union.
list.Add(new ServiceStaticConfig(id, name, messagingPattern));
return Iox2NativeMethods.iox2_callback_progression_e.CONTINUE;
}
catch (Exception ex)
{
Console.WriteLine($"Error in service list callback: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
Comment thread
dkroenke marked this conversation as resolved.
Resolved
// Internal marshalling code — surface diagnostics on stderr so
// failures here are debuggable. Distinct from the WaitSet
// trampolines, which intentionally swallow user-callback
// exceptions at the FFI boundary.
Console.Error.WriteLine($"Error in service list callback: {ex.Message}");
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}");
return Iox2NativeMethods.iox2_callback_progression_e.STOP;
}
}
Expand Down Expand Up @@ -172,20 +173,17 @@ public Result<List<ServiceStaticConfig>, ServiceListError> List()
ThrowIfDisposed();

var services = new List<ServiceStaticConfig>();
_tempServiceList = services;
var contextPtr = CallbackContext.Pin(services);

try
{
// Get the global config pointer
var configPtr = Iox2NativeMethods.iox2_config_global_config();

// Call the native service list function with static callback
var result = Iox2NativeMethods.iox2_service_list(
_serviceType,
configPtr, // Use global config instead of NULL
ServiceListCallbackStatic,
IntPtr.Zero // No callback context
);
configPtr,
ServiceListCallback,
contextPtr);

if (result != Iox2NativeMethods.IOX2_OK)
{
Expand All @@ -204,7 +202,7 @@ public Result<List<ServiceStaticConfig>, ServiceListError> List()
}
finally
{
_tempServiceList = null;
CallbackContext.Unpin<List<ServiceStaticConfig>>(contextPtr);
}
}

Expand Down
Loading
Loading