views:

352

answers:

1

Why might SCardEstablishContext hang, never to return, when called from a service?

I have code that works fine on lots of Windows installations. It accesses a Cherry keyboard's Smart Card reader (6x44) to read data on a smart card. It works fine on most PCs it has been tried on. However, on some PCs, running in Spain with Spanish Windows, the SCardEstablishContext function never returns. I cannot work out why this might be. I have logging either side of it, but the log entry after it does not appear. I cannot then shut it down (the worker thread is getting stuck), and have to kill it.

Exactly the same thread code works fine if run from an application, and not a service. Giving the service login settings of a user instead of system makes no difference. I've installed Spanish XP on a machine here, but it works just fine. The far end has the same Winscard.dll version as I have here (both at XP SP3 status). No errors are shown in the event log.

How might I work out what is going wrong, and what might be fixing it? (Delphi code below)

// based on code by Norbert Huettisch
function TPCSCConnector.Init: boolean;
var
    RetVar: LongInt;
    ReaderList: string;
    ReaderListSize: integer;
    v: array[0..MAXIMUM_SMARTCARD_READERS] of string;
    i: integer;
begin
    Result := false;
    FNumReaders := 0;
{$IFDEF MJ_ONLY}
    LogReport(leInformation, 'About to call SCardEstablishContext');
{$ENDIF}
    RetVar := SCardEstablishContext(SCARD_SCOPE_USER, nil, nil, @FContext);
{$IFDEF MJ_ONLY}
    // never gets to report this (and logging known good etc)
    LogReport(leInformation, 'SCardEstablishContext result = ' + IntToStr(RetVar));
{$ENDIF}
    if RetVar = SCARD_S_SUCCESS then
    begin
+2  A: 

There may be different reasons why the API function appears to hang, like a deadlock, or an invisible message box or dialog waiting for user input. You should try to get a stacktrace using WinDbg.

You should also make sure that you are trying to reproduce the bug in the same environment. Important points might be whether Fast User Switching is active and whether other users are logged on, also that there are the same device drivers and services running.

mghie
I'll try the WinDbg option - the stack trace would be a good clue. Fast user switching is not enabled I don't think, and certainly there is only one user active. I rebooted yesterday and it starts automatically so was hung before any user could start.
mj2008
WinDbg worked for finding the solution, if not the real answer. I'd updated to XP SP3, but WinDbg showed that it was loading a winscard.dll from the app directory, which was probably old. I deleted the DLL, and ran it and all worked fine again. Thanks!
mj2008