C++ code analysis in Visual Studio 2012

Lire cet article en français

lots-of-crashes_thumb1

The problem with this kind of message is that it does not make your customers very found of your application. And what if it happens during trial period?

Good news is, code analysis is one answer to this kind of problem.

Code analysis examines source code at compilation time, and finds bugs before they even happen. It is one of the debugging tools a developer can use. It complements the usual test procedures (functional testing, unit testing …) Its secret is to find unsafe code patterns in source code. And it is efficient.

Code analysis is one of the tools that can be used to create safer applications. It is part of Microsoft SDL methodology (Security Development Lifecycle).

I’m sorry to inform you that Code analysis knows which bugs you create. Hence, it can find them in your code:

  • dereferencing null pointer
  • buffer overrun
  • uninitialized variable
  • memory leak
  • concurrent access problem

Code Analysis in Visual C++ 2012 (VS11) and MFC

 

The team which has created Code analysis for C++ used the huge code base of Windows. They know what type of code is safe, and what type of code can cause a crash!

Code analysis in Visual Studio 2010 is only available in Visual Studio Ultimate. But Microsoft decided it is important for every C++ developer to have this tool handy. So, a light version of C++ code analysis is included in Visual Studio 11 Express, and all of the 200+ rules are in Visual Studio 11 Professional (from Code Analysis talk at Build Conference)

Code analysis has been improved in Visual Studio 11 in many ways: it is easier to use, thanks to the new Code Analysis window, and it is more powerful, more readable (more explicit messages) and reported problems are more relevant. Code analysis uses rules to find unsafe code patterns. The rules are improved, and cover a wider range of code, including multitasking, and soon 64-bit compilation.

Visual Studio 11 Developer Preview, a pre-release version of Visual Studio vNext, allows everyone to use C++ code analysis and its bug traps, under Windows 7 (Visual Studio 11 is temporary name of next release of Visual Studio.)

When you use C++ MFC application wizard (menu File/New project/MFC Application), a SDL checks checkbox can activate Code analysis:

MFC-app-wizard-11-SDL-check_thumb3

When the project is created, Code analysis can be run very easily:

Visual--studio-2010-build-menu-code-

Code analysis must recompile the project. It is slightly longer than a simple compilation.

Note : for non-MFC C++ projects, code analysis can also be activated in the project properties (menu Project/Properties), in C/C++ general tab.

 

A few bugs detected by Code Analysis

 

All indices of arrays are scrutinized by Code analysis to detect potential overflow, especially in the loops. If an array index goes out of the array boundaries, the problem will be reported.

For example, in CDocument class, let’s create an array and use it like this:

class CMFCApplication1Doc : public CDocument
{
    // ...
    static const int m_size = 100;
    char m_tab[m_size];
    // ...
};
void CMFCApplication1Doc::ShiftArray()
{
    for (int i=0; i< m_size; i++)
    {
        m_tab[i] = m_tab[i+1];
    }
}

Of course there is a problem. It may not be caught by a code review anyway, especially if the code is not as simple as here. Code analysis finds the bug, and notices that valid indices for m_tab array range from 0 to 99, while index 100 is used.:

visual-studio-2012-code-analysis_thu

The code analysis window has a search field. Results can be filtered. Above, only the results for files whose names contain “doc” are displayed.

Here is another unsafe code sample:

void CMFCApplication1Doc::SetDelay(int delay)
{
    CDelayHolder *pObj = nullptr;
    bool isFound = false;
    for (int index = 0; index <10; index++)
    {
        if (index >= delay)
        {
            pObj = new CDelayHolder();
        }
        else
        {
            if (!isFound)
                isFound = WaitDelay(delay);
            else
                pObj->Wait(delay);
        }
    }
} 

This code is a bit weird but I have seen even stranger code! Code analysis finds the problem and explains it. It occurs during the second time through the loop:

visual-studio-2012-code-analysis-loo

 

Buffer overrun, invalid pointers, memory leaks, and many other problems are sought in the code. Code analysis uses more than 200 rules to check code safety.

 

Customizing Code analysis

 

You can customize the rules of the code analyzer as needed. Create a new rule file (menu File/New File/Code Analysis rule set), and you can disable, enable, or treat certain rules as error or warning.

visual-studio-2012-code-analysis-lis

Code Analysis tab in the Project properties let you select a Code analysis rule set.

Code analysis behavior can also be customized in C++ code, using #pragma warning :

#pragma warning(suppress: 6011) #pragma warning (error: 6001) 

 

Semantic code annotation

 

It is very easy to get a diagnostic on code quality with Visual Studio 11 Code analysis. It is possible to get even more accurate diagnostics if you help the code parser to do its job. SAL (Source code Annotation Language) is a list of keywords you can add in your source code. SAL keywords are recognized by the Code analysis parser, to make the results more accurate.

SAL can be seen as semantic comments in code. They are used by the analyzer to make verifications. SAL keywords are defined in the file sal.h. This is the file you want to check if you want to know how it works.

_In_ and _Out_ are the most used SAL keywords, in a function declaration. For example:

void GetTextProperty(_In_ LPCTSTR szPropertyName,
                    _Out_ LPTSTR szOutBuffer,
                    _In_ int nBufferSize);

_In_ means the function will only read from the buffer. The caller must provide the buffer and initialize it.

_Out_ means the function will only write to the buffer. The caller must provide the buffer, and the function will initialize it.

Code analysis will check that szPropertyName is correctly initialized before the function is called.

Microsoft Windows development team uses SAL, and more than 3 millions SAL annotations have been added to Windows source code. Thus, Windows include files contain useful annotations for our applications. For example, GlobalLock Win32 function is defined in winbase.h:

_Ret_maybenull_ LPVOID WINAPI GlobalLock (_In_ HGLOBAL hMem); 

This is quite explicit: hMem parameter must be initialized before function call and must not be null, while the return value might be null.

Thus, Code analysis will display two messages with following sample code:

HGLOBAL hMem = nullptr;
char *p = (char *)GlobalLock(hMem);
*p = 'a';

visual-studio-2012-code-analysis-glo

The first message indicates that you must not pass a null pointer to GlobalLock. The second says that, since GlobalLock can return a null pointer, it is illegal to dereference it without testing if it is not null.

MFC code also uses SAL. For example, CWnd::GetWindowText is declared as follow:

int GetWindowText(_Out_writes_to_(nMaxCount, return + 1) LPTSTR lpszStrBuf,
    _In_ int nMaxCount) const;

So, Code analysis checks that lpszStrBuf is an array of at least nMaxCount bytes, and nMaxCount must not be null.

A buffer overrun problem is detected in this code sample:

TCHAR buffer[80];
AfxGetMainWnd()->GetWindowText(buffer, 100);

visual-studio-2012-code-analysis-get

 

Parallel code analysis

 

C++ Code analysis can help finding bugs in parallel code. More than 100 rules are particularly relevant on this topic.

One of the common problems of parallel code is avoiding concurrent access to a variable. An error at this level can cause a crash or an application dead lock.

Following code sample uses an integer count, protected by a critical section cs.

_Garded_by_ is a new SAL keyword indicating that a variable must be protected by a lock. Here, cs is the lock which avoids concurrent access on count. Code analysis can now detect any access to count which is not guarded by cs.

typedef struct
{
    _Garded_by_(cs) int count;
    CRITICAL_SECTION cs;
}COUNT; 

bool CMFCApplication1Doc::UpdateCount(_In_ COUNT *p, _In_ int diff)
{
    EnterCriticalSection(&p->cs);
    if (p->count < diff)
        return false;
    p->count -= diff;
    LeaveCriticalSection(&p->cs);
    return !p->count;
}

Two problems are detected by Code analysis: a return inside the critical section, and an unprotected access to count at the end of the function:

visual-studio-2012-code-analysis-cri[2]

 

C++ Code analysis – conclusion

 

These last samples impress me. For decades, we were debugging code to find memory overflow in code! And these examples only demonstrate a part of the awesome power of the C++ Code analyzer of Visual Studio 2012. The analyzer will be included in all Visual Studio 2012 versions, including Visual C++ 2012 express, as explained in the Code Analysis talk at Build conference.

One of the conclusions we can draw is you must not use * pointers, operators new and delete anymore, but use C++11 smart pointers . If you are not using shared_ptr or unique_ptr  today, it is essential for you to get started. Smart pointers are really safer than C-style * pointers.

With the new features of C++11 and this new C++ Code analysis feature, it will be very difficult to write unsafe C++ code!

Hello world C++ Metro style app

Lire cet article en français 

C++/CX or WRL?

It is really easy to create a simple C++ app using C++/CX.

Microsoft is providing two supported ways to create Metro apps in C++, as explained in a previous post:

  • C++/CX language. C++ with MS specific language extensions like hat pointers.
  • A C++ template library (WRL). WRL is a C++ library-based solution, which offers template wrapper classes and explicit smart pointers.

But in fact, WRL is way too tedious and verbose to use. You not only have to manage COM interfaces, but also implement delegates and other WinRT stuff by hand. C++/CX is much simpler. This was just my opinion about WRL.

 

Create a C++ project

Of course you need Windows 8 installed on a touch enabled device with Visual Studio 11 Express.

In Visual Studio 11 express developer preview, click tap on menu File / New / Project, and choose Visual C++ Metro application:

Select OK to generate the sample project. MainPage.xaml file is automatically opened:

If you already know WPF, this should look familiar to you. It looks like a WPF project, but C# file is replaced by C++!

 

Create a few controls

MainPage.xaml is – as its name suggests – the Xaml language description of the main window. It is a UserControl.

For those familiar with Win32 resource files, Xaml can be seen as an improved of a resource language (string tables, DialogBox, menus, now it is in a Xaml file).

Visual Studio displays the XAML code form, along with the final rendering of the window. For now the window is empty.

Let’s add three controls in our main window: a label, an edit control, and an OK button. Insert the following text in file MainPage.xaml, inside tag <Grid> </ Grid>:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Enter 'hello, world':" Height="20" Margin="10"/>
    <TextBox Height="20" Margin="20" Width="200" x:Name="MyText"/>
    <Button Content="OK" Width="100" Height="20" Click="OnOK"/>
</StackPanel>

The Edit control (TextBox) has a MyText identifier that will be used in the code to retrieve the content.

The OK button is associated with an event handler OnOK which is still to be defined.

The three controls are encapsulated in a StackPanel control, which has the effect of aligning the three controls on a line.

 

Add C++ code

A Xaml file often comes with two other files: a .cpp and a .h file. Mainpage.xaml.cpp and Mainpage.xaml.h are linked to MainPage.xaml. Thus, C++ code for MainPage naturally find its place in these two files.

In Solution Explorer, click the small triangle in front MainPage.xaml to display the C++ associated files :

To define OnOK event handler, add the following code.

In Mainpage.xaml.h:

private:
    void OnOK(Platform::Object^ sender,
              Windows::UI::Xaml:RoutedEventArgs^ e);

In Mainpage.xaml.cpp:

void MainPage::OnOK(Platform::Object^ sender,
                    Windows::UI::Xaml::RoutedEventArgs^ e)
{
    String^ strInput = MyText->Text;
    String^ strMessage;
    if ( !wcsicmp( strInput->Data(), L"hello, world") )
        strMessage = L"Well done!";
    else strMessage = L"Try again";
    auto boxOK =
        ref new Windows::UI::Popups::MessageDialog(strMessage);
    boxOK->ShowAsync()->Start();
}

The code is fairly straightforward. The identifier MyText references the edit control. A MessageDialog displays a message depending on MyText content.

enter-hello-world

When the user presses OK, the MessageDialog is displayed.

Simple-metro-messagedialog

A Metro app is not supposed to exit. To close it anyway, use Visual Studio menu Debug/Stop debugging.

 

Customize MessageDialog

MessageDialog can be customized by adding buttons.

Each button in a MessageDialog is represented by a UICommand object, which combines a button caption and an event handler. The event handler method is called when the button is pushed.

UICommand^ btnYes = ref new UICommand(L"Yes I do",
    ref new UICommandInvokedHandler(this, &MainPage::OnYes));

Method MainPage::OnYes is called when the user pushes the button in the MessageDialog.

Here is the full MainPage.xaml.cpp code. A custom MessageDialog with two custom buttons is displayed:

using namespace Windows::UI::Popups;

void MainPage::OnOK(Platform::Object^ sender,
                    Windows::UI::Xaml::RoutedEventArgs^ e)
{
    String^ strInput = MyText->Text;
    if ( !wcsicmp( strInput->Data(), L"hello, world") )
    {
        // Create a simple default MessageDialog
        MessageDialog^ boxOK =
            ref new MessageDialog(ref new String(L"Well done!"));
        boxOK->ShowAsync()->Start(); // Display MessageDialog
    }
    else
    {
        // Create a MessageDialog with 2 buttons and 2 event handlers
        MessageDialog^ boxAsk =
            ref new MessageDialog("Do you want the solution?",
            L"You did not enter the magic phrase!");

        // Add buttons "Yes" and "No"
        UICommand^ btnYes = ref new UICommand(L"Yes I do",
            ref new UICommandInvokedHandler(this, &MainPage::OnYes));
        UICommand^ btnNo = ref new UICommand(L"No I don't",
            ref new UICommandInvokedHandler(this, &MainPage::OnNo));
        boxAsk->Commands->Append(btnYes);
        boxAsk->Commands->Append(btnNo);

        boxAsk->DefaultCommandIndex = 1; // Default btn index in Commands vector
        boxAsk->ShowAsync()->Start(); // Display MessageDialog
    }
}

void MainPage::OnYes(IUICommand^ command)
{
    // Give solution to user
    MyText->Text = L"hello, world";
}

void MainPage::OnNo(IUICommand^ command)
{
    MyText->Text = L"";
}

Custom-metro-MessageDialog

Source code project for C++/CX and for C# is available at http://code.msdn.microsoft.com/windowsapps/MessageDialog-sample-243ce23e

Installing Windows 8 on a Windows 7 tablet for dummies

Lire cet article en français 

A preview of Windows 8 for developers is available for download since a couple of days. Build Windows conference participants got a Samsung touch tablet with Windows 8 and Visual Studio 11 preinstalled. These lucky guys can already use Visual Studio 11 to create Metro applications.

The tablet

If you did not attend the conference, you don’t have a Windows 8 tablet. There is a solution however if you too want to create new Windows 8 Metro app. Microsoft Labs test Windows 8 on some Windows 7 touch hardware, the list is available on Windows Building 8 blog.

Here are some of the touch systems they use:

  • HP Elitebook 2740p and 2760p convertible
  • ASUS tablet EP121
  • Dell Inspiron Duo Convertible
  • Lenovo X201, convertible x220t
  • 3M M2256PW 22 “display

They are touch laptops, except the Asus EP121 which is a tablet. Asus EP 121 tablet has 12″ touch screen, pen, Intel Core i5, 4GB RAM, SSD 64 GB, Bluetooth keyboard, two USB 2 ports, HDMI output for an external monitor … This tablet is widely available, and costs almost 1250 US$, 990 € or 900 UK £.I feel lucky, I buy one Asus EP 121 tablet at the nearest reseller, cross my fingers and hope I am able to install Windows 8 on it.

As I unpack the tablet, I download the ISO file of the 64-bit version of Windows 8 with integrated development tools. The download site says the 5 GB ISO file must be burnt on a dual-layer DVD. Then boot the device from the DVD to start installation.

Problem is the tablet does not have a DVD player. I must use an external USB drive.

 

Prepare an external USB drive to install Windows 8

If your tablet / laptop has a DVD player, you don’t have to use a USB drive. Just burn the ISO file on a dual layer DVD. If you don’t have a DVD player, you have no choice but to use a USB drive.

Note: a 8GB USB stick might be OK, but some people had problems using a USB stick. External USB drive seems to be recommended.

In searching the Web, several pages tought me that the disk must be NTFS formated and bootable. It should not contain other data, so use an empty drive.

I’ve found references to Windows 7 USB/DVD download tool which might be able to setup a bootable USB drive from an ISO file, but it didn’t work for me. The tool couldn’t recognize my WD external drive.

Preparing the USB drive to install Windows with 8 is done in three steps.

1. First step is to format in NTFS.

Windows 7 Disk Management Utility allows you to:

  • Format the drive in NTFS
  • Mark the disk as Active (right click on disk, then click “Mark Partition as active”)

2. Second step is to make the drive bootable by copying the boot sector from Windows 8 ISO to the USB disk.

For that, mount the Windows 8 ISO file as a virtual disk. Run a DOS prompt in administrator mode (type cmd in Windows 7 start menu, then press Ctrl + Shift + Enter). Go to the BOOT folder of Windows 8 ISO and type the command:

Bootsect /NT60 I:

Where I: is the drive letter of the external USB drive. Replace it with the letter of your USB drive of course.

3.Last step is to copy all files from the Windows 8 ISO to the USB drive.

Installation

Plug the USB drive in the tablet and power it on. The installation program starts automatically.

You must first make Microsoft lawyers happy by reading the license agreement carefully (There won’t be a quiz later).

At some point, the installation program asks if you want to keep your data:

In fact, the previous version of Windows, programs and user accounts will not be deleted, but moved to a Windows.old folder. This is a new installation of Windows, not an update.

The installation process went without any problem. Hats off to Mr. Microsoft.

 

The tablet restarts, and still ask me if I want to install Windows 8. It’s time to unplug the USB drive and reboot.

The tablet configures itself. Then you must enter a Windows Live account name. It will be your username on the tablet. Windows settings and user data are automatically synchronized with your Skydrive account (you can disable that). Should I use Windows 8 on another PC, I could retreive my configuration automatically.

Then Windows Metro start screen appears.

Visual Studio 11, Expression Blend 5, Windows 8 SDK and other tools are preinstalled. Cool.

The setup process went really smoothly. All devices were automatically recognized (touch screen, pen, sound, HDMI external display, USB, card reader, wifi, network, file sharing, media center streaming, webcam …) except the external Bluetooth keyboard. Tablet orientation detection doesn’t work either.

To get support for bluetooth, I had to download the Windows 7 bluetooth driver on Asus website, and install it in compatibility mode. It works fine under Windows 8. The keyboard now works fine.

Metro UI is quite pleasant to use, more than I expected. My first impression is quite good. It will be a lot of work to port applications to this platform.

And voila!

The lucky guys who went to Build Conference in Los Angeles are not back yet. It’s not too late to grab a Windows 7 tablet and install Windows 8 on it before you see them ;)

Oh, by the way, Visual C++ 11 is waiting for me!

New Windows 8 application architecture

There are now two application types:

  • New hotness, Metro style applications, developed with WinRT.
  • Old and busted apps, using outdated dev techniques like C++/COM/Win32 or C#/Silverlight.

architecture-app-windows-8

(by http://www.riaservicesblog.net/Blog/post/Microsofts-New-Mullet.aspx)

We all know that the world is not black or white, things are not good or evil. WinRT API are available as COM objects! This 20-year-old technology is used for the building blocks of WinRT! So, WinRT is not that modern finaly! :D

Build Windows : C++ sessions

Build Windows proposes 15 sessions for C++ developpers! Video will be available shortly.

Herb Sutter, one the the key C++11 architects, is speaker of two conferences:

Using the Windows Runtime from C++

Writing modern C++ code: how C++ has evolved over the years

Other C++ talks :

Improving software quality using Visual Studio 11 C++ Code Analysis

A lap around Visual Studio 11 Express for Metro style apps using C++

Under the covers with C++ for Metro style apps

Tips and tricks for developing Metro style apps using C++

Bringing existing C++ code into Metro style apps

Taming GPU compute with C++ AMP

Tips & tricks: how to use Visual Studio to the fullest

Lessons learned designing the Windows Runtime

Metro style apps using XAML: what you need to know

Building Metro style apps that print

Lap around the Windows Runtime

Windows Runtime internals

What’s new in Visual Studio 11

Some conferences about DirectX and graphic hardware acceleration, not specific to C++ dev :

A lap around DirectX game development tools by Boris Jabes !

Direct3D Graphics in Metro Style Apps and Games

Tuning GPU usage for any form factor

Introduction to DirectX for Metro style apps

Achieving high performance 2D graphics with Direct2D

C++ developpers have to learn XAML, Windows 8 interface definition langage:

A deep dive into Visual Studio 11 Express for designing Metro style apps using XAML

Metro style apps using XAML: what you need to know

Tips and tricks for developing Metro style apps using XAML

Unit testing your metro style apps built using XAML

Build advanced touch apps in Windows 8

WinRT makes it easy to be connected:

Debugging connected Windows 8 apps

Power your app with Live services

The complete developer’s guide to the SkyDrive API

Connecting and sharing with near field communication

Building Windows runtime sockets apps

Making apps social and connected with HTTP services