Querying uptime in C
This is definitely stupid on what I have been upto with this. I will try to make the blog as much direct as I can and not make a story out of it !
A bit of context: I was working on Lumi, released v2.0 that had network information and changed the project name from Winbun64 to Lumi - that was version 3.0 !
Now I thought of showcasing it so I wrote a program myself that uses Lumi to fetch the info and log it in the console. I asked GPT to write me a simple C function that takes milliseconds and formats it in month, day, hour, minute, seconds format and since it was a basic arithmetic function I didn't bother to check it and that caused inaccuracies in uptime.
That was my first mistake of not verifying the AI code and that was very likely the reason of all this ! I thought what can be the issue and researched a bit and my point of reference was fastfetch.
While researching I actually had quite a lot of responses from Brave Search AI, the issue with Brave's AI is that it is too direct and can hallucinate very confidently, Now idk from where it did a search and said fastfetch used GetTickCount64() before but then moved to NtQuerySystemInformation as someone said their uptime was only 3 days but the API reported 10 days ! And like a stoopid person I believed that without my own verification. Same props go to Gemini too. So I was convinced that GetTickCount64() really had some inaccuracy problem and I shifted to NtQuerySystemInformation. Now this one is not a public function and is I can say "semi-documented". View the Doc here. Or maybe the doc is perfect the problem is reading WinAPI docs feels like reading ancient Greek (not like I have read ancient Greek), so I heavily relied on AI explanation on what the API does !
I understood the whole concept of NtQuerySystemInformation not just blindly paste anything. Below is the code for reference what I had:
#include <windows.h>
#include "lumi.h"
#include "lumi_functions.h"
typedef struct _SYSTEM_TIME_INFORMATION {
LARGE_INTEGER BootTime;
LARGE_INTEGER CurrentTime;
LARGE_INTEGER TimeZoneBias;
ULONG CurrentTimeZoneId;
ULONG Reserved;
} SYSTEM_TIME_INFORMATION;
typedef LONG (WINAPI* pfnNtQuerySystemInformation)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
void getUptime(LUMI* lumi){
lumi->uptime = 0;
HMODULE hNTDLL = GetModuleHandleA("ntdll.dll");
if(!hNTDLL) return;
pfnNtQuerySystemInformation NtQuerySystemInformation =
(pfnNtQuerySystemInformation)GetProcAddress(hNTDLL, "NtQuerySystemInformation");
if(!NtQuerySystemInformation) return;
SYSTEM_TIME_INFORMATION timeInfo = {0};
ULONG returnLen = 0;
LONG status = NtQuerySystemInformation(3, &timeInfo, sizeof(timeInfo), &returnLen);
if(status == 0 && timeInfo.CurrentTime.QuadPart > timeInfo.BootTime.QuadPart){
LONGLONG diff = timeInfo.CurrentTime.QuadPart - timeInfo.BootTime.QuadPart;
// diff is chunks of nano seconds (each chunk is 100ns) !
// Divide the div by 10,000,000 to get seconds
// printf("Uptime: %llu\n", (unsigned long long)(diff / 10000000LL));
lumi->uptime = (unsigned long long)(diff / 10000000LL);
}
else {
lumi->uptime = 0;
return;
}
}
Here is an explanation of what I understood of this whole thing (there can definitely be flaws in my understanding).
Since this is not a public structure and function we create a custom struct that matches the layout of what we expect the function populates. Also we create a typedef'ed version of a function pointer that will hold the address of the function itself !
Next we retrieve a HANDLE to a loaded .dll called ntdll.dll, HANDLE is basically like an opaque object and here we get a HANDLE to that specific loaded .dll !
Next what we do is that we create a function pointer variable that has the exact signature of the function we need from the loaded .dll. To get the function address we call GetProcAddress passing the HANDLE to the .dll and the name of the function we need !
GetProcAddress returns a generic FARPROC pointer, this pointer contains the address of the needed function but since the .dll has many functions a generic pointer type is returned because it doesn't know which function we want. Then we cast that address to the type of the function pointer we defined earlier ! We then initialize a variable for our custom struct and call the function that will populate our struct.
NtQuerySystemInformation(3, &timeInfo, sizeof(timeInfo), &returnLen); This is the function call, 3 here is the information class basically its like says the API which kind of system information is to be retrieved. Class 3 retrieves SystemTimeOfDayInformation, view reference.
Next we pass out struct by address, size of it and the returned length that too by address !
Next we check status here 0 indicates success and the other check is basically a, if current time is greater than boot time we dont go through ! After that we do a simple subtraction with timeInfo.CurrentTime.QuadPart - timeInfo.BootTime.QuadPart; Looks pretty self explanatory so I didn't look up much of it and it kinda made sense to me current time - boot time should have gave me the computer awake timing.
Now Windows gives out these in 100ns chunks so basically if Windows says diff = 100 its saying 100 chunks of 100ns so 100 x 100 = 10000ns in total ! With that calculation in mind,
diff / 10000000LL; This thing is performed, this converts those chunks into literal seconds.
I was hoping that with this I can get the proper uptime with no inaccuracies but I was mistaken and misled. Upon verifying even more I found out fastfetch never used GetTickCount64 or NtQuerySystemInformation, again I can be wrong here but I looked at the actual source code but didnt find implementations of the same. The code was dense so I could have missed it maybe.
In Lumi v3.2 I though its okay I can keep both the boot time and GetTickCount64() for the total uptime.
[!NOTE]
GetTickCount64()doesn't reset on computer shutdown (if fast startup enabled) hibernation or sleep. It only resets on restart or if fast startup is disabled it resets on shutdown !
This was the biggest concept I missed while the AI kept confidently mixing things up !
The whole issue was on me, I blindly took the word for it without self verification.
As said in v3.2 I kept both where uptime queried NtQuerySystemInformation and kernelUptime queried GetTickCount64(). Now I was okay with v3.2 having both ! But I wanted to test if keeping both made any difference but oh lucky me I had Fast startup was disabled on all my systems. Regardless I actually turned on fast startup on my Windows 10 (22H2 build 19045) machine and then tested with Fast startup and sleep too. I expected both to be different ! But surprisingly both gave same results. NtQuerySystemInformation and GetTickCount64 gave same results which was strange (or maybe my subtraction was off ? IDK !)
Now just for clarity here is what I expected:
NtQuerySystemInformation should only give time elapsed since last system boot basically time passed since last power on and it should get reset on shutdown and it also should not count time the system spends in sleep or hibernation. Whereas, GetTickCount64 would account for everything and only resets on restart of shutdown with fast startup disabled !
I wanted to confirm this properly but honestly I didnt have much luck MS docs so I took another bet on AI this time GPT and Claude and their answers were satisfactory. They said since the API is undocumented and its closed source they cant verify what exactly does querying NtQuerySystemInformation (Class 3) gives out.
And at this point I realized that GetTickCount64 did my job flawlessly and I was stoopid enough to blindly believe an AI that it gave correct answer and lesson is learned. I reverted back to only using a single uptime field and queried GetTickCount64 only ! Version 3.3 is up !
And just in case anyone that read all this rant of mine and think I am flawed u are welcome to correct me because I am here to learn !