Hungry Mind , Blog about everything in IT - C#, Java, C++, .NET, Windows, WinAPI, ...

Показаны сообщения с ярлыком problem. Показать все сообщения
Показаны сообщения с ярлыком problem. Показать все сообщения

How to compute IP and TCP checksum

Whenever I need to code something, the very first thing I do is google for a ready to use solution. Some time ago I had to calculate IP and TCP checksums. Every peace of code I googled was unreadable junk. I wonder is it really hard to write good looking readable code, so you can just copy and paste it?!

#pragma pack(push, 1)
 
struct IPV4_HDR
{
    uint8_t ihl : 4;
    uint8_t version : 4;
    uint8_t tos;
    uint16_t total_length;
    uint16_t identification;
 
    uint16_t fragment_offset : 13;
 
    uint16_t more_fragment : 1;
    uint16_t dont_fragment : 1;
    uint16_t reserved_zero : 1;
 
    uint8_t ttl;
    uint8_t proto;
    uint16_t header_checksum;
    uint32_t src_ip;
    uint32_t dst_ip;
};
 
struct TCP_HDR
{
    uint16_t src_port;
    uint16_t dst_port;
    uint32_t seqn;
    uint32_t ackn;
 
    uint8_t ns : 1;
    uint8_t reserved : 3;
    uint8_t data_offset : 4;
 
    uint8_t fin : 1;
    uint8_t syn : 1;
    uint8_t rst : 1;
    uint8_t psh : 1;
    uint8_t ack : 1;
    uint8_t urg : 1;
 
    uint8_t ecn : 1;
    uint8_t cwr : 1;
 
    uint16_t window;
    uint16_t checksum;
    uint16_t urgent_pointer;
};
 
#pragma pack(pop)
 
uint16_t compute_checksum(uint16_t const *data, size_t count)
{
    uint32_t sum = 0;
    while (count > 1) {
        sum += *data++;
        count -= sizeof(uint16_t);
    }
    if (count > 0) sum += ((*data) & htons(0xFF00));
    while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16);
    sum = ~sum;
    return static_cast<uint16_t>(sum);
}
 
uint16_t compute_ip_checksum(IPV4_HDR *ip)
{
    ip->header_checksum = 0U;
    return (ip->header_checksum = compute_checksum(reinterpret_cast<uint16_t const *>(ip), ip->ihl << 2));
}
 
uint16_t compute_tcp_checksum(IPV4_HDR const *ip, uint16_t *payload)
{
    uint32_t sum = 0;
    uint16_t tcp_len = ntohs(ip->total_length) - (ip->ihl << 2);
    auto const tcp = reinterpret_cast<TCP_HDR *>(payload);
    sum += (ip->src_ip >> 16) & 0xFFFF;
    sum += (ip->src_ip) & 0xFFFF;
    sum += (ip->dst_ip >> 16) & 0xFFFF;
    sum += (ip->dst_ip) & 0xFFFF;
    sum += htons(IPPROTO_TCP);
    sum += htons(tcp_len);
 
    tcp->checksum = 0;
    while (tcp_len > 1) {
        sum += *payload++;
        tcp_len -= sizeof(uint16_t);
    }
    if (tcp_len > 0) sum += ((*payload) & htons(0xFF00));
    while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
    sum = ~sum;
    return (tcp->checksum = static_cast<uint16_t>(sum));
}

__await is still broken in Visual Studio 2015 RTM

Connect issue

The following simple code does not work:

#include "stdafx.h"
#include <experimental\generator>
#include <future>

using namespace std;
using namespace std::experimental;

future<int> get_int()
{
    return async([] { return 0; });
}

future<int> wait_int()
{
    return __await get_int();
}


int main()
{
    auto const i = wait_int().get();
    return 0;
}

App hits int 3 instruction (XXX.exe has triggered a breakpoint) and then hangs forever waiting for suspended coroutine to finish. Bravo! My investigation shows that compiler generates invalid instructions within XXX.exe!wait_int$_ResumeCoro$2() function:

00007FF6166FB0F0  mov         qword ptr [rsp+8],rcx  
00007FF6166FB0F5  push        rbp  
00007FF6166FB0F6  sub         rsp,30h  
00007FF6166FB0FA  mov         qword ptr [rsp+20h],0FFFFFFFFFFFFFFFEh  
00007FF6166FB103  mov         rbp,qword ptr [$S2]  
00007FF6166FB108  mov         eax,dword ptr [rbp+20h]  
00007FF6166FB10B  mov         dword ptr [rbp+78h],eax  
00007FF6166FB10E  cmp         dword ptr [rbp+78h],5  

rbp has the address of coroutine frame, frame has two consequent 64-bit values - address of resume method and some internal state flag, which is set to 2 initially. dword ptr [rbp+20h] - this instruction obtains the flag, but the offset is completely wrong, it must be dword ptr [rbp+8h]. So all cases of state flag switch are bypassed. Default case makes the assert hit. Boom.

UPD: It doesn't support Debug Information Format == Program Database for Edit And Continue (/Zl). With this setting set to something else the code is generated properly: mov eax, [rbp+8].

Establishing an RDP connection with a Windows 8.1 client from Mac OS X

How to detect VHD attached volume

In order to detect a volume is VHD attached, you can query its device descriptor using DeviceIoControl:

#include <windows.h>
#include <iostream>
 
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
   if (argc < 2) {
      cerr << "Usage: FsUtil.exe file" << endl;
      return -1;
   }
   auto const h = ::CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
   if (h == INVALID_HANDLE_VALUE) {
      cerr << "Unable to open " << argv[1] << endl;
      return -2;
   }
 
   STORAGE_PROPERTY_QUERY spq = { StorageDeviceProperty, PropertyStandardQuery };
 
   unsigned char b[1024];
   auto const btyped = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR *>(&b[0]);
 
   DWORD br;
   if (::DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), &b[0], sizeof(b), &br, nullptr) == FALSE) {
      cerr << "DeviceIoControl failed with " << ::GetLastError() << endl;
      return -3;
   }
 
   auto const vendor = reinterpret_cast<LPCSTR>(b + btyped->VendorIdOffset);
   auto const product = reinterpret_cast<LPCSTR>(b + btyped->ProductIdOffset);
 
   cout << "Bus type: " << btyped->BusType << endl
        << "Vendor: " << vendor << endl
        << "Product: " << product << endl;
 
   return 0;
}

BusType would be BusTypeFileBackedVirtual, vendor - Msft, product - Virtual Disk.

WinDbg: find probable CONTEXT records

This script finds and pretty prints all probable CONTEXT struct instances throughout x64 process address space:

0:000> .foreach ( CxrPtr { s -[w1]b 0x00000000000000000 L?FFFFFFFFFFFFFFFF 2b 00 2b 00 53 00 2b 00 } ) { .cxr ${CxrPtr}-@@(#FIELD_OFFSET(ntdll!_CONTEXT, SegDs)) }
rax=000000000f2907e0 rbx=00000001420b70f0 rcx=0000000010c3d130
rdx=0000000010c3cad8 rsi=00000001420b7d08 rdi=000000013fda9cb0
rip=000007fe99e71cc9 rsp=0000000010c3e850 rbp=0000000010c3e870
 r8=0000000010c2a000  r9=000000000f2907e0 r10=000007fef6bd6738
r11=0000000000000001 r12=0000000140e4fb00 r13=000000033fcc69f8
r14=0000000010c3f098 r15=0000000000000004
iopl=0         nv up ei pl nz na pe nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
000007fe`99e71cc9 8a4510          mov     al,byte ptr [rbp+10h] ss:00000000`10c3e880=00

...

rax=000000004685a478 rbx=0000000241d02878 rcx=0000000000000000
rdx=0000000000000000 rsi=0000000241c9d708 rdi=0000000241d02838
rip=000007fe9d9d39f4 rsp=000000004685a450 rbp=000000004685a4a0
 r8=0000000441b49850  r9=0000000000000000 r10=000007fe9b1e1ac0
r11=0000000441b49870 r12=0000000241c90e88 r13=000007fe9b299448
r14=00000001406cc858 r15=0000000441b24af0
iopl=0         nv up ei pl nz na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
000007fe`9d9d39f4 803900          cmp     byte ptr [rcx],0 ds:00000000`00000000=??

Then you would normally use RIP and RSP registers to find relevant code and thread context:

0:000> !IP2MD 000007fe99e71cc9 
MethodDesc:   000007fe98e229c0
Method Name:  Replay.Core.Implementation.AutomaticUpdate.PatchDetector.IsPatched(System.Diagnostics.FileVersionInfo)
Class:        000007fe98dec4a0
MethodTable:  000007fe98e22a70
mdToken:      0000000006000463
Module:       000007fe988acb20
IsJitted:     yes
CodeAddr:     000007fe99e71c50
Transparency: Critical

0:000> !IP2MD 000007fefde1940d  
Failed to request MethodData, not in JIT code range
0:000> ln 000007fefde1940d
(000007fe`fde193d0)   KERNELBASE!RaiseException+0x39   |  (000007fe`fde19420)   KERNELBASE!CreateMutexExW

0:000> !address 000000004685a450

                                     
Mapping file section regions...
Mapping module regions...
Mapping PEB regions...
Mapping TEB and stack regions...
Mapping heap regions...
Mapping page heap regions...
Mapping other regions...
Mapping stack trace database regions...
Mapping activation context regions...


Usage:                  Stack
Base Address:           00000000`46852000
End Address:            00000000`46860000
Region Size:            00000000`0000e000
State:                  00001000 MEM_COMMIT
Protect:                00000004 PAGE_READWRITE
Type:                   00020000 MEM_PRIVATE
Allocation Base:        00000000`46460000
Allocation Protect:     00000004 PAGE_READWRITE
More info:              ~88k


0:000> ~88k
Child-SP          RetAddr           Call Site
00000000`4685ed48 000007fe`fde110dc ntdll!NtWaitForSingleObject+0xa
00000000`4685ed50 000007fe`f7e89622 KERNELBASE!WaitForSingleObjectEx+0x79
00000000`4685edf0 000007fe`f7e89841 clr!CLRSemaphore::Wait+0x8a
00000000`4685eeb0 000007fe`f7e897ec clr!ThreadpoolMgr::UnfairSemaphore::Wait+0x134
00000000`4685eef0 000007fe`f7d733de clr!ThreadpoolMgr::WorkerThreadStart+0x204
00000000`4685efb0 00000000`77a959ed clr!Thread::intermediateThreadProc+0x7d
00000000`4685fb70 00000000`77ccc541 kernel32!BaseThreadInitThunk+0xd
00000000`4685fba0 00000000`00000000 ntdll!RtlUserThreadStart+0x1d

KiPageFault into BSOD when stepping over

I've been struggling long time with weird bug check during kernel driver debugging. Stack trace would look like this:

1: kd> k
Child-SP          RetAddr           Call Site
ffffd000`20463d78 fffff800`1aa610ea nt!DbgBreakPointWithStatus
ffffd000`20463d80 fffff800`1aa609fb nt!KiBugCheckDebugBreak+0x12
ffffd000`20463de0 fffff800`1a9d8da4 nt!KeBugCheck2+0x8ab
ffffd000`204644f0 fffff800`1aa00b1f nt!KeBugCheckEx+0x104
ffffd000`20464530 fffff800`1a8c75ad nt! ?? ::FNODOBFM::`string'+0x1797f
ffffd000`204645d0 fffff800`1a9e2f2f nt!MmAccessFault+0x7ed
ffffd000`20464710 fffff800`002b92e3 nt!KiPageFault+0x12f
ffffd000`204648a0 fffff800`0117b41f Wdf01000!imp_WdfFdoInitQueryProperty+0x28
ffffd000`204648f0 fffff800`0118117f MyVolFlt!WdfFdoInitQueryProperty+0x5f [c:\program files (x86)\windows kits\8.1\include\wdf\kmdf\1.13\wdffdo.h @ 217]
ffffd000`20464940 fffff800`0027f55b MyVolFlt!MyVolFltEvtDeviceAdd+0x9f [c:\development\projects\kernelmode\myvolflt\driver.c @ 116]
ffffd000`20464bd0 fffff800`1a9539d9 Wdf01000!FxDriver::AddDevice+0xab
ffffd000`20464ff0 fffff800`1ace18ab nt!PpvUtilCallAddDevice+0x35
ffffd000`20465030 fffff800`1acdff9e nt!PnpCallAddDevice+0x63
ffffd000`204650b0 fffff800`1acdf2db nt!PipCallDriverAddDevice+0x6e2
ffffd000`20465250 fffff800`1ad14b89 nt!PipProcessDevNodeTree+0x1cf
ffffd000`204654d0 fffff800`1a97d0b8 nt!PiProcessReenumeration+0x91
ffffd000`20465520 fffff800`1a97cf2e nt!PnpDeviceActionWorker+0x168
ffffd000`204655d0 fffff800`1af93382 nt!PnpRequestDeviceAction+0x1da
ffffd000`20465610 fffff800`1af89022 nt!IopInitializeBootDrivers+0x83e
ffffd000`204658b0 fffff800`1af7794d nt!IoInitSystem+0x91e
ffffd000`204659d0 fffff800`1ad7bd09 nt!Phase1InitializationDiscard+0xe61
ffffd000`20465bd0 fffff800`1a9182e4 nt!Phase1Initialization+0x9
ffffd000`20465c00 fffff800`1a9df2c6 nt!PspSystemThreadStartup+0x58
ffffd000`20465c60 00000000`00000000 nt!KiStartSystemThread+0x16

Bug Check description:

   1: kd> !analyze -v
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************
PAGE_FAULT_IN_NONPAGED_AREA (50)
Invalid system memory was referenced.  This cannot be protected by try-except,
it must be protected by a Probe.  Typically the address is just plain bad or it
is pointing at freed memory.
Arguments:
Arg1: ffffe00020464c10, memory referenced.
...

Now lets see what is this address:

1: kd> !pool ffffe00020464c10
Pool page ffffe00020464c10 region is Nonpaged pool
ffffe00020464000 is not a valid large pool allocation, checking large session pool...
Unable to read large session pool table (Session data is not present in mini and kernel-only dumps)
ffffe00020464000 is not valid pool. Checking for freed (or corrupt) pool
Address ffffe00020464000 could not be read. It may be a freed, invalid or paged out page
1: kd> ? poi(DeviceInit)
Evaluate expression: -35183830610928 = ffffe000`20464c10

Wow, faulting memory references is DeviceInit actually! And it is located on stack (because of KMDF model).

Sure IRQL is at PASSIVE level:

1: kd> !irql
Debugger saved IRQL for processor 0x1 -- 0 (LOW_LEVEL)

The funniest thing so far is that if I set bp after the call to WdfFdoInitQueryProperty - it would run smoothly. So there is something wrong with the debugger interacting OS kernel.

Now I finally managed to figure out what was wrong. I would normally set my bp during initial break-in sequence:

Connected to Windows 8 9600 x64 target at (Thu Jan 16 00:54:33.435 2014 (UTC + 2:00)), ptr64 TRUE
Kernel Debugger connection established.
************* Symbol Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       cache*C:\Development\Tools\Symbols
Deferred                                       srv*http://msdl.microsoft.com/download/symbols
Symbol search path is: cache*C:\Development\Tools\Symbols;srv*http://msdl.microsoft.com/download/symbols
Executable search path is: 
Windows 8 Kernel Version 9600 MP (1 procs) Free x64
Built by: 9600.16452.amd64fre.winblue_gdr.131030-1505
Machine Name:
Kernel base = 0xfffff800`5547e000 PsLoadedModuleList = 0xfffff800`55742990
System Uptime: 0 days 0:00:00.102
nt!DebugService2+0x5:
fffff800`555d28e5 cc              int     3
kd> bp MyVolFltEvtDeviceAdd
kd> g

And here what happens after:

Unload module \SystemRoot\system32\mcupdate_GenuineIntel.dll at fffff800`1b200000
Unload module \SystemRoot\System32\drivers\werkernel.sys at fffff800`19ed5000
...
Unload module \SystemRoot\system32\DRIVERS\MyVolFlt.sys at fffff800`1b9ed000
nt!DebugService2+0x5:
fffff800`555d28e5 cc              int     3
kd> k
 # Child-SP          RetAddr           Call Site
00 fffff800`573991a8 fffff800`55544361 nt!DebugService2+0x5
01 fffff800`573991b0 fffff800`555442ff nt!DbgLoadImageSymbols+0x45
02 fffff800`57399200 fffff800`55b76fc4 nt!DbgLoadImageSymbolsUnicode+0x2b
03 fffff800`57399240 fffff800`55b7684b nt!MiReloadBootLoadedDrivers+0x300
04 fffff800`573993c0 fffff800`55b6c091 nt!MiInitializeDriverImages+0x163
05 fffff800`57399470 fffff800`55b67299 nt!MiInitSystem+0x3d9
06 fffff800`57399500 fffff800`557e84ea nt!InitBootProcessor+0x301
07 fffff800`57399740 fffff800`557de1a3 nt!KiInitializeKernel+0x5a2
08 fffff800`57399ad0 00000000`00000000 nt!KiSystemStartup+0x193

It is unloading boot time drivers! And reloading with different start addresses! So when I set my breakpoint at MyVolFltEvtDeviceAdd, WinDbg would insert int 3 instruction and during module relocation that instruction is copied as is. So my breakpoint actually hits, despite code relocation. But this is where the Windows and debugger fall apart - they don't know about this breakpoint.

In order to issue correct breakpoint address, you must break on module load:

kd> sxe ld MyVolFlt
kd> sxe ud MyVolFlt
kd> sx
  ct - Create thread - ignore
  et - Exit thread - ignore
 cpr - Create process - ignore
 epr - Exit process - ignore
  ld - Load module - break
       (only break for myvolflt)
  ud - Unload module - break
       (only break for MyVolFlt)

And issue bp command after kernel reloads boot loaded drivers.

ReaderWriterLockSlim fails on dual-socket environments

This is yet another story of orphaned ReaderWriterLockSlim.

Another dump, the same problem - ReaderWriterLockSlim object state is corrupted:

0:173> !do 0x0000000001c679f8
Name:        System.Threading.ReaderWriterLockSlim
MethodTable: 000007f87ec7c1d8
EEClass:     000007f87e999448
Size:        96(0x60) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007f880dbcbf0  4000755       50       System.Boolean  1 instance                1 fIsReentrant
000007f880dbe0c8  4000756       30         System.Int32  1 instance                0 myLock
000007f880db2308  4000757       34        System.UInt32  1 instance                1 numWriteWaiters
000007f880db2308  4000758       38        System.UInt32  1 instance               28 numReadWaiters
000007f880db2308  4000759       3c        System.UInt32  1 instance                0 numWriteUpgradeWaiters
000007f880db2308  400075a       40        System.UInt32  1 instance                0 numUpgradeWaiters
000007f880dbcbf0  400075b       51       System.Boolean  1 instance                0 fNoWaiters
000007f880dbe0c8  400075c       44         System.Int32  1 instance               -1 upgradeLockOwnerId
000007f880dbe0c8  400075d       48         System.Int32  1 instance               -1 writeLockOwnerId
000007f880db9138  400075e        8 ...g.EventWaitHandle  0 instance 000000000381eb38 writeEvent
000007f880db9138  400075f       10 ...g.EventWaitHandle  0 instance 00000000035a32e0 readEvent
000007f880db9138  4000760       18 ...g.EventWaitHandle  0 instance 0000000000000000 upgradeEvent
000007f880db9138  4000761       20 ...g.EventWaitHandle  0 instance 0000000000000000 waitUpgradeEvent
000007f880dd0398  4000763       28         System.Int64  1 instance 9 lockID
000007f880dbcbf0  4000765       52       System.Boolean  1 instance                0 fUpgradeThreadHoldingRead
000007f880db2308  4000766       4c        System.UInt32  1 instance       1073741824 owners
000007f880dbcbf0  4000767       53       System.Boolean  1 instance                0 fDisposed
000007f880dd0398  4000762      408         System.Int64  1   static 14118 s_nextLockID
000007f87ec99a20  4000764        8 ...ReaderWriterCount  0 TLstatic  t_rwc
0:173> .formats 0n1073741824 
Evaluate expression:
  Hex:     00000000`40000000

EnterReadLock, EnterWriteLock and other Enter operations waiting for an event which never goes off. Deadlock.

I must say that I checked possibilities of thread aborts in this code and found no signs of such scenarios happening. This made me desperately searching for another root cause of the problem.

So started searching ReaderWriterLockSlim.cs file for potential problems. I immediately became suspicious when I realyzed there is lack of synchronization when, for example, TryEnterUpgradeableReadLockCore method modified one of object fields:

uint owners;
...
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{ 
...
       owners++;
}

Fields are not declared volatile, nor are they modified via interlocked operations. The only exception is the myLock field, which is used as a spin lock ang modified via Interlocked.CompareExchange:

[MethodImpl(MethodImplOptions.AggressiveInlining)] 
private void EnterMyLock()
{
   if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0)
      EnterMyLockSpin(); 
}

Note, however, spin lock release method doesn't use Interlocked operation:

private void ExitMyLock()
{ 
   Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
   myLock = 0; 
} 

This looks to be a mistake, possibly the root cause on one of root causes.

OK, lets go back to the problem - ReaderWriterLockSlim gets locked forever on 24-core dual socket Intel hardware. Threads are not aborted, the code is perfect. So what the hell is going on?

Well, the problem looks to be bad software (ReaderWriterLockSlim) on expensive hardware. Dell PowerEdge R720 has two psysical CPUs - 2x Intel Xeon E5-2620, 1200 MHz (12 x 100), 6 cores and 12 threads each. 24 logical cores total. And the problem is experienced only on such configurations.

I made a program that creates 24 (= Environment.ProcessorCount) threads with highest priority acquiring and releasing the lock in a tight loop:

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
namespace RWLSTest
{
   internal class Program
   {
      private static readonly ReaderWriterLockSlim slim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
      private static readonly List<object> objects = new List<object>();
      private static readonly Int32 processorCount = Environment.ProcessorCount;
      private static Int32 threadsCount;
      private static Int64 reads;
      private static Int64 writes;
      private static volatile Object[] threads = new Object[processorCount];
      private static Action loopAction;
      static Program()
      {
         // Let it JIT those methods
         using (var temp = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion)) {
            Thread.Yield();
            temp.EnterReadLock();
            temp.ExitReadLock();
         }
         var thread = new Thread(() =>
         {
            try {
               Thread.Sleep(Timeout.Infinite);
            }
            catch {
               return;
            }
            throw new InvalidOperationException();
         });
         thread.Start();
         try {
            thread.Abort();
         }
         catch (Exception e) {
            Console.WriteLine(e.Message);
         }
      }
      private static void LoopWithEmptryTryBlocks()
      {
         var random = new Random(Environment.TickCount);
         for (;;) {
            if (random.Next(processorCount) <= (processorCount / 4)) {
               Interlocked.Increment(ref writes);
               try {}
               finally {
                  slim.EnterWriteLock();
               }
               try {
                  ExclusiveLoop(random);
               }
               finally {
                  slim.ExitWriteLock();
               }
            }
            else {
               Interlocked.Increment(ref reads);
               try {}
               finally {
                  slim.EnterReadLock();
               }
               try {
                  SharedLoop(random);
               }
               finally {
                  slim.ExitReadLock();
               }
            }
         }
      }
      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      private static void SharedLoop(Random random)
      {
         foreach (var o in objects) {
            var i = (Int32)o;
            if ((i % processorCount) == (random.Next() % processorCount) && random.Next(37) == 3) {
               break;
            }
         }
      }
      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      private static void ExclusiveLoop(Random random)
      {
         if (objects.Count < 10240) {
            for (var i = 0; i < 19; ++i) {
               if (random.Next(13) == 7) {
                  objects.Add(random.Next());
               }
            }
         }
         for (var i = 0; i < 13; ++i) {
            if (objects.Count > 0 && random.Next(19) == 13) {
               objects.Remove(random.Next() % objects.Count);
            }
         }
      }
      private static void Loop()
      {
         var random = new Random(Environment.TickCount);
         for (;;) {
            if (random.Next(processorCount) <= (processorCount / 4)) {
               slim.EnterWriteLock();
               try {
                  ExclusiveLoop(random);
               }
               finally {
                  slim.ExitWriteLock();
               }
            }
            else {
               slim.EnterReadLock();
               try {
                  SharedLoop(random);
               }
               finally {
                  slim.ExitReadLock();
               }
            }
         }
      }
      private static void StartOneThread(Object state)
      {
         var thread = new Thread(() =>
         {
            try {
               Interlocked.Increment(ref threadsCount);
               loopAction();
            }
            catch (ThreadAbortException) {}
            finally {
               Interlocked.Decrement(ref threadsCount);
               ThreadPool.UnsafeQueueUserWorkItem(StartOneThread, state);
            }
         }) { Priority = ThreadPriority.Highest };
         thread.Start();
         Thread.VolatileWrite(ref threads[(Int32)state], thread);
      }
      private static void Main(string[] args)
      {
         var random = new Random(Environment.TickCount);
         var abortCycle = 0;
         if (args.Length > 0) {
            abortCycle = Int32.Parse(args[0]);
            loopAction = LoopWithEmptryTryBlocks;
         }
         else {
            loopAction = Loop;
         }
         for (var i = 0; i < processorCount; ++i) {
            StartOneThread(i);
         }
         for (var i = 0U;; ++i) {
            Thread.Sleep(1);
            if (abortCycle > 0 && i % abortCycle == 0) {
               var ti = random.Next(111) % processorCount;
               var thread = (Thread)Thread.VolatileRead(ref threads[ti]);
               if (thread != null) {
                  Console.WriteLine("Aborting thread #" + ti);
                  try {
                     thread.Abort();
                  }
                  catch (Exception e) {
                     Console.WriteLine(e.Message);
                  }
               }
            }
         }
      }
   }
}

I ran it several times and after about 1 hour all threads ended up waiting for lock event to fire. Voila! Have a look at the state of ReaderWriterLockSlim object:

0:000> !do 000000b343bd2860 
Name:        System.Threading.ReaderWriterLockSlim
MethodTable: 000007fbf887c1a8
EEClass:     000007fbf8599448
Size:        96(0x60) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007fbfe6ac7b8  4000755       50       System.Boolean  1 instance                1 fIsReentrant
000007fbfe6adc90  4000756       30         System.Int32  1 instance                0 myLock
000007fbfe6a1ed0  4000757       34        System.UInt32  1 instance                1 numWriteWaiters
000007fbfe6a1ed0  4000758       38        System.UInt32  1 instance               23 numReadWaiters
000007fbfe6a1ed0  4000759       3c        System.UInt32  1 instance                0 numWriteUpgradeWaiters
000007fbfe6a1ed0  400075a       40        System.UInt32  1 instance                0 numUpgradeWaiters
000007fbfe6ac7b8  400075b       51       System.Boolean  1 instance                0 fNoWaiters
000007fbfe6adc90  400075c       44         System.Int32  1 instance               -1 upgradeLockOwnerId
000007fbfe6adc90  400075d       48         System.Int32  1 instance               -1 writeLockOwnerId
000007fbfe6a8d00  400075e        8 ...g.EventWaitHandle  0 instance 000000b343beb448 writeEvent
000007fbfe6a8d00  400075f       10 ...g.EventWaitHandle  0 instance 000000b343be2fd0 readEvent
000007fbfe6a8d00  4000760       18 ...g.EventWaitHandle  0 instance 0000000000000000 upgradeEvent
000007fbfe6a8d00  4000761       20 ...g.EventWaitHandle  0 instance 0000000000000000 waitUpgradeEvent
000007fbfe6bff60  4000763       28         System.Int64  1 instance 1 lockID
000007fbfe6ac7b8  4000765       52       System.Boolean  1 instance                0 fUpgradeThreadHoldingRead
000007fbfe6a1ed0  4000766       4c        System.UInt32  1 instance       1073741824 owners
000007fbfe6ac7b8  4000767       53       System.Boolean  1 instance                0 fDisposed
000007fbfe6bff60  4000762      408         System.Int64  1   static 2 s_nextLockID
000007fbf88999f0  4000764        8 ...ReaderWriterCount  0 TLstatic  t_rwc

There are 23 reader waiters, 1 writer waiter and owners field is 0x40000000 once again. All of 24 threads look like the following:

0:000> ~22e !CLRStack
OS Thread Id: 0xf28 (22)
        Child SP               IP Call Site
000000b361a1df78 000007fc137b315b [HelperMethodFrame_1OBJ: 000000b361a1df78] System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
000000b361a1e0a0 000007fbfe5195c4 System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)
000000b361a1e0e0 000007fbf8af4c25 System.Threading.ReaderWriterLockSlim.WaitOnEvent(System.Threading.EventWaitHandle, UInt32 ByRef, TimeoutTracker)
000000b361a1e150 000007fbf8dd4c48 System.Threading.ReaderWriterLockSlim.TryEnterReadLockCore(TimeoutTracker)
000000b361a1e1b0 000007fbf8804d4a System.Threading.ReaderWriterLockSlim.TryEnterReadLock(TimeoutTracker)
000000b361a1e200 000007fbf8af55ad System.Threading.ReaderWriterLockSlim.TryEnterReadLock(Int32)
000000b361a1e250 000007fba0010a45 RWLSTest.Program.Loop()
000000b361a1e2c0 000007fba00106f7 RWLSTest.Program+<>c__DisplayClass4.<startonethread>b__3()
000000b361a1e330 000007fbfe4ff8a5 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
000000b361a1e490 000007fbfe4ff609 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
000000b361a1e4c0 000007fbfe4ff5c7 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
000000b361a1e510 000007fbfe512d21 System.Threading.ThreadHelper.ThreadStart()
000000b361a1e828 000007fbff6bf713 [GCFrame: 000000b361a1e828] 
000000b361a1eb58 000007fbff6bf713 [DebuggerU2MCatchHandlerFrame: 000000b361a1eb58] 

They all WaitOnEvent, but who and when will fire the event? This never happens. Deadlock.

Now lets get back to ExitMyLock. ReaderWriterLockSlim contains many fields with at least 88 bytes storage space required (without extra aligning, if needed). Modern Intel CPUs have cache lines of 64 bytes which is too small to entirely hold ReaderWriterLockSlim object instance. So each one requires at least two cache lines to hold its data. Since the distance between myLock and owners fields is more than 64 bytes (both x86 and x64), releasing myLock without a memory barrier (or interlocked instruction) causes only a portion of object's storage invalidated on demand between CPU cores and/or CPUs. Invalidation is forced by EnterMyLock's interlocked instruction. But only 64 bytes of aligned memory where myLock resides. Other cache line's changes might not be visible at that point. So the core acquiring the lock may see inconsistent object state.

Very important note: ReaderWriterLockSlim.cs is a part of 4.5Update1 reference source. Vanilla .NET 4.5 and probably several updates following it has this code, for example 4.0.30319.17929, 4.0.30319.18408. Recent versions, for example 4.0.30319.33440, has fixed this:

private void ExitMyLock()
{ 
   Volatile.Write(ref myLock, 0);
}

Volatile write inserts explicit memory barriers and makes any changes visible to other cores and CPUs.

Conclusion: do not use ReaderWriterLockSlim class without .NET Framework updated to at least 4.0.30319.33440. Its will eventually fail, at least on dual-socket Intel system.

Windows 8.1 and Windows Server 2012 R2 have this issue fixed. Windows Server 2012 (nor R2) seems to stuck with buggy implementation of ReaderWriterLockSlim class. After installing all available updates, ExitMyLock looks the same (no volatile write operation).

Cruel DateTime vs serialization

Недавно столкнулся с проблемой сериализации DateTime. protobuf-net, как и BinaryFormatter не сохраняют тип даты, перечисление DateTimeKind. В результате после чтения из архива тип даты становится Unspecified. Вот выдержка из исходного кода структуры DateTime:

// This value type represents a date and time.  Every DateTime
// object has a private field (Ticks) of type Int64 that stores the
// date and time as the number of 100 nanosecond intervals since
// 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar. 
//
// Starting from V2.0, DateTime also stored some context about its time 
// zone in the form of a 3-state value representing Unspecified, Utc or 
// Local. This is stored in the two top bits of the 64-bit numeric value
// with the remainder of the bits storing the tick count. This information 
// is only used during time zone conversions and is not part of the
// identity of the DateTime. Thus, operations like Compare and Equals
// ignore this state. This is to stay compatible with earlier behavior
// and performance characteristics and to avoid forcing  people into dealing 
// with the effects of daylight savings. Note, that this has little effect
// on how the DateTime works except in a context where its specific time 
// zone is needed, such as during conversions and some parsing and formatting 
// cases.
// 
// There is also 4th state stored that is a special type of Local value that
// is used to avoid data loss when round-tripping between local and UTC time.
// See below for more information on this 4th state, although it is
// effectively hidden from most users, who just see the 3-state DateTimeKind 
// enumeration.
// 
// For compatability, DateTime does not serialize the Kind data when used in 
// binary serialization.
// 
// For a description of various calendar issues, look at
//
// Calendar Studies web site, at
// http://serendipity.nofadz.com/hermetic/cal_stud.htm. 
//
// 
[StructLayout(LayoutKind.Auto)] 
[Serializable]
public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable,IEquatable { 

Как видно из описания, дата представляет собой число типа Int64 в котором хранится количество 100нс интервалов от начала времен - 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar. А вот до какой точки - здесь уже интересней. В случае DateTimeKind.Utc - до Гринвича, DateTimeKind.Local - до времени в локальной для операционной системы\программы\потока зоне. И последнее значение - DateTimeKind.Unspecified, до куда - неизвестно.

На что влияет тип даты? В первую очередь на методы ToLocalTime и ToUniversalTime, потом уже и на форматирующие методы. Самое неприятное происходит при вызове этих двух методов для дат с типом DateTimeKind.Unspecified - ToLocalTime считает, что дата имеет тип DateTimeKind.Utc, а ToUniversalTime - что тип DateTimeKind.Local. Логично, правда? В результате если сериализировать DateTime.UtcNow, вычитать его обратно и преобразовать в DateTimeKind.Utc методом ToUniversalTime - получаем сдвиг на временную зону. При этом ToLocalTime вернет правильный результат.

Обойти это недоразумение можно с помощью статического метода DateTime.SpecifyKind.

using System;

namespace CSharpLanguageInv
{
   internal class Program
   {
      private static void Main(string[] args)
      {
         var now = DateTime.UtcNow;
         var unspecified = DateTime.SpecifyKind(now, DateTimeKind.Unspecified);
         var localTime = unspecified.ToLocalTime();
         var universalTime = unspecified.ToUniversalTime();
         Console.WriteLine("Now               = " + now/*.Ticks*/);
         Console.WriteLine("unspecified       = " + unspecified/*.Ticks*/);
         Console.WriteLine("localTime         = " + localTime/*.Ticks*/);
         Console.WriteLine("universalTime     = " + universalTime/*.Ticks*/);
         Console.WriteLine("Now - unspecified = " + (now/*.Ticks*/ - unspecified/*.Ticks*/));
         Console.ReadLine();
      }
   }
}

A story of orphaned ReaderWriterLockSlim

Recently I got 2 dumps of a resource intensive process. The customer complained about hangs in web UI so the application had been killed and restarted numerous times. Quick WinDbg analysis spotted thousands of working threads in the pool:

0:000> !ThreadPool
CPU utilization: 6%
Worker Thread: Total: 6304 Running: 6303 Idle: 1 MaxLimit: 12000 MinLimit: 24
Work Request in Queue: 0
--------------------------------------
Number of Timers: 2
--------------------------------------
Completion Port Thread:Total: 2 Free: 1 MaxFree: 48 CurrentLimit: 1 MaxLimit: 12000 MinLimit: 24

Most of the threads wait for ReaderWriterLockSlim read lock on ManualResetEvent instance:

System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)
System.Threading.ReaderWriterLockSlim.WaitOnEvent(System.Threading.EventWaitHandle, UInt32 ByRef, TimeoutTracker)
System.Threading.ReaderWriterLockSlim.TryEnterReadLockCore(TimeoutTracker)
System.Threading.ReaderWriterLockSlim.TryEnterReadLock(TimeoutTracker)

One thread was waiting for write lock on the same object. No other stacks observed executing while holding the lock, all lock usages seemed proper:

s.EnterXXXLock();
try
{
   // Do the job
}
finally
{
   s.ExitXXXLock();
}

Yet the process is fucked up. What the hell is wrong here? Well, sometimes things get very complicated...

Lets take a look on reader writer lock instance:

0:3444> !do 0x0000000001affe60
Name:        System.Threading.ReaderWriterLockSlim
MethodTable: 000007f87a91c1a8
EEClass:     000007f87a639448
Size:        96(0x60) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007f8802fc7b8  4000755       50       System.Boolean  1 instance                1 fIsReentrant
000007f8802fdc90  4000756       30         System.Int32  1 instance                0 myLock
000007f8802f1ed0  4000757       34        System.UInt32  1 instance                1 numWriteWaiters
000007f8802f1ed0  4000758       38        System.UInt32  1 instance             6293 numReadWaiters
000007f8802f1ed0  4000759       3c        System.UInt32  1 instance                0 numWriteUpgradeWaiters
000007f8802f1ed0  400075a       40        System.UInt32  1 instance                0 numUpgradeWaiters
000007f8802fc7b8  400075b       51       System.Boolean  1 instance                0 fNoWaiters
000007f8802fdc90  400075c       44         System.Int32  1 instance               -1 upgradeLockOwnerId
000007f8802fdc90  400075d       48         System.Int32  1 instance               -1 writeLockOwnerId
000007f8802f8d00  400075e        8 ...g.EventWaitHandle  0 instance 00000000f8e8f9c0 writeEvent
000007f8802f8d00  400075f       10 ...g.EventWaitHandle  0 instance 00000000fa23f040 readEvent
000007f8802f8d00  4000760       18 ...g.EventWaitHandle  0 instance 0000000000000000 upgradeEvent
000007f8802f8d00  4000761       20 ...g.EventWaitHandle  0 instance 0000000000000000 waitUpgradeEvent
000007f88030ff60  4000763       28         System.Int64  1 instance 9 lockID
000007f8802fc7b8  4000765       52       System.Boolean  1 instance                0 fUpgradeThreadHoldingRead
000007f8802f1ed0  4000766       4c        System.UInt32  1 instance       1073741824 owners
000007f8802fc7b8  4000767       53       System.Boolean  1 instance                0 fDisposed
000007f88030ff60  4000762      408         System.Int64  1   static 17381 s_nextLockID
000007f87a9399f0  4000764        8 ...ReaderWriterCount  0 TLstatic  t_rwc
    >> Thread:Value c18:0000000001917410 d18:00000000025a51c8 e54:000000000245d5f0 e90:0000000000000000 e20:00000000f90a6ce8 [>6000 more values]

The most valuable information is the owners field:

0:000> ? 0n1073741824
Evaluate expression: 1073741824 = 00000000`40000000

And heres what it means:

//The uint, that contains info like if the writer lock is held, num of
//readers etc. 
uint owners; 

//Various R/W masks 
//Note:
//The Uint is divided as follows:
//
//Writer-Owned  Waiting-Writers   Waiting Upgraders     Num-REaders 
//    31          30                 29                 28.......0
// 
//Dividing the uint, allows to vastly simplify logic for checking if a 
//reader should go in etc. Setting the writer bit, will automatically
//make the value of the uint much larger than the max num of readers 
//allowed, thus causing the check for max_readers to fail.

private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000; 
private const uint WAITING_UPGRADER = 0x20000000;

So, we are waiting for writers. Hold on, there are no writers! The lock is not held. Conslusion - the lock state is corrupted and could never recover. This is called orphaned lock.

The only thing (I am aware of) might have caused the orphan - asynchronous thread aborts. If a thread is interrupted while taking a lock via [Try]EnterXXXLock method - we might come into described problem since those methods are not atomic. In my case thread aborts are triggered by WCF runtime (or perhaps Http runtime, it doesn't matter).

Heres a simple code to simulate the situation:

using System;
using System.Threading;
 
namespace CLRInv
{
   internal class Program
   {
      private static readonly ReaderWriterLockSlim rwl = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
 
      private static void Main(string[] args)
      {
         rwl.EnterReadLock();
         do {
            rwl.ExitReadLock();
 
            var reader = new Thread(UseLockForRead);
            var writer = new Thread(UseLockForWrite);
            reader.Start();
            writer.Start();
 
            Thread.Sleep(TimeSpan.FromSeconds(2));
            writer.Abort();
            reader.Abort();
 
            reader.Join();
            writer.Join();
         }
         while (rwl.TryEnterReadLock(TimeSpan.FromSeconds(10)));
 
         Console.WriteLine("Gotcha!");
 
         // Forever young
         rwl.EnterWriteLock();
      }
 
      private static void UseLockForRead()
      {
         try {
            for (;;) {
               rwl.EnterReadLock();
               try {
               }
               finally {
                  rwl.ExitReadLock();
               }
            }
         }
         catch (ThreadAbortException) {
         }
      }
 
      private static void UseLockForWrite()
      {
         try {
            for (;;) {
               rwl.EnterWriteLock();
               try {
               }
               finally {
                  rwl.ExitWriteLock();
               }
            }
         }
         catch (ThreadAbortException) {
         }
      }
   }
}

The conclusion is not very optimistic - you can't use slim locks the way you normally use em if your application experiences timeouts and consequent thread aborts. Does this mean slim locks should be banned? Well, no. You just need to ensure special constructions are used to take and release locks.

First of all we need to prevent async aborts while executing [Try]EnterXXXLock. How to do that? You must take the lock inside so called protected region. Here they mention a protected region of code, such as a catch block, finally block, or constrained execution region. This basically means ThreadAbortExeption can't be thrown asynchronously while executing except and finally blocks of a try statement. So our [Try]EnterXXXLock should be wrapped like this:

try {} finally { rw.EnterXXXLock(); }

Weird? No, if you have .NET BCL source code. There are tonns of empty try blocks with excessive comments:

// prevent ThreadAbort while updating state
try { } 
finally
{
...
}

Proper slim lock usage turns out to be the following construction:

var lockIsHeld = false;
try {
   try {
   }
   finally {
      rwl.EnterReadLock();
      lockIsHeld = true;
   }
 
   // Do work here
}
finally {
   if (lockIsHeld) {
      rwl.ExitReadLock();
   }
}

Asynchronous ThreadAbortException is thrown either before lock is held or after lock is held making finally unlock the object if it has been locked.

Two things I havent studied yet - is it possible to observe the following situation:

try {
   // <-- Could it happen here, before finally block is run but after try has opened fault clause region?
   try {
   }
   finally {
      // Lock
   }
 
   // Use resource
}
finally {
   // Unlock
}

Thats why I used that condition flag to ensure the lock is held.

And the second one:

try {
}
finally {
   // Lock
}
try {
   // Use resource
}
finally {
   // Unlock
}

Is this one safe? Probably yes.

The bottom line is know your runtime environment, don't use new features cause they are cool or Mr. Jeff has fresh stuff in his brand new book you love so much. Or hire a professional like me [:-D].

Marshall function call to another thread

Short tutorial on how to make cross apartment (cross thread) COM call without interfaces, proxies, stubs and tlbs.

Each apartment (thread) has its own accesible context object. It can be obtained via CoGetObjectContext API function:

CComPtr<IContext> pContext;   
CComPtr<IContextCallback> pContextCallback;
hr = CoGetObjectContext(IID_PPV_ARGS(&pContext));
hr = CoGetObjectContext(IID_PPV_ARGS(&pContextCallback));

One of interfaces you can get is IContextCallback with only one method - ContextCallback. As you might already guessed, we just need to get IContextCallback in target execution context and invoke ContextCallback method in any other context:

pContextCallback.p->AddRef();
_beginthread(&myThread, 65536, pContextCallback.p);
HANDLE h[] = { CreateEvent(NULL, TRUE, FALSE, NULL) };
DWORD dwIndex;
CoWaitForMultipleHandles(0, INFINITE, _countof(h), h, &dwIndex);
[...]
HRESULT _stdcall contextCall(ComCallData *pParam)
{
   OutputDebugString(_T("contextCall\n"));
   return S_OK;
}

void __cdecl myThread(LPVOID p)
{
   CoInitialize(NULL);

   CComPtr<IContextCallback> pContextCallback;
   pContextCallback.Attach(reinterpret_cast<IContextCallback *>(p));
   
   ComCallData cd = { 0, 0, NULL };
   pContextCallback->ContextCallback(&contextCall, &cd, IID_NULL, 0, NULL);

   CoUninitialize();
}

Here I'm starting a separate thread to make cross context call and using CoWaitForMultipleHandles OLE32 function to trigger message loop to accept cross thread COM calls (regular message loop is surely enough, I'm just reluctant to write one). Here are resulting call stacks:

Main thread:
> Win32ConsoleApplication.exe!contextCall(tagComCallData * pParam) Line 227 C++
  ole32.dll!CRemoteUnknown::DoCallback(struct tagXAptCallback *) Unknown
  rpcrt4.dll!_Invoke@12 () Unknown
  rpcrt4.dll!_NdrStubCall2@16 () Unknown
  ole32.dll!_CStdStubBuffer_Invoke@12 () Unknown
  ole32.dll!SyncStubInvoke(struct tagRPCOLEMESSAGE *,struct _GUID const &,class CIDObject *,void *,struct IRpcChannelBuffer *,struct IRpcStubBuffer *,unsigned long *) Unknown
  ole32.dll!StubInvoke(struct tagRPCOLEMESSAGE *,class CStdIdentity *,struct IRpcStubBuffer *,struct IRpcChannelBuffer *,struct tagIPIDEntry *,unsigned long *) Unknown
  ole32.dll!CCtxComChnl::ContextInvoke(struct tagRPCOLEMESSAGE *,struct IRpcStubBuffer *,struct tagIPIDEntry *,unsigned long *) Unknown
  ole32.dll!MTAInvoke(struct tagRPCOLEMESSAGE *,unsigned long,struct IRpcStubBuffer *,class IInternalChannelBuffer *,struct tagIPIDEntry *,unsigned long *) Unknown
  ole32.dll!STAInvoke(struct tagRPCOLEMESSAGE *,unsigned long,struct IRpcStubBuffer *,class IInternalChannelBuffer *,void *,struct tagIPIDEntry *,unsigned long *) Unknown
  ole32.dll!AppInvoke(class CMessageCall *,class CRpcChannelBuffer *,struct IRpcStubBuffer *,void *,void *,struct tagIPIDEntry *,struct LocalThis *) Unknown
  ole32.dll!ComInvokeWithLockAndIPID(class CMessageCall *,struct tagIPIDEntry *) Unknown
  ole32.dll!ComInvoke(class CMessageCall *) Unknown
  ole32.dll!ThreadDispatch(void *) Unknown
  ole32.dll!ThreadWndProc(struct HWND__ *,unsigned int,unsigned int,long) Unknown
  user32.dll!_InternalCallWinProc@20 () Unknown
  user32.dll!_UserCallWinProcCheckWow@32 () Unknown
  user32.dll!_DispatchMessageWorker@8 () Unknown
  user32.dll!_DispatchMessageW@4 () Unknown
  ole32.dll!CCliModalLoop::PeekRPCAndDDEMessage(void) Unknown
  ole32.dll!CCliModalLoop::FindMessage(unsigned long) Unknown
  ole32.dll!CCliModalLoop::HandleWakeForMsg(void) Unknown
  ole32.dll!CCliModalLoop::BlockFn(void * *,unsigned long,unsigned long *) Unknown
  ole32.dll!_CoWaitForMultipleHandles@20 () Unknown
  Win32ConsoleApplication.exe!wmain(int argc, wchar_t * * argv) Line 284 C++
  Win32ConsoleApplication.exe!__tmainCRTStartup() Line 533 C
  Win32ConsoleApplication.exe!wmainCRTStartup() Line 377 C
  kernel32.dll!@BaseThreadInitThunk@12 () Unknown
  ntdll.dll!___RtlUserThreadStart@8 () Unknown
  ntdll.dll!__RtlUserThreadStart@8 () Unknown
Worker thread:
  ntdll.dll!_NtWaitForMultipleObjects@20 () Unknown
  ntdll.dll!_NtWaitForMultipleObjects@20 () Unknown
  KernelBase.dll!_WaitForMultipleObjectsEx@20 () Unknown
  kernel32.dll!_WaitForMultipleObjectsExImplementation@20 () Unknown
  user32.dll!_RealMsgWaitForMultipleObjectsEx@20 () Unknown
  ole32.dll!CCliModalLoop::BlockFn(void * *,unsigned long,unsigned long *) Unknown
  ole32.dll!ModalLoop(class CMessageCall *) Unknown
  ole32.dll!SwitchSTA(class OXIDEntry *,class CMessageCall * *) Unknown
  ole32.dll!CRpcChannelBuffer::SwitchAptAndDispatchCall(class CMessageCall * *) Unknown
  ole32.dll!CRpcChannelBuffer::SendReceive2(struct tagRPCOLEMESSAGE *,unsigned long *) Unknown
  ole32.dll!CCliModalLoop::SendReceive(struct tagRPCOLEMESSAGE *,unsigned long *,class IInternalChannelBuffer *) Unknown
  ole32.dll!CAptRpcChnl::SendReceive(struct tagRPCOLEMESSAGE *,unsigned long *) Unknown
  ole32.dll!CCtxComChnl::SendReceive(struct tagRPCOLEMESSAGE *,unsigned long *) Unknown
  ole32.dll!NdrExtpProxySendReceive(void *,struct _MIDL_STUB_MESSAGE *) Unknown
  rpcrt4.dll!@NdrpProxySendReceive@4 () Unknown
  rpcrt4.dll!_NdrClientCall2 () Unknown
  ole32.dll!_ObjectStublessClient@8 () Unknown
  ole32.dll!_ObjectStubless@0 () Unknown
  ole32.dll!CObjectContext::InternalContextCallback(long (*)(void *),void *,struct _GUID const &,int,struct IUnknown *) Unknown
  ole32.dll!CObjectContext::ContextCallback(long (*)(struct tagComCallData *),struct tagComCallData *,struct _GUID const &,int,struct IUnknown *) Unknown
> Win32ConsoleApplication.exe!myThread(void * p) Line 239 C++
  msvcr110d.dll!_callthreadstart() Line 255 C
  msvcr110d.dll!_threadstart(void * ptd) Line 239 C
  kernel32.dll!@BaseThreadInitThunk@12 () Unknown
  ntdll.dll!___RtlUserThreadStart@8 () Unknown
 ntdll.dll!__RtlUserThreadStart@8 () Unknown

Windows OS has many hidden features, used by Microsoft products. Are we any worse?

Change system drive letter in Windows

Недавно пришлось устанавливать Windows 7 x64 из работающей Windows 7 x32 (болванки не было нормальной для загрузки с нее). В результате буква системного диска стала G. Я такого не люблю и попытался всяческими способами сменить ее на C. В результате система перестала грузиться или оказалась в состоянии что-то в духе человека-овоща, подключенного к аппарату поддержки жизнедеяльности. А все потому, что реестр захламлен путями к файлам драйверов, COM библиотек и прочей важной ерунды. А пути там, да, абсолютные, включают букву системного диска. Ура, товарищи! Букву системного диска сменить НЕЛЬЗЯ, устанавливайте с оптических или других носителей.

MFC fails again

MFC, I love you. Really. Your source code is a fantastic example of how not to do it. Don't do it ever.

The problem

OK, so here's the problem - given an MFC dialog (or dialog control), sometimes we have no focus cues when tabbing through UI elements. You press Tab, use cursor keys and yet focus rectangle is not there. Forever. What might the problem be? Let's find out how this works internally.

Focus rect internals

First of all open any system dialog (for example taskbar Properties) using mouse only and ensure there is no focus rectangle on currently focused UI element. Press Tab and watch for it to immediately appear. Whatever you do from now on (excluding cases where the whole window hierarchy is hidden or recreated), focus rect is always on the screen. Now try to open this dialog using keyboard operation (you can open taskbar context menu and select Properties menu item using keyboard keys). Focus rect is shown immediately. What's happening here?

The answer begins it's path in dlgbegin.c, function InternalCreateDialog:

HWND InternalCreateDialog(
    HANDLE hmod,
    LPDLGTEMPLATE lpdt,
    DWORD cb,
    HWND hwndOwner,
    DLGPROC lpfnDialog,
    LPARAM lParam,
    UINT fSCDLGFlags)
{
...
}

The most interesting part is the following:

 /*
  * UISTATE: if keyboard indicators are on and this is a topmost dialog
  * set the internal bit.
  */
 if (TEST_KbdCuesPUSIF) {
     /*
      * If property page, UISTATE bits were copied from parent when I was created
      * Top level dialogs act as containers and initialize their state based on
      * the type of the last input event, after sending UIS_INITIALIZE
      */
     if (!TestwndChild(pwnd)) {
         SendMessageWorker(pwnd, WM_CHANGEUISTATE, MAKEWPARAM(UIS_INITIALIZE, 0), 0, FALSE);
     }
 }

TEST_KbdCuesPUSIF tests current execution environment for keyboard cues enablement (field check in some global structure), TestwndChild ensures top level dialog. Then the window gets WM_CHANGEUISTATE message with two arguments - UIS_INITIALIZE and zero. Documentation says Top level dialogs act as containers and initialize their state based on the type of the last input event. What does this mean? The answer is in the default window procedure (dwp.c):

/***************************************************************************\
* xxxDefWindowProc (API)
*
* History:
* 10-23-90 MikeHar Ported from WaWaWaWindows.
* 12-07-90 IanJa   CTLCOLOR handling round right way
\***************************************************************************/

LRESULT xxxDefWindowProc(
    PWND pwnd,
    UINT message,
    WPARAM wParam,
    LPARAM lParam)
{
...
}

Take a look at WM_CHANGEUISTATE handler:

case WM_CHANGEUISTATE:
    {
        WORD wAction = LOWORD(wParam);
        WORD wFlags = HIWORD(wParam);
        BOOL bRealChange = FALSE;

        if (wFlags & ~UISF_VALID || wAction > UIS_LASTVALID ||
            lParam || !TEST_KbdCuesPUSIF) {
                return 0;
        }

        if (wAction == UIS_INITIALIZE) {
            if (gpsi->bLastRITWasKeyboard) {
                wAction = UIS_CLEAR;
            } else {
                wAction = UIS_SET;
            }
            wFlags = UISF_HIDEFOCUS | UISF_HIDEACCEL;
            wParam = MAKEWPARAM(wAction, wFlags);
        }

        UserAssert(wAction == UIS_SET || wAction == UIS_CLEAR);
        /*
         * If the state is not going to change, there's nothing to do here
         */
        if (wFlags & UISF_HIDEFOCUS) {
            bRealChange = (!!TestWF(pwnd, WEFPUIFOCUSHIDDEN)) ^ (wAction == UIS_SET);
        }
        if (wFlags & UISF_HIDEACCEL) {
            bRealChange |= (!!TestWF(pwnd, WEFPUIACCELHIDDEN)) ^ (wAction == UIS_SET);
        }

        if (!bRealChange) {
            break;
        }

        /*
         * Children pass this message up
         * Top level windows update their children's state and
         * send down to their imediate children WM_UPDATEUISTATE.
         */
        if (TestwndChild(pwnd)) {
            ThreadLockAlways(pwnd->spwndParent, &tlpwndParent);
            lt = xxxSendMessage(pwnd->spwndParent, WM_CHANGEUISTATE, wParam, lParam);
            ThreadUnlock(&tlpwndParent);
            return lt;
        } else {
            return xxxSendMessage(pwnd, WM_UPDATEUISTATE, wParam, lParam);
        }

        }
    break;

case WM_QUERYUISTATE:
    return (TestWF(pwnd, WEFPUIFOCUSHIDDEN) ? UISF_HIDEFOCUS : 0) |
           (TestWF(pwnd, WEFPUIACCELHIDDEN) ? UISF_HIDEACCEL : 0);
    break;

case WM_UPDATEUISTATE:
    {
        WORD wAction = LOWORD(wParam);
        WORD wFlags = HIWORD(wParam);

        if (wFlags & ~UISF_VALID || wAction > UIS_LASTVALID ||
            lParam || !TEST_KbdCuesPUSIF) {
                return 0;
        }

        switch (wAction) {
            case UIS_INITIALIZE:
                /*
                 * UISTATE: UIS_INITIALIZE sets the UIState bits
                 * based on the last input type
                 */
                if (!gpsi->bLastRITWasKeyboard) {
                    SetWF(pwnd, WEFPUIFOCUSHIDDEN);
                    SetWF(pwnd, WEFPUIACCELHIDDEN);
                    wParam = MAKEWPARAM(UIS_SET, UISF_HIDEACCEL | UISF_HIDEFOCUS);
                } else {
                    ClrWF(pwnd, WEFPUIFOCUSHIDDEN);
                    ClrWF(pwnd, WEFPUIACCELHIDDEN);
                    wParam = MAKEWPARAM(UIS_CLEAR, UISF_HIDEACCEL | UISF_HIDEFOCUS);
                }
                break;

            case UIS_SET:
                if (wFlags & UISF_HIDEACCEL) {
                    SetWF(pwnd, WEFPUIACCELHIDDEN);
                }
                if (wFlags & UISF_HIDEFOCUS) {
                    SetWF(pwnd, WEFPUIFOCUSHIDDEN);
                }
                break;

            case UIS_CLEAR:
                if (wFlags & UISF_HIDEACCEL) {
                    ClrWF(pwnd, WEFPUIACCELHIDDEN);
                }
                if (wFlags & UISF_HIDEFOCUS) {
                    ClrWF(pwnd, WEFPUIFOCUSHIDDEN);
                }
                break;

            default:
                break;
         }

        /*
         * Send it down to its immediate children if any
         */
         if (pwnd->spwndChild) {

            PBWL pbwl;
            HWND *phwnd;
            TL tlpwnd;

            pbwl = BuildHwndList(pwnd->spwndChild, BWL_ENUMLIST, NULL);
            if (pbwl == NULL)
                return 0;

            for (phwnd = pbwl->rghwnd; *phwnd != (HWND)1; phwnd++) {
                /*
                 * Make sure this hwnd is still around.
                 */
                if ((pwnd = RevalidateHwnd(*phwnd)) == NULL)
                    continue;

                ThreadLockAlways(pwnd, &tlpwnd);
                xxxSendMessage(pwnd, message, wParam, lParam);
                ThreadUnlock(&tlpwnd);
            }
            FreeHwndList(pbwl);
        }
    }
    break;

We are interested in the following code:

if (wAction == UIS_INITIALIZE) {
    if (gpsi->bLastRITWasKeyboard) {
        wAction = UIS_CLEAR;
    } else {
        wAction = UIS_SET;
    }
    wFlags = UISF_HIDEFOCUS | UISF_HIDEACCEL;
    wParam = MAKEWPARAM(wAction, wFlags);
}

It checks whether last input event was the one from keyboard (bLastRITWasKeyboard, RIT - raw input thread) and prepares appropriate action - set UISF_HIDEFOCUS and UISF_HIDEACCEL flags or clear them. The system tries to understand user experience type (mouse or keyboard) and initializes window state for better interaction. That's why you don't see focus or accelerator cues having opened a dialog using mouse whereas they are both on if you used your keyboard.

There is a little trick to have the system on: move the mouse right after you triggered a dialog using keyboard, or press any key after you triggered a dialog using mouse. The effect speaks for itself.

The rest of the handler simply decides where to send WM_UPDATEUISTATE message. WM_UPDATEUISTATE's handler just saves the state to internal OS structure for particular window. As you have already guessed, WM_QUERYUISTATE reads the state back.

What does this all mean? There is a window state for focus and accelerator cues and a set of messages for it's manipulation. This state is kept in sync by all windows of the same hierarchy. OS initializes the state for best user experience.

Who uses the state

At least common controls, of course. The pattern is simple (listview.c for example):

case WM_UPDATEUISTATE:
{
    DWORD dwUIStateMask = MAKEWPARAM(0xFFFF, UISF_HIDEFOCUS);

    // we care only about focus not accel, and redraw only if changed
    if (CCOnUIState(&(plv->ci), WM_UPDATEUISTATE, wParam & dwUIStateMask, lParam))
    {
        if(plv->iFocus >= 0)
        {
            // an item has the focus, invalidate it
            ListView_InvalidateItem(plv, plv->iFocus, FALSE, RDW_INVALIDATE | RDW_ERASE);
        }
    }

    goto DoDefault;
}

It just listens to UI state updates and does appropriate actions (saves the state to local structure, invalidates the window etc.).

Who updates the state

As I've already mentioned, focus rect is shown immediately as you pressed focus navigation key (Tab for example). This is done by ::IsDialogMessage OS function:

case WM_SYSKEYDOWN:
    /*
     * If Alt is down, deal with keyboard cues
     */
    if ((HIWORD(lpMsg->lParam) & SYS_ALTERNATE) && TEST_KbdCuesPUSIF) {
        if (TestWF(pwnd, WEFPUIFOCUSHIDDEN) || (TestWF(pwnd, WEFPUIACCELHIDDEN))) {
                SendMessageWorker(pwndDlg, WM_CHANGEUISTATE,
                                  MAKEWPARAM(UIS_CLEAR, UISF_HIDEACCEL | UISF_HIDEFOCUS), 0, FALSE);
            }
    }
    break;
case WM_KEYDOWN:
    code = (UINT)SendMessage(lpMsg->hwnd, WM_GETDLGCODE, lpMsg->wParam,
            (LPARAM)lpMsg);
    if (code & (DLGC_WANTALLKEYS | DLGC_WANTMESSAGE))
        break;

    switch (lpMsg->wParam) {
    case VK_TAB:
        if (code & DLGC_WANTTAB)
            break;
        pwnd2 = _GetNextDlgTabItem(pwndDlg, pwnd,
                (GetKeyState(VK_SHIFT) & 0x8000));

        if (TEST_KbdCuesPUSIF) {
            if (TestWF(pwnd, WEFPUIFOCUSHIDDEN)) {
                SendMessageWorker(pwndDlg, WM_CHANGEUISTATE,
                                      MAKEWPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0, FALSE);
            }
        }

WM_SYSKEYDOWN and WM_KEYDOWN analyze keyboard input and trigger UI state updates by sending WM_CHANGEUISTATE. All child windows then receive state change update, focused window shows up a shiny focus rectangle, labels begin to draw accelerator cues. Simple, huh?

So what the fuck is wrong might be in MFC

As you already know (I hope) MFC focus navigation is implemented via CWnd::PreTranslateMessage virtual function which eventually calls CWnd::IsDialogMessage method:

BOOL CWnd::IsDialogMessage(LPMSG lpMsg)
{
 ASSERT(::IsWindow(m_hWnd));

 if (m_nFlags & WF_OLECTLCONTAINER)
  return afxOccManager->IsDialogMessage(this, lpMsg);
 else
  return ::IsDialogMessage(m_hWnd, lpMsg);
}

In case of ActiveX controls in your dialog template (or any other shit involving OCC state initialization), WF_OLECTLCONTAINER flag is set and the control passes to COccManager::IsDialogMessage instead of API ::IsDialogMessage. Believe me or not, COccManager::IsDialogMessage analyzes keyboard input and moves the focus. The biggest problem with this method - it doesn't consider UI layout the way ::IsDialogMessage does. ZOrder enumeration is done using CWnd::GetNextDlgTabItem (see correct overload with COleControlSiteOrWnd * parameter), which moves through controls registered in COleControlContainer - m_pCtrlCont->m_listSitesOrWnds. As you might have already guessed, this container is populated by MFC during dialog creation (from template of course) and is not updated afterwards. So if you add your controls dynamically (WTL/MFC/whatever) - be ready for focus navigation problems. The solution is to update container with necessary items for each control you create/recreate etc. Plus you have to keep items order to reflect proper ZOrder. What a crap!

Finally, the answer

COccManager::IsDialogMessage doesn't fucking send WM_CHANGEUISTATE as ::IsDialogMessage does. It doesn't fucking do it. Fucking MFC, fuck you. FUCK YOU.

Copyright 2007-2011 Chabster