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

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].

Lindemann

Он бесподобен, я хочу от него детей!!!!!!11

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

std::numeric_limits<UnsignedIntegral>::max() alternative

std::numeric_limits<uint32_t>::max() == static_cast<uint32_t>(-1) == ~0U

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.

Visual C++ versus new T[N] { 0 }

auto const p = std::unique_ptr(new unsigned char[1024 * 50] { 0 });

link.exe зависает, кушая при этом процессор.

auto const p = std::unique_ptr(new unsigned char[1024 * 50] { 0 });

Результат: fatal error C1063: compiler limit : compiler stack overflow

auto const p = std::unique_ptr(new unsigned char[1024] { 0 });

Сгенерированные инструкции:

00007FF6D1CF1A3A  call        operator new[] (07FF6D1CF1E30h)  
00007FF6D1CF1A3F  xor         ecx,ecx  
00007FF6D1CF1A41  test        rax,rax  
00007FF6D1CF1A44  je          wmain+383h (07FF6D1CF1D9Bh)  
00007FF6D1CF1A4A  mov         qword ptr [rax],rcx  
00007FF6D1CF1A4D  mov         qword ptr [rax+8],rcx  
00007FF6D1CF1A51  mov         qword ptr [rax+10h],rcx  
00007FF6D1CF1A55  mov         qword ptr [rax+18h],rcx  
00007FF6D1CF1A59  mov         qword ptr [rax+20h],rcx  
00007FF6D1CF1A5D  mov         qword ptr [rax+28h],rcx  
00007FF6D1CF1A61  mov         qword ptr [rax+30h],rcx  
00007FF6D1CF1A65  mov         qword ptr [rax+38h],rcx  
00007FF6D1CF1A69  mov         qword ptr [rax+40h],rcx  
00007FF6D1CF1A6D  mov         qword ptr [rax+48h],rcx  
00007FF6D1CF1A71  mov         qword ptr [rax+50h],rcx  
00007FF6D1CF1A75  mov         qword ptr [rax+58h],rcx  
00007FF6D1CF1A79  mov         qword ptr [rax+60h],rcx  
00007FF6D1CF1A7D  mov         qword ptr [rax+68h],rcx  
00007FF6D1CF1A81  mov         qword ptr [rax+70h],rcx  
00007FF6D1CF1A85  mov         qword ptr [rax+78h],rcx  
00007FF6D1CF1A89  mov         qword ptr [rax+80h],rcx  
...

Заполнение пасяти нулями шмомпилятор от Быдлософт развернул в 128 инструкций mov.

То же, но компилятором Intel C++:

00007FF755B1102B  call        operator new[] (07FF755B13C50h)  
...
00007FF755B11053  call        _intel_fast_memcpy (07FF755B11B50h)  

_intel_fast_memcpy для моего Core i5 2XXX выбрала реализацию с циклом следующего вида:

00007FF755B132A0  movdqa      xmm0,xmmword ptr [rdx]  
00007FF755B132A4  movdqa      xmm1,xmmword ptr [rdx+10h]  
00007FF755B132A9  movdqa      xmmword ptr [rcx],xmm0  
00007FF755B132AD  movdqa      xmmword ptr [rcx+10h],xmm1  
00007FF755B132B2  lea         r8,[r8-80h]  
00007FF755B132B6  movdqa      xmm2,xmmword ptr [rdx+20h]  
00007FF755B132BB  movdqa      xmm3,xmmword ptr [rdx+30h]  
00007FF755B132C0  movdqa      xmmword ptr [rcx+20h],xmm2  
00007FF755B132C5  movdqa      xmmword ptr [rcx+30h],xmm3  
00007FF755B132CA  movdqa      xmm0,xmmword ptr [rdx+40h]  
00007FF755B132CF  movdqa      xmm1,xmmword ptr [rdx+50h]  
00007FF755B132D4  cmp         r8,0A8h  
00007FF755B132DB  movdqa      xmmword ptr [rcx+40h],xmm0  
00007FF755B132E0  movdqa      xmmword ptr [rcx+50h],xmm1  
00007FF755B132E5  movdqa      xmm2,xmmword ptr [rdx+60h]  
00007FF755B132EA  movdqa      xmm3,xmmword ptr [rdx+70h]  
00007FF755B132EF  lea         rdx,[rdx+80h]  
00007FF755B132F6  movdqa      xmmword ptr [rcx+60h],xmm2  
00007FF755B132FB  movdqa      xmmword ptr [rcx+70h],xmm3  
00007FF755B13300  lea         rcx,[rcx+80h]  
00007FF755B13307  jge         __intel_memcpy+0E90h (07FF755B132A0h)  

А если выбрать Favor Small Code в настройках компилятора, то заполнение нулями превращается в ожидаемый и привычный rep movs:

...
00007FF615041053  rep movs    qword ptr [rdi],qword ptr [rsi]

Nosgoth beta keys

VEBOME-957-JAMONO-230

NABOFA-205-CAXABU-021

VEJODE-375-COZABO-211

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

Apple Swift

Windows Internals 7th edition

March 13, 2015

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.

Metal Gear Rising: Revengeance

Metal Gear Rising: Revengeance has just released on PC!

Amazing OST:

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).

Injustice: Gods Among Us

Игроки в онлайне делятся на два типа: одни спамят, а другие занимались сексом с их матерью

Visual Studio 2012 Update 4

Asshole in Range Rover

Сегодня красиво наказал энурезника очередного на белом коне. Стоял в левом ряду на Автозаводской (по 3 полосы в каждую сторону) первым, смотрю в зеркало - а там очередное хуйло, обгоняя аж 3-4 автомобиля, прет по встречке. Я дал по газам и не позволил белому Range Rover'у стать перед собой. А на другом конце перекрестка в том же левом ряду первыми стояли угадайте кто? Правильно - пацаны с красными и синими мигалками. Результат - быдло к тротуару. Энурез нужно лечить, господа, ЛЕЧИТЬ.

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();
      }
   }
}

Razer DeathStalker (not Ultimate)

Завидуйте, нищеброды! Американская раскладка, с не кастрированным левым шифтом и нормальным вводом! USA! USA! USA!

Maelstorm- Wild Dances

Copyright 2007-2011 Chabster