Move to Parent

This post is inspired by a discussion regarding a coding snack done by lanux128 on DonationCoder. A user requested a tool to add a context menu entry that would copy selected files and folders to the parent folder.

Moving folders is one of those tasks that appear trivial. But as always, the devil is in the details.

To keep it simple, we will assume regular files and folders in a filesystem where paths are unique. The problem we will look at is: Given absolute paths Src and Dst (where Dst is not equal to, or a subfolder of Src), move the contents of Src to Dst.

The first solution that comes to mind is to move files and folders recursively. In pseudocode it would be something along the lines of:

MoveSimple(Src, Dst)
{
    // loop through files/folders in Src folder
    for each Name in Src
    {
        if Name is a folder
        {
            // create folder in Dst
            mkdir Dst\Name
 
            // recursively move contents of subfolder
            MoveSimple(Src\Name, Dst\Name)
 
            // remove subfolder, which is now empty
            rmdir Src\Name
 
        } else {
 
            // move file to Dst
            move Src\Name Dst\Name
        }
    }
}

This works — well, almost.
Continue reading

Long Division

Integer types with at least 64 bits have been a part of the C standard for a while now (they were added in C99, and were a standard extension in many 32-bit compilers before that). But have you ever wondered what exactly happens when you use them?

Consider the following function (substitute long long with __int64 if you are using an older version of Visual C++):

long long div64(long long x, long long y)
{
    return x / y;
}

let’s first have a look at what the VC 64-bit compiler gives us:

div64:
    mov   r8, rdx
    mov   rax, rcx
    cdq
    idiv  r8
    ret

Pretty much what you would expect, a little setup and an idiv instruction to perform the division. Now let’s try the VC 32-bit compiler:

div64:
_x$ = 8
_y$ = 16
    mov   eax, _y$[esp]
    mov   ecx, _y$[esp-4]
    mov   edx, _x$[esp]
    push  eax
    mov   eax, _x$[esp]
    push  ecx
    push  edx
    push  eax
    call  __alldiv
    ret

A little setup and .. a call?
Continue reading

System Up Time

A while ago I set out to write a little tool that would show the time a system had been running since the last reboot. It seemed like something that should be fairly easy to do, but as it turns out, it isn’t entirely straightforward.

The first thing that came to my mind was the GetTickCount function. It returns the number of milliseconds since the system was started, which fits nicely. There is one problem of course, the value returned is a DWORD, and that limits the time it can handle to about 50 days.

Microsoft realized this as well, and added GetTickCount64, which returns a 64-bit value instead. Unfortunately it only works on Vista+.

Looking more closely at the documentation for GetTickCount we see:

“To obtain the time elapsed since the computer was started, retrieve the System Up Time counter in the performance data in the registry key HKEY_PERFORMANCE_DATA. The value returned is an 8-byte value. For more information, see Performance Counters.”

The performance counters are a nice idea. Basically they provide a homogeneous interface to a multitude of counters that give information about how well the operating system or an application, service, or driver is performing.

The recommended way to access the data is through the PDH interface. You access the counters by specifying a counter path; a string that describes the computer, object, counter, and instance you are interested in.

Looking through the list of counters by objects for the ‘System’ object, we find the ‘System Up Time’ counter, which is exactly what we need.

So I wrote a test application to open a query, add the counter “\System\System Up Time”, collect the data, and display it. It failed. Apparently my computer did not have a ‘System Up Time’ counter.

Reading over the documentation for the PDH interface again did not help, but after some searching I ended up at this help article:

“Performance Data Helper (PDH) APIs use object and counter names that are in the localized language. Therefore, applications that use PDH APIs should always use the localized string for the object or counter name specification.”

Since I was running a Danish version of Windows, that explained the problem!

Following the steps outlined there, I found that the ‘System’ object has index 2, and the ‘System Up Time’ counter has index 674. With these indices in hand, you can then call the PdhLookupPerfNameByIndex function to get the localized names. Using the localized path “\System\Computerperiode uden afbrydelser” gave the desired result.

The choice to make the paths use localized names makes it somewhat more involved to use these functions. Also, this should have been described much more clearly in the PDH documentation, since it is quite possible for a developer using English Windows to read over the documentation like I did, and use a hardcoded path for a counter. This will work nicely while testing, and then fail if someone with a localized Windows uses it.

As an example, let’s take a look at the PsInfo tool. It is written by Mark Russinovich, one of the people behind Sysinternals.com, a site that specializes in advanced system utilities and technical information. He is also a coauthor of the Windows Internals book, describing the inner workings of Windows operation systems.

Running PsInfo on my system I get:

 PsInfo v1.75 - Local and remote system information viewer
 Copyright (C) 2001-2007 Mark Russinovich
 Sysinternals - www.sysinternals.com

 System information for \\removed:
 Uptime:                    Error reading uptime
 ...

Could it be? let’s have a little peek inside PsInfo.exe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
perform_query:
    push    esi
    lea     ecx, [esp+834h+szCounterPath]
    push    offset aSUT ; "\\\\%s\\System\\System Up Time"
    push    ecx
    call    sprintf?
    mov     ecx, [esp+83Ch+hQuery]
    add     esp, 0Ch
    lea     edx, [esp+830h+phCounter]
    push    edx
    push    0
    lea     eax, [esp+838h+szCounterPath]
    push    eax
    push    ecx
    call    PdhAddCounterW

Indeed, a hardcoded path to the counter using the English names.

Microsoft must have realized it could be a problem as well, because I found the function PdhAddEnglishCounter, added in Vista, which made me smile.

What Else Could Go Wrong?

JrDebugLogger is a very nice debug logging library. Much of it’s functionality is implemented through macros to allow it to be selectively left out when compiling. Along the way the author has had some interesting problems to solve, and this post is about one of them.

Assume we use the following macro:

#define DEBUGOUT if (debug_on) debug_stream

to allow us to perform debug logging with a stream-like interface. We can then do:

DEBUGOUT << "hello";

which expands to:

if (debug_on) debug_stream << "hello";

Now if the compiler knows that debug_on is false, it can leave out all code related to the debug logging, since it knows it will never be called. If it does not know the value at compile time, the resulting code will contain a very fast check around the call, allowing debug logging to be turned on and off dynamically with little performance overhead.

There is, however, an insidious bug lurking in the corner, waiting to jump at the user. Can you spot the problem? Think about it for a minute or two before reading on.

Consider this use:

1
2
3
4
if (i > limit)
    DEBUGOUT << "i too big";
else
    do_computation(i);

it expands to:

1
2
3
4
if (i > limit)
    if (debug_on) debug_stream << "i too big";
else
    do_computation(i);

This is valid C++, and compiled without warnings on the three compilers I tried. But who does that else belong to?

Let’s see what the standard says:

“An else is associated with the lexically nearest preceding if that is allowed by the syntax.”

This is from the C99 standard (6.8.4.1p3), which was the most clear, however statements to the same effect are present in the C++ standards.

So the above is equivalent to:

1
2
3
4
5
6
7
if (i > limit)
{
    if (debug_on)
        debug_stream << "i too big";
    else
        do_computation(i);
}

which was of course not the intention.

So how can we solve this without giving up the nice properties of the if? The simple solution is to give the if in the macro its own else:

#define DEBUGOUT if (!debug_on) ; else debug_stream

We now get the expansion:

1
2
3
4
if (i > limit)
    if (!debug_on) ; else debug_stream << "i too big";
else
    do_computation(i);

and the compiler will correctly associate the users else with his if. So it is equivalent to:

1
2
3
4
5
6
7
8
9
if (i > limit)
{
    if (!debug_on)
        ;
    else
        debug_stream << "i too big";
} else {
    do_computation(i);
}

Thanks to Jesse for the nice topic.