COM, BSTR or _bstr_t is leaking memory

COM, BSTR or _bstr_t is leaking memory. That was my first thought when I saw increasing number in Task Manager under memory colon for the process I am developing.

Searching Google for quick answer I found famous Microsoft employee and blogger Larry Osterman’s blog post about Hey, why am I leaking all my BSTR’s? He describes OLE caching of BSTR objects and tool called UMDH. OLE caching is not my case, however UMDH may be useful is you are able to figure out what to do.

Another link I found is from 1999 (VS6) Implementing a Simple MFC Client for an ATL Server. They have notes about memory leaks all over the place. Particularly interesting are two examples I have copied below.

Without leak:
//Update static text with new value
BSTR tmpBStr;
 
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr(tmpBStr, FALSE); //necessary to avoid a memory leak
 
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);

With leak:
//Update static text with new value
BSTR tmpBStr;
 
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr;
 
tmpbstr= tmpBStr; //Caution: Memory leak occurs
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);

And explanation:

The leak occurs when the tmpbstr variable is initialized. A call to SysAllocString (reference available in the Component Services section of the Platform SDK) is automatically made when creating the tmpbstr variable. This new allocation is never freed later, resulting in a memory leak. Using this version of the _bstr_t constructor avoids the issue by attaching the BSTR object to tmpbstr without a call to SysAllocString. For more information on this issue, see _bstr_t::_bstr_t (reference available in the C++ Language Reference section of the Visual C++ Documentation).

The problem is that explanation is wrong. My speculation: Most probably one person (senior programmer?) found memory leak in documentation, fixed it and told another person (junior programmer?) to update documentation. And that second person got it wrong. First: _bstr_t constructor _bstr_t::_bstr_t() does not allocate memory. Second: if it were allocating, then it would be freed, see the code below:
_bstr_t& _bstr_t::operator=(const wchar_t* s)
{
    if (s == NULL || ...)
    {
        _Free();
        m_Data = new Data_t(s);

And yes, _Free does exactly that. It frees m_Data if it contains something, in our case as I noted above, it points to 0×00000000;

operator=(const wchar_t* s) is exactly what is called in my case – Unicode compile.

Again, the code in Microsoft article leaks memory as comment says, but it does not leak as it is described. It leaks because memory allocated by m_pObject1->get_ObjectString is not freed.

In the end I found my memory leak. It was similar problem, I needed to call _bstr_t constructor with FALSE as second argument. From MSDN: If false, the bstr argument is attached to the new object without making a copy by calling SysAllocString.

So be careful playing with BSTRs.

Posted in Computers, OS, Programming | Tagged , , , | 1 Comment

2011 links no. 3

Interview With Sacha Barber in The Code Project.

The ABA problem occurs during synchronization, when a location is read twice, has the same value for both reads, and “value is the same” is used to indicate “nothing has changed”. However, another thread can execute between the two reads and change the value, do other work, then change the value back, thus fooling the first thread in to thinking “nothing has changed” even though the second thread did work that violates that assumption.

An Idiot’s Guide to C++ Templates by Ajay Vijayvargiya from The Code Project.

C++0x Finally Becomes a Standard discussed in Slashdot.

What is Cloud Programming and why should we care By GanesanSenthilvel at The Code Project.

Interesting discussion in StackOverflow about Creating a memory leak with Java.

Why is subtracting two times (in 1927) is giving a strange result? or in Shanghai at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. From StackOverflow.

$300M To Save 6 Milliseconds in high frequency trading discussed at Slashdot.

Age bias in IT: Some consider it IT’s dirty little secret, or even IT’s big open secret – from computerworld.com by Tam Harbert.

Am I Too Old To Learn New Programming Languages? from Slashdot and Become a Good Programmer in Six Really Hard Steps from ApochPiQ in GameDev.net.

InfoWorld writes about The nine circles of IT hell by Dan Tynan.

Biggest Mistakes in Web Design 1995-2015 from webpagesthatsuck.com.

From glyph recognition to augmented reality with video demos and source code By Andrew Kirillov in The Code Project.

Introduction to Google App Inventor by VinayakIyer from The Code Project.

Guide to Image Composition with Win32 MsImg32.dll By Paul Watt from The Code Project.

JavaScript Jargon (Coming to JavaScript from C#) By Jonathan Cardy.

Learn to code: Codecademy is the easiest way to learn how to code. It’s interactive, fun, and you can do it with your friends.

Minimalist Coding Guidelines By gggustafson.

Penrose Tiling in Obfuscated Python or Who says you can’t write obfuscated Python? from Jeff Preshing.

Learn Perl in about 2 hours 30 minutes By Sam Hughes.

PowerShell is powerful but can it handle gaming? PowerShell Falling Blocks By Lasse W.

Sudoku solver via a webcam: A nice computer vision application with source code from Bojan Banko.

Windows API: Slim Reader/Writer (SRW) Locks from MSDN (available from Vista and Server 2008).

The Five Levels of ISP Evil from Dane Jasper.

spin.js – cool open source JavaScript spinner hosted in GitHub.

Starting up inside the box (Vista and above) from Raymond Chen.

Stuxnet Malware Analysis Paper By AmrThabet. This article will focus on Stuxnet’s windows infection methods and spreading methods.

The Power of Rooting on Android By David Magnotti.

The Principles of Good Programming by Christopher Diggins.

.NET ThreadPool vs. Tasks by Paul Stovell.

Why does creating a shortcut to a file change its last-modified time… sometimes? from Raymond Chen.

Writing a Multiplayer Game (in WPF) By Paulo Zemek. This article will explain some concepts of game development and how to apply and adapt them for multiplayer development.

Posted in Computers, OS, Programming, Web | Tagged , , , , , , , , , , , , , , , , | Leave a comment

.NET Framework 2.0 is not installed on Windows 8 Developer Preview by default

.NET Framework 2.0 is not installed on Windows 8 Developer Preview by default.

To install it, go to Control Panel – Programs – Turn Windows features on or off – Check ‘Microsoft .NET Framework 3.5.1′ – OK.

Note, that .NET Framework 2.0 is included into version 3.5.

Below are some screenshots from the installation process.

Posted in OS | Tagged , | 5 Comments

Urih.com statistics – you never know what will be most used feature

22 weeks (or 5 months and 5 days) after urih.com launch, here we have an interesting stats. Clearly, the most used feature on the urih.com is SilverBench – online CPU benchmark tool.

The opposite – the feature that no one have used is: Feedback form, that is located on all pages.

To be exact, the Feedback feature is used exactly 0 (zero, null, none) times. However SilverBench is used many, many times each day. If you look at the SilverBench results page, you can see, that from 5 – 10 people submit their benchmark scores every day.

So no one can predict, that after 22 weeks, the one of the most prominent features will not be used even single time.

P.S. Forgot to mention, that 36 days ago we launched HTTP Response header tool. An online tool, that can be used to view HTTP header stats and information for any site in the Internet.

Posted in Web | Tagged , , , | Leave a comment

CreateProcessAsUser fails on Windows XP with System error 233

Today I fixed one bug that was very hard to reproduce. Many hours were spent to figure out what combination caused it:

  • It happens only on Windows XP (not on Vista, Server 2003, 2008, Win 7);
  • It does not happens on all Windows XP, because it is Race condition;
  • I was unable to reproduce it with physical glass/monitor attached to the computer; It only happened using Remote Desktop;
  • It does not happen when debugger is attached and breakpoint is being hit;

Latter I found people that have similar issue:

The code is the following:
WTSQueryUserToken(..., &hToken);
SetTokenInformation(hToken, ...);
SomeVistaAndWin7ElevatedTokenStuff(hToken);
CreateProcessAsUser(hToken, ...);

And CreateProcessAsUser fails with GetLastError() = 233. Looking in System Error Codes (0-499) – ERROR_PIPE_NOT_CONNECTED 233 (0xE9) – No process is on the other end of the pipe.

The confusing part is about Pipe, because you didn’t expect to get pipe error here – you have not created any pipe.

In the first post I have linked, Thomas Graefenhain writes:

I’ve debugged a little bit with the kernel debugger, and have found the
problem: CreateProcessAsUser uses internally, when creating a process in an
other session, the function CreateRemoteProcessW from ADVAPI32.DLL. This
function opens a pipe with the name
\\.\Pipe\TerminalServer\SystemExecSrvr\%d where %d is the SessionID and
sending the request over to csrss.exe. …

In another post someone mentioned that Sleep(2000) fixed the problem. This explains why under debugger everything works without an error.

The good news is that it happens only under Windows XP and under Remote Desktop, so small group of users are affected. The bad new is that there are no elegant workarounds. Windows XP is in the Extended Support Phase, so I am not counting on fix from Microsoft.

Currently I use the following workaround (simplified version, see below). If you have something better or more elegant, please let me know in the comments below.
{
     Sleep(100);
     CreateProcessAsUser(hToken, ...);
} while (wasError && GetLastError() == 233 && IsWindowsXP());

Posted in Computers, OS, Programming | Tagged , , , , | 1 Comment

Microsoft’s PowerShell hangs when output is captured using Windows API

I was debugging a program that uses Windows API (Creating a Child Process with Redirected Input and Output) to capture stdout of Microsoft’s Windows PowerShell.

Script passed to PowerShell (-File switch) didn’t execute and PowerShell just hanged until killed by Task Manager.

It turns out that you need to use undocumented parameter “-InputFormat none”:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -InputFormat none -File file.ps1

This is discussed in MS Connect site: PowerShell.exe can hang if STDIN is redirected.

Similar issue at StackOverflow: Silently executing a PowerShell script from WiX Hangs PowerShell.

Posted in Computers, OS, Programming | Tagged , , | Leave a comment

2011 links no. 2

Stack Overflow profiler open sourced: Profiling your website like a true Ninja.

Smaller is Faster (and Safer Too). Chrome team have just started using a new compression algorithm called Courgette to make Google Chrome updates small. Read more.

Ask Amir Taaki About Bitcoin. From Slashdot.

The Four Stages of NTFS File Growth from Windows Server Core Team.

Some articles from CodeProject:

Rosa Golijan writes about what happens on the Internet every 60 seconds.

The Biggest Changes in C++11 (and Why You Should Care) by Danny Kalev.

Are You Too Good For Code Reviews? Articles and discussion in Slashdot.

Google’s Swiffy converts Flash SWF files to HTML5.

Have you wondered whether WordPress can handle high-volume traffic? High Traffic Tips For WordPress.

The most detailed story about Stuxnet: How Digital Detectives Deciphered Stuxnet, the Most Menacing Malware in History.

How to build your own 135TB RAID6 storage pod for $7,384 from extremetech.com.

Investigation: Is Your SSD More Reliable Than A Hard Drive? from tomshardware.com.

pdf.js is a technology demonstrator prototype to explore whether the HTML5 platform is complete enough to faithfully and efficiently render the ISO 32000-1:2008 Portable Document Format (PDF) without native code assistance. From Dr. Andreas Gal.

Posted in Programming, Web | Tagged , , , , , , , , , , , | Leave a comment

Urih.com has online resource viewer for executable files

One of very interesting online tool we launched in urih.com is online resource viewer for executable files. We call it – Portable executable online viewer.

This new (online) tool can be used like any old (offline) tool to view images embedded into executable (PE format) file.

Also, many properties of executable file are shown, like Date compiled – date when exe is build (not same as file date/time), minimum OS version, application manifest XML file, and more.

Here is an example of how it looks like for calc.exe file from Windows 7.

Posted in Computers, OS, Programming | Tagged , , | Leave a comment

Strange HTTP GET requests from IP 150.70.x.x and IP 62.24.x.x

Recently I started to notice that one of our sites gets strange HTTP GET requests from two IP ranges: 150.70.x.x and IP 62.24.x.x.

The short version of this goes as follows: we have web service when users can submit results via HTTP GET request. For example:
http://www.example.com/service?guid={BEDC2C9A-C5E6-4766-B57C-7CC07BB26F59}&result=x

Each (next) user/request gets a new GUID, like:
http://www.example.com/service?guid={412E9B56-E9CE-4FB5-9804-676FDC9EA3EC}&result=a
http://www.example.com/service?guid={64A00D1D-BCDB-4B5A-9DF3-51CF2BB6B663}&result=b
http://www.example.com/service?guid={CA5B86A1-A6B4-4CA8-AAA6-DC9302CF34D3}&result=c

Because GUIDs are unique, we should get each GUID only once. But this was not true for our web-service. We occasionally got duplicate requests. We started to investigate closer, and found that all double requests come from two IP ranges 150.70.x.x and IP 62.24.x.x, and all “second” requests follows the first after 30s – 5 min.

We did a Google search and found, that 150.70 IP range belongs to Trend Micro. There are even some statement from them:

Dear Site Owner,

To protect our customers from visiting a malicious or harmful site, web pages of the applicable URLs are downloaded and scanned by our servers. Thus, you may have noticed a few visits from our IPs. Please be assured that this poses no security risk to your web sites as our servers do not perform any action other than scanning the sites.
We then store the rating of the web site in our server cache so that our servers will no longer access those pages for analysis when a customer chooses to visit those web sites again. We have already asked our server owner to add the rating for the following domain(s);
…..
The setting will take effect soon, please verify it again on your site.
Sorry for any inconvenience and please inform us of any other concerns you may have.
Best Regards,
Trend Micro’

More: http://forum.notebookreview.com/security-anti-virus-software/331930-trendmicro-servers-japan-accessing-webservers.html

It seems, that Trend Micro is spying after their customers. Second range comes from Talk Talk UK’s ISP, who apparently spies after their customers too.

Here are some links with more reading:
Search Engine Spider and User Agent Identification Forum from webmasterworld.com
IP Address Inspector – projecthoneypot.org
Im Being Monitored/Watched?

P.S. Most probably they do not try to do HTTP POST request, I do not know. We probably should use POST too, but that’s another story.
P.S.S. Some encryption like SSL should be mandatory for all Internet traffic in future.

Posted in Computers, Programming, Web | Tagged , , | 2 Comments

Windows API PlaySound error / silence

Today stumbled at strange behavior of Windows API function PlaySound in combination with SND_FILENAME flag.

There are two scenarios:

  1. No sound is played, and PlaySound returns success (TRUE) in combination with SND_ASYNC;
  2. No sound is played, and PlaySound returns failure (FALSE) when using the same wav file, but without asynchronous flag.

The cause is, that system where this is happening is Windows Server 2008 R2, which is apparently missing some WAV codec. Files coded with different codec works.

Posted in Computers, OS | Tagged , , | Leave a comment