Bug in ScardListReaders when called with NULL context?

Zoltan Kelemen 21 Reputation points
2020-12-21T10:20:21.463+00:00

I would like to ask if someone can confirm if the following is a bug in Windows.

When SCardListReaders is called with a NULL context (which is allowed by the API), and the reader list is empty in the registry, the function returns without zero-terminating the buffer. The bug is present from Windows 7 at least, and only in the ANSI variant (SCardListReadersA). The Unicode version works fine.

To trigger the problem, remove all subkeys in: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Calais\Readers

The example program below shows the problem. When run with an empty reader list in the registry, it reports "Missing zero terminator in reader list".

#include <windows.h>
#include <winscard.h>
#include <stdio.h>
#include <stdlib.h>

#pragma comment(lib, "winscard.lib")

int main(void)
{
    char *buf;
    DWORD bufSize = 0;
    char *p;
    DWORD r;

    if ((r = SCardListReadersA(0, NULL, NULL, &bufSize)) != SCARD_S_SUCCESS) {
        printf("Failed to get reader list size: %08x\n", r);
        return 1;
    }

    if (!bufSize) {
        printf("Invalid reader list size\n");
        return 1;
    }

    buf = malloc(bufSize);
    memset(buf, 0xff, bufSize);

    if ((r = SCardListReadersA(0, NULL, buf, &bufSize)) != SCARD_S_SUCCESS) {
        printf("Failed to get reader list: %08x\n", r);
        return 1;
    }

    if (buf[bufSize - 1]) {
        printf("Missing zero terminator in reader list\n");
        return 1;
    }

    if (!buf[0]) {
        printf("No readers found\n");
        return 0;
    }

    printf("Reader list:\n");
    for (p = buf; *p != '\0'; p += strlen(p) + 1)
        printf("%s\n", p);

    return 0;
}
Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,716 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,431 questions
Windows 10 Security
Windows 10 Security
Windows 10: A Microsoft operating system that runs on personal computers and tablets.Security: The precautions taken to guard against crime, attack, sabotage, espionage, or another threat.
2,769 questions
0 comments No comments
{count} votes

Accepted answer
  1. David Lowndes 4,711 Reputation points
    2020-12-21T10:43:37.42+00:00

    Yes, it's still the same for me running the latest Windows 10 insider version.
    The Unicode version returns the null while the ANSI version doesn't.
    You should report it on the feedback hole, but given its history I suspect it won't change and all you can do is work around it.


0 additional answers

Sort by: Most helpful