Blog | Статии

My New Logging System for C++

I’ve been experimenting lately with better ways to get good logging under C++.

This is what I wanted to achieve when I started my latest project:

  • Stack trace, similar to what you get from C# and .NET in general
  • Easy to use
  • Work with HRESULT-s, and Windows’ GetLastError()

HRRESULTs are COM’s way of handling exceptions in an easy to marshal cross-process manner. They behave exactly as exceptions, most of the time – once you FAIL(hr), you usually return hr, this propagating the exception down the calling methods. Thus, if we recorded each FAIL(hr), would easily get a .NET-like stack trace.

.NET stack traces contain another useful feature (besides the calling stack itself): it tells you where you failed: method name and source code location. In C++, we have __FILE__, __LINE__, and the non-standard __FUNCSIG__.

Now, my projects at work are Windows-based, and, unfortunately, Microsoft implemented UNICODE way back when it was believed that all there is can be encoded in 16 bits. That is, all UNICODE text is UTF16LE encoded, and you have to use wchar_t-s and prefix your strings with L.

Since __FILE__ and __FUNCSIG__ are normal strings, we will need a few macro helpers to widen them:

#define WSTRIGIFY(x) L#x
#define WSTRINGIFY_STRING(x) L##x
#define WSTRINGIFY_MACRO(x) WSTRIGIFY(x)
#define WSTRINGIFY_STRING_MACRO(x) WSTRINGIFY_STRING(x)

#define __WFILE__ WSTRINGIFY_STRING_MACRO(__FILE__)
#define __WLINE__ WSTRINGIFY_MACRO(__LINE__)
#define __WFUNCSIG__ WSTRINGIFY_STRING_MACRO(__FUNCSIG__)

Remember, stringify-ing a macro is the process of getting the compiler expand macro arguments as string literals. Since we don’t want string arguments to be expanded as L"\"some value\"", we need the additional WSTRINGIFY_STRING/WSTRINGIFY_STRING_MACRO pair.

Now that we have the wide string versions of __FILE__, __LINE__, and __FUNCSIG__, we can combine them in a single literal (the C/C++ compiler combines adjacent string literals):

.. which would output something like:

d:\dev\mmkeys2\utilities.cpp(140): long __cdecl InitializeCommonControls(void)
  Expression "::InitCommonControlsEx(&cc)"

Notice that we copy the Visual Studio syntax of file.cpp(line): – if we print this to the Output window and double-click on the line, Visual Studio’s editor will jump right into utilities.cpp at line 140!

To take things one step further, it’d be nice to print out the failed HRESULT and the text representation of the message via FormatMessage:

#define LOG_HR(expr, hr) LogErorWithHresult(LOG_HR_LOCATION(expr,hr), hr)
#define ASSERT_HR_CODE(expr, code) { HRESULT hr = expr; if (FAILED(hr)) { LOG_HR(expr, hr); return code; } }
#define ASSERT_HR(expr) { HRESULT hr = expr; if (FAILED(hr)) {  LOG_HR(expr, hr); return hr; } }
#define ASSERT_WIN(expr) if (!(expr)) { HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); LOG_HR(expr, hr); return hr; }
#define ASSERT(expr, code) if (!(expr)) { LOG_HR(expr, code); return code; }

void LogErorWithHresult(const wchar_t* location, long hresult);
void LogErrorMessage(const wchar_t* message);

Once we’ve defined LOG_HR_LOCATION, the rest is easy:

  • ASSERT checks if an expression evaluates to false, and returns a custom error code
  • ASSERT_WIN uses GetLastError as return code
  • ASSERT_HR uses whatever expr evaluates to as return code
  • ASSERT_HR_CODE is the same as above, but returns a custom error code

All macros assume that your methods have the standard COM signature: HRESULT SomeMethod(/*args...*/). As mentioned before, the whole call-stack idea rests on the assumption that you follow the COM error handling model – that is, you don’t use C++ exceptions.

void LogErorWithHresult(const wchar_t* location, long hresult)
{
  const size_t SYSTEM_MESSAGE_LEN = 100;
  const size_t FINAL_MESSAGE_LEN = 200;

  wchar_t systemMessage[SYSTEM_MESSAGE_LEN];

  DWORD len = ::FormatMessage(
    FORMAT_MESSAGE_FROM_SYSTEM
    | FORMAT_MESSAGE_IGNORE_INSERTS,
    nullptr, hresult, 0, systemMessage, SYSTEM_MESSAGE_LEN, nullptr);

  wstringstream finalMessage;
  finalMessage 
    << location     
    << L"\n\tHRESULT 0x" << hex << setw(8) << setfill(L'0') << hresult
    << L": " << systemMessage;

  LogErrorMessage(finalMessage.str().c_str());
}

LogErorWithHresult is quite straightforward – it extracts the system message string and appends to the output of LOG_HR_LOCATION.

void LogErrorMessage(const wchar_t* message)
{
  ::OutputDebugString(message);

#if defined(_DEBUG)
  if (::IsDebuggerPresent())
  {
    ::DebugBreak();
  }
#endif
  // write to file, etc...
}

LogErrorMessage is the heart of the logging system: you can plug in writing to the Output window, appending to a log file, for example.

For a conclusion, I’ll give the output of a sample usage of the logging API

HRESULT InitializeCommonControls();
int Run(int cmdShow);
//...
HRESULT Window::MapGlobalHotkeys()
{
  ASSERT( m_winHandle, E_ILLEGAL_METHOD_CALL );

  ASSERT_HR( RegisterGlobalHotkey(Hotkey_ToggleVolume, VK_F10) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_VolumeUp, VK_F12) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_VolumeDown, VK_F11) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_PlayPause, VK_HOME) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_Stop, VK_END) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_PlayNext, VK_NEXT) );
  ASSERT_HR( RegisterGlobalHotkey(Hotkey_PlayPrevious, VK_PRIOR) );

  return S_OK;
}

HRESULT Window::RegisterGlobalHotkey(int id, UINT vk)
{
  ASSERT( id >= First_Hotkey && id < Count_Hotkeys, E_INVALIDARG );

  ASSERT_WIN( FALSE != (m_isMappingRegistered[id] =
    ::RegisterHotKey(m_winHandle + 5, id, MOD_ALT | MOD_CONTROL, vk) )
  );

  return S_OK;
}

//..

int Run(int cmdShow)
{
  ASSERT_HR_CODE(InitializeCommonControls(), 1);

  Window window;
  ASSERT_HR_CODE(window.Create(), 1);
  ASSERT_HR_CODE(window.Show(cmdShow), 1);
  ASSERT_HR_CODE(window.MapGlobalHotkeys(), 1);

  MSG msg;
  while (GetMessageW(&msg, nullptr, 0, 0))
  {
    TranslateMessage(&msg);
    DispatchMessageW(&msg);
  }
  return static_cast(msg.wParam);
}

becomes

Window.cpp(162): long __cdecl Window::RegisterGlobalHotkey(int,unsigned int)
  Expression "0 != (m_isMappingRegistered[id] = ::RegisterHotKey(m_winHandle + 5, id, 0x0001 | 0x0002, vk) )"
  HRESULT 0x80070578: Invalid window handle.

Window.cpp(145): long __cdecl Window::MapGlobalHotkeys(void)
  Expression "RegisterGlobalHotkey(Hotkey_ToggleVolume, 0x79)"
  HRESULT 0x80070578: Invalid window handle.

MMKeys2.cpp(37): int __cdecl Run(int)
  Expression "window.MapGlobalHotkeys()"
  HRESULT 0x80070578: Invalid window handle.

Of course, it can still be expanded (as in: don’t print the expression/hresult lines every time), but I believe this is a very good start!

C++, Win32 and Memory Issues

It’s been ages since I’ve done something in C++, but with the new developments – especially c++11 (and to do something different than what I do at work), I’ve decided to do my own Tetris clone.

I’ve had very little free time, so the project’s mostly moved forward quite slowly. One day, I decided to port it to Ubuntu via SDL. The approach is rather ineffective – with two separate code paths – because I decided to keep the D2D code path intact.

In order to do this, I’ve utilized the pimpl idiom. This basically means that the class is separate in public interface and implementation details, which become opaque.

Before the pimpl refactoring, I used to have this in my Win32 code:

m_window = ::CreateWindowExW(exStyle, APP_CLASS, APP_TITLE,
    windowStyle, x, y, width, height, HWND_DESKTOP, nullptr, m_instance,
    reinterpret_cast<void*>(this));

… and in WndProc, the usual shenanigans:

if (message == WM_CREATE) {
  CREATESTRUCT* createData = reinterpret_cast<CREATESTRUCT*>(lparam);
  Game* game = reinterpret_cast<Game*>(createData->lpCreateParams);

  ::SetWindowLongPtr(window, GWLP_USERDATA,
#ifdef _WIN64
    reinterpret_cast<LONG_PTR>(game)
#else
    reinterpret_cast<LONG>(game)
#endif
    );
  return 0;
} else {
  Game* game = reinterpret_cast<Game*>(::GetWindowLongPtr(window, GWLP_USERDATA));

Now, the problem is that with the move to pimpl, this changes its meaning… now the pointer we pass to CreateWindowEx is Game::Impl, instead of Game, while I still treated it as Game in WndProc. Of course, being pampered by managed languages such as C# and Java, it took me some time to actually find the problem 🙂

Conclusion: treat your memory with respect!

Българското образование и проблемите в него

Днес видях поредния пост във Facebook, който едва ли не хвали нашата образователна система… и нещо не издържа в мене. Реших, че искам да напиша мислите, които съм обсъждал с приятели.

Въпреки, че съм имал късмета да се запозная с много кадърни и готини учителки, далеч не всички са такива.

Освен това, дори и в елитните училища, където се предполага, че след тежък прием ще има подбор на учениците, с което да се вдигне средата, далеч не всички реално са там, за да учат.

В образованието е въпрос на голям късмет да попаднеш на съмишленици (т.е. да има други, които се вълнуват от същите неща и това, че си умен, да не е повод за подигравка) и преподаватели, които не ти се сърдят/карат/комплексират, ако задаваш въпроси и искаш да научиш повече.

Да, има ученици, които са извадили този късмет. Но в повечето случаи, по мой опит, нито на родителите, нито на учениците, нито на преподавателите в голямата им част им пука. Най-вече след началния етап на образованието.

В университета нещата стават още по-зле – където по-голямата част нито работят, нито учат, а клюкарството, пиенето на кафе, играенето на карти и люпенето на семки се превръщат в основни занимания и единствена причина да се ходи въобще в университета.

Като цяло образователната ни система е архаична и беше описана добре от един мой частен учител по математика: докато в чуждите системи правят децата еднакво кадърни – както по-умничките, така и по-тъпичките; тука се хващат най-умничките и се развиват. Ако имат късмет, де. А за по-тъпичките…

По тази архаична систма децата нямат никакъв избор. Винаги им се казва какво да правят. Дисциплината над всичко. Тишина! И тъй като на повечето родите им пука само на думи, децата се превръщат в хора, които не знаят какво искат (т.е. отделят ли време да видят как се справят децата с материала? помагат ли им? карат ли ги да учат допълнително? карат ли ги да са любопитни като им говорят за неща, които са интересни, но децата им все още не могат да разберат напълно? разправят ли им интересни неща, които да ги карат да искат да научат повече – за каквото и да било – от коли до научна фантастика?).

Огормен проблем е, че на децата много рядко им се казва за какво учат това или пък това другото. Особено зле е положението в университета, където преподавателят просто сменя 200 слайда на PowerPoint за 40 минути пред 200 човека в аулата и си тръгва.

Още от ранна възраст трябва да им се казва, че има едно сигурно нещо в живота: ако искат да мият чинии или да правят бургери цял живот – да, не трябва да учат. Но ако искат да правят нещо смислено в живота си едно е сигурно: нещата се променят много бързо и те винаги ще трябва да продължават да учат. Така че те са на училище, за да се научат да мислят самостоятелно, да правят избори и най-вече – да намерят най-ефективния за себе си начин да учат нови, непознати неща.

Вместо да зубрят датите на това или онова събитие по исторя… защо да не видят причините, които са довели до него? Имах една отвратителна учителка по история, която само се интересуваше от имена и дати – но не и от смисълна на историята – защо дадени неща са се случили, случвали ли са се преди това, какво можем да направим, какво означава това за нас тук и сега? Дали това и това се случиха, заради нещо, което се е случило преди?

Вместо да се зубри, че в Ямбол преди 20 години е имало такъв-и-такъв завод, защо не се учат децата за смисъла на парите? Какво всъщност са парите? Какво означава “дълг”? Какво става с парите ми, когато ги вкарам в банка? Защо получавам такава и такава лихва като тегля заем и защо получавам такава и такава лихва като вкарвам пари на влог? Защо не се обясняват основните начини по които държавата взема пари – облигации и данъци? Защо им се покаже какво е това макро- и микро-икономика в най-общ план? И след това да се обсъдят неща от истинския живот (като например кризата в Гърция) и всеки да си каже мнението защо според него се е стигнало до там? Какви са теоретичните начини да се излезе от нея? Правилнот нещо ли направи ЕС? Плюсовете и опасностите на хиперинфлацията? Познават ли нещо подобно? Каква е приликата и разликата с кризата в България през 96-97ма?

Да не говорим за преразказването. Това е супер безсмислено за след пети клас. Можеш ли да пишеш? Да. Можеш ли да запомниш пет изречения? Да. Разбираш ли го? Тук децата не се карат да мислят самостоятелно (за по-горните класове важи супер много). Как протичат някои от часовете по литература? Учителката диктува своя анализ, който трябва да бъде запомнен, за да може след това да бъде възпроизведен. Кому е необходимо това? Учениците трябва сами да стигнат до своите изводи. Нали уж трябва да се учим от грешките си? Или пък, да – забравих – да грешиш е грях ако съдиш по поведението на не малка част от преподавателите! И още по-важно: трябва да се научат да защитават мнението си. Ако ще и за всички да е очевидно, че то има грешки – защото това е едно много важно умение в живота.

Системата на гимназията също е прекалено остаряла. Вместо да се карат децата да ровят в библиотеките/интернет и да се учат сами да търсят и пресяват информация, всичко им е дадено на готово. Вместо това имаш няколко странички в учебник, който я е обновен последните 30 години, я не. Да не говорим за плачевното състояние на историята, където често се преподават непълни и грешни неща. А по моите спомени от края на IIта световна до днес има една черна дупка. Което прави децата да бъдат изключително лесно манипулирани от политиците, като им се внушават неистини и от носталгично-настроени роднини, и от хора, които са били ощетени от режми. Например – как, по дяволите! – се е стигнало до там, че в началото на 20ти век водим непрекъснато войни, за да се обединим, а извъднъж Македония е самстоятелна държава, която ни мрази? Не съм против правото им на самоопределяне – а престъпното мълчание за историческите причини, поради които се е стигнало до там.

Има и някакво маниакално желание да се спазват правила. От този до този клас пишем съчинение-разсъждение. После това става интерпретативно. След няколко преобразувания се получава есе. Ама и там има фетиш към формата – трябва задължително, ама задължително – и това е много важно! – да спазваш формата теза-изложение-заключение. Докато в нормалния свят есето е най-свободния начин да напишеш мненито си по даден въпрос – или просто да напишеш какво мислиш.

Има още какво какво да напиша, но като че ли ми свърши енергията 🙂 Ако някой друг път имам желанието и енергията, бих написал какво бих променил – особено в гимназията и университета.

The birth of FooTicTacToe

I haven’t been doing a lot of C++ in the past few years, and with the arrival of Windows 8 and the new C++11, I decided it is due time to refresh my knowledge! The APIs in particular that I want to use are Direct2D, DirectWrite and WIC.

Since I’m working in a start-up, I get to see (and participate in) the whole process – from planning, to development, to deployment, to support. One thing that’s been hurting us a lot is deploying our software to clients. Every dependency – whether it would be the Kinect Runtime, XNA runtime or the .NET framework – introduces a whole new set of problems.

For example, Microsoft do not provide a silent installer for the Kinect Runtime – so when you want your clients to install your software, they have to install 2 programs instead of one.

In Windows 8, when installers need to restart the computer, users do not get asked whether they want to restart now or later: the PC restarts automatically (even if there is a setting about it, auto-restart seems to be on by default). This means that your installer has to be resilient to this kind of impolite behaviour. And that happens when you make your installer start-up on log-in. Yet programs that require administrator privileges (such as installers) cannot be added to the start-up items. To solve that problem, the happy developer must split the setup in two: one part checks of the state of the installation that launches the second part, and another part that requires administrator privileges to actually do the work. And the list goes on and on…

As you can see, a single dependency in your app adds a long list of problems for your installer. That is why I wanted to try out purely native development on a pet project and thus reduce the dependencies to just the C++ run-time. Also, it would be a nice testbed to see if it is feasible to release future products that are written in C++.

Usually, when I’m learning a new technology, I implement a game of tic-tac-toe. The mechanics are simple, but it does cover the basics:

  • loading and drawing textures
  • game loop
  • basic state machine

Now that we have the rationale, let’s list the things I want to have (and thus test) in the game:

  • Full-screen game in release, windowed in debug build
  • Intro screen where a simple picture/logo fades out – to test out animations and state machine
  • Main menu with options to start a new game or quit
  • In-game (gameplay) screen
  • Pause screen
  • Game over screen

Even a simple game of tic-tac-toe can provide a lot of work, especially if the goal is to have a polished product. Aside from the features, I’ve also taken the following decisions:

  • I will avoid C++ exceptions and I will use HRESULT-s/nullptr instead. The code will be ugly, but it will be logical and predictable.
  • I will not use a smart COM pointer. There is no reason to include ATL as a dependency, and I do not like the default _com_ptr_t. Plus, this will be a very small game, and most resources’ lifetime is bound either to the game itself or to a state, so they will have to be managed manually anyway (unless I write a content framework, which I won’t).
  • I will minimize the use of c++11 pointers. The reasoning is the same as before: the ownership of resources is usually quite well defined, and most pointers will probably be to COM objects anyway.
  • I will use C++11 features without backwards compatibility (e.g. vector<shared_ptr<GameState>>). Compilers aren’t going back in time, and some of the new features do increase productivity.
  • I will use Microsoft-specific features – e.g. __uuidof and #pragma once. This project is solely based on Windows APIs, and is never going to be ported to another compiler or platform; if a feature saves me some time – that’s fine by me.

Hello, v2

It’s been quite a while! I do intend to write more regularly, but I didn’t have the time. I intend to correct this!

A lot has happened! I graduated the Technical University of Sofia, and also quit Telerik to pursue an MSc in the UK. After long deliberation, I chose the University of St Andrews. And now I’ve almost graduated that, as well 🙂

Currently, I’m writing my dissertation. The working title is “An IDE for Grasp ADL”. Well, apart from IDE, the rest is probably gibberish for most people 🙂 ADL stands for “architecture description language”. It is an attempt in academic circles to come up with an easy formal description for software architecture (which is yet another field). Grasp is one of the (really) many such languages. What sets it apart is that it is currently being developed at the University of St Andrews. The advantage for me is that I have easy access to the language creator, Lakshitha de Silva.

The project itself is going to be written in Java, using Eclipse as a platform for development. For the (unlikely) interested souls that randomly stumbled on this post, I’ve set-up a public repository for the project on Google Code. I’m still studying the Eclipse platform, but it seems very well engineered, indeed. IBM do seem to be very good at writing APIs!

I plan on writing about my impressions from the academic work on software engineering, software architecture, the education in the UK, and, of course, my experience in writing the IDE. And, of course, the occasional random rambling!