microsoft / Windows-driver-samples

This repo contains driver samples prepared for use with Microsoft Visual Studio and the Windows Driver Kit (WDK). It contains both Universal Windows Driver and desktop-only driver samples.
Microsoft Public License
7k stars 4.94k forks source link

[serial/VirtualSerial2] code is not concise enough #1194

Open aspist opened 4 months ago

aspist commented 4 months ago

in serial/VirtualSerial2/device.c line 166-207:

  //
    // Manually create the symbolic link name. Length is the length in
    // bytes not including the NULL terminator.
    //
    // 6054 and 26035 are code analysis warnings that comPort.Buffer might
    // not be NULL terminated, while we know that they are. 
    //
    #pragma warning(suppress: 6054 26035)
    symbolicLinkName.Length = (USHORT)((wcslen(comPort.Buffer) * sizeof(wchar_t))
                                + sizeof(SYMBOLIC_LINK_NAME_PREFIX) - sizeof(UNICODE_NULL));

    if (symbolicLinkName.Length >= symbolicLinkName.MaximumLength) {

        Trace(TRACE_LEVEL_ERROR, "Error: Buffer overflow when creating COM port name. Size"
            " is %d, buffer length is %d", symbolicLinkName.Length, symbolicLinkName.MaximumLength);
        status = STATUS_BUFFER_OVERFLOW;
        goto Exit;
    }

    errorNo = wcscpy_s(symbolicLinkName.Buffer,
                       SYMBOLIC_LINK_NAME_LENGTH,
                       SYMBOLIC_LINK_NAME_PREFIX);

    if (errorNo != 0) {
        Trace(TRACE_LEVEL_ERROR, 
              "Failed to copy %ws to buffer with error %d",
              SYMBOLIC_LINK_NAME_PREFIX, errorNo);
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    errorNo = wcscat_s(symbolicLinkName.Buffer,
                       SYMBOLIC_LINK_NAME_LENGTH,
                       comPort.Buffer);

    if (errorNo != 0) {
        Trace(TRACE_LEVEL_ERROR, 
              "Failed to copy %ws to buffer with error %d",
              comPort.Buffer, errorNo);
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

replace it with the following code:

status = RtlUnicodeStringCopyString(&symbolicLinkName, SYMBOLIC_LINK_NAME_PREFIX);
if (!NT_SUCCESS(status)) 
{
    Trace(TRACE_LEVEL_ERROR,
        "Error: Cannot create symbolic link name");
    goto Exit;
}
status = RtlUnicodeStringCat(&symbolicLinkName, &comPort);
if (!NT_SUCCESS(status)) {
    Trace(TRACE_LEVEL_ERROR,
        "Error: Cannot create symbolic link name");
    goto Exit;
}