I noted some time ago Windows requires that pointers be aligned unless explicitly permitted to be unaligned. I gave as an example of a function that explicitly permits unaligned pointers the SHFormatDateTime function:
LWSTDAPI_(int) SHFormatDateTimeA( In const FILETIME UNALIGNED * pft, Inout_opt DWORD * pdwFlags, Out_writes(cchBuf) LPSTR pszBuf, UINT cchBuf);
Why does this function go out of its way to allow an unaligned FILETIME?
The SHFormatDateTime was originally written for Explorer to use when formatting dates and times in details view and in property sheets. And a common source of these FILETIME structures are embedded inside Shell item ID lists, commonly known as “pidls” (rhymes with “riddles”) because the Hungarian notation for them is pidl, a “pointer to an ID list”.
Shell item ID lists require only byte alignment, so any structures you embed in them will be unaligned. The SHFormatDateTime bent over backward to accommodate its primary audience and allowed unaligned FILETIME structures to be passed in. (It presumably just copies it to an aligned local variable.)
I suspect that the SHFormatDateTime function was originally written for the Windows 95 series, which ran on x86-class processors, and x86-class processors are forgiving of misalignment. When the Windows NT team ported the code to alignment-sensitive RISC processors, they got tired of fixing all the individual call sites to copy the misaligned FILETIME to an aligned local, and they instead just taught the SHFormatDateTime function to be forgiving of misalignment and transfer the work of copying the misaligned FILETIME to a local into the SHFormatDateTime function.
So really, the fact that SHFormatDateTime accepts a misaligned pointer is just a historical expediency and not something that was part of its original design. Nowadays, we’d just tell everybody to align the FILETIME on the caller side instead of doing it on the receiving end.
The post Why does <CODE>SHFormatDateTime</CODE> take an unaligned <CODE>FILETIME</CODE>? appeared first on The Old New Thing.
From The Old New Thing via this RSS feed


