Skip to content

Implement SerialPort.GetPortNames on all non-Apple - #137910

Open
am11 wants to merge 4 commits into
dotnet:mainfrom
am11:feature/ports-getportnames-unix
Open

am11 wants to merge 4 commits into
dotnet:mainfrom
am11:feature/ports-getportnames-unix

Conversation

@am11

@am11 am11 commented Nov 19, 2026

Copy link
Copy Markdown
Member

No description provided.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 19, 2026
@am11
am11 requested a review from adamsitnik November 19, 2026 12:20
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@am11
am11 requested a review from jkotas November 19, 2026 12:21
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-io-ports
See info in area-owners.md if you want to be subscribed.

@adamsitnik
adamsitnik requested a review from krwq November 19, 2026 12:56

@adamsitnik adamsitnik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes LGTM, but it would be great if the owner (@krwq) could take a look as well.

@krwq

krwq commented Nov 20, 2026

Copy link
Copy Markdown
Member

On OpenBSD and NetBSD /dev is static (MAKEDEV creates the nodes up front), so the name check alone can't tell a real port from a placeholder: a stock NetBSD/amd64 install returns 224 names here (192 of them the Cyclades [td]tyCZ*/[td]tyCY* nodes) and OpenBSD/amd64 53, even with a single COM port.

Probing with open() isn't an option since it raises DTR and resets Arduino-style boards, but both systems save the boot messages to /var/run/dmesg.boot (OpenBSD's fw_update reads it the same way to find devices). Fixed serial ports only attach at boot, so we can keep just the nodes whose device shows up there (com0 at ..., plcom0 at ..., cy0 at ...), leave the USB ones alone since adapters get plugged in later, and fall back to today's behavior when the file is missing or its start (the boot banner) is gone:

// OpenBSD and NetBSD have a static /dev with nodes for every unit MAKEDEV knows about. Fixed serial ports only
// attach at boot, so the dmesg copy saved at boot tells which of them exist (like OpenBSD's fw_update uses it).
// Returns the attached devices, both as "com0" and as the driver "com", or null if that can't be determined.
private static HashSet<string>? GetBootDevices()
{
    HashSet<string> devices = [];
    bool sawBootBanner = false;

    try
    {
        foreach (string line in File.ReadLines("/var/run/dmesg.boot"))
        {
            // NetBSD may prefix messages with a timestamp, e.g. "[     1.003637] com0 at isa0 port 0x3f8-0x3ff irq 4".
            ReadOnlySpan<char> message = line.AsSpan();
            if (message.StartsWith('['))
            {
                message = message.Slice(message.IndexOf(']') + 1).TrimStart();
            }

            // The message buffer can still hold an earlier boot, so only the last one counts.
            if (message.StartsWith("OpenBSD ", StringComparison.Ordinal) || message.StartsWith("NetBSD ", StringComparison.Ordinal))
            {
                devices.Clear();
                sawBootBanner = true;
                continue;
            }

            // e.g. "com0 at acpi0 COM1 addr 0x3f8/0x8 irq 4: ns16550a, 16 byte fifo"
            int at = message.IndexOf(" at ", StringComparison.Ordinal);
            if (at > 0 && !message.Slice(0, at).ContainsAny(' ', ':'))
            {
                ReadOnlySpan<char> device = message.Slice(0, at);
                devices.Add(device.ToString());
                devices.Add(device.TrimEnd("0123456789").ToString());
            }
        }
    }
    catch (Exception e) when (e is IOException or UnauthorizedAccessException)
    {
        return null;
    }

    // Without the boot banner the start of the boot was lost, so attach messages may be missing too.
    return sawBootBanner ? devices : null;
}

The matchers then return the device behind a node instead of a bool (null = not a serial port, "" = USB), and the loop becomes:

if (GetOpenBSDSerialDevice(Path.GetFileName(path.AsSpan())) is string device &&
    (device.Length == 0 || bootDevices is null || bootDevices.Contains(device)))
  • OpenBSD: tty0a/cua0a → com10 (MAKEDEV units are hex), ttyc* → cy, ttyVI* → viocon, ttyU* → ""
  • NetBSD: tty00/dty00 → com0, ttyZ0 → zstty0, plcom0/dplcom0 → plcom0, [td]tyCY*/[td]tyCZ* → cy/cz, ttyVI* → viocon, ttyU*/ttyY* → ""

With real dmesg.boot files from dmesgd.nycbug.org this goes from 224 to 24 names on a Dell R640 running NetBSD (com0 and com1, plus the 20 USB nodes), and from 53 to 10 on an OpenBSD Ryzen box with com0. A test along these lines (with /dev and /var/run/dmesg.boot pointed at a temp dir, and the result reduced to sorted file names) fails on the current code, which also returns tty01/cua01, ttyc0/cuac0 and ttyVI00, and passes with the change:

[Fact]
public void OpenBSD_OnlyListsPortsThatAttachedAtBoot()
{
    CreateDev("tty00", "cua00", "tty01", "cua01", "ttyc0", "cuac0", "ttyU0", "cuaU0", "ttyVI00", "ttyp0", "console");
    WriteDmesgBoot("""
        OpenBSD 8.0 (GENERIC.MP) #84: Tue Oct  6 23:13:49 MDT 2026
        com0 at acpi0 UAR1 addr 0x3f8/0x8 irq 4: ns16550a, 16 byte fifo
        """);

    Assert.Equal(new[] { "cua00", "cuaU0", "tty00", "ttyU0" }, GetPortNames_OpenBSD());
}

[Fact]
public void NetBSD_OnlyListsPortsThatAttachedAtBoot()
{
    CreateDev("tty00", "dty00", "tty01", "dty01", "ttyU0", "dtyU0", "ttyCY000", "dtyCY000", "ttyCZ0000", "plcom0", "dplcom0", "ttyVI00", "ttyp0", "ttyE0");
    WriteDmesgBoot("""
        [     1.000000] NetBSD 11.1 (GENERIC) #0: Mon Nov  2 16:34:32 UTC 2026
        [     1.003637] com0 at acpi0 (COM1, PNP0501-1): io 0x3f8-0x3ff irq 4
        """);

    Assert.Equal(new[] { "dty00", "dtyU0", "tty00", "ttyU0" }, GetPortNames_NetBSD());
}

Note

This comment was generated with the help of AI. Please review before applying.

am11 and others added 2 commits November 20, 2026 15:08
/dev is static on both, so keep only the nodes whose device is in /var/run/dmesg.boot.
USB nodes are always listed, and everything is listed when the boot devices can't be determined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@krwq
krwq requested a review from wfurt November 20, 2026 13:52

@krwq krwq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, and fair enough on the tests. Sorry, my suggestion missed one case: on OpenBSD/arm64 the console UART takes over com's device nodes. When pluart (Raspberry Pi, arm64 VMs like Hetzner's) or exuart/imxuart/mvuart/amluart/cduart is the console, it replaces com's device switch entry with its own (cdevsw[maj] = pluartdev; /* KLUDGE */ in sys/dev/ic/pluart.c), so /dev/tty00 is pluart0 and dmesg never mentions com0. With the current change that port gets filtered out, so a Raspberry Pi with a serial console gets only the USB nodes back (before, tty00 was at least listed). Tracking the serial console's driver fixes it, see the suggestions below (they can be committed as one batch).

With real dmesg output from a Raspberry Pi 3, a Raspberry Pi 5 and a Hetzner CAX11 this keeps tty00/cua00; on an ODROID HC4 and an M2 MacBook, where amluart/exuart isn't the console and so has no /dev node of its own, tty00 is still dropped. The same kind of temp-dir test as before fails on the current code (nothing is returned) and passes with the change:

[Fact]
public void OpenBSD_SerialConsoleOwnsTheComNodes()
{
    CreateDev("tty00", "cua00", "tty01", "cua01");
    WriteDmesgBoot("""
        OpenBSD 8.0 (GENERIC.MP) #84: Tue Oct  6 23:13:49 MDT 2026
        pluart0 at simplebus1: rev 3, 32 byte fifo
        pluart0: console
        """);

    Assert.Equal(new[] { "cua00", "tty00" }, GetPortNames_OpenBSD());
}

Note

This comment was generated with the help of AI. Please review before applying.

@krwq

krwq commented Nov 20, 2026

Copy link
Copy Markdown
Member

@pgrawehr @raffaeler please see if you want to take a look at this as well

@am11

am11 commented Nov 20, 2026 •

Copy link
Copy Markdown
Member Author

Applied in 5f17816, thanks.

@krwq krwq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM on my end now, would be nice if @wfurt could review as well and if we got some testing with real hardware but given it's currently not working I'm willing to also take it as is as long as you confirm it works for your scenario.

@pgrawehr

Copy link
Copy Markdown

I have no experience with any of the newly supported OS types, so I don't think I can be of help here.

@raffaeler

Copy link
Copy Markdown

@krwq I have no experience on BSD-like OSes.
Running dotnet/iot tests could help. If the lab has loopback cables attached on the Mac we could run the full tests (a simple RX/TX short should be enough).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.IO.Ports community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants