Skip to main content

Posts

Showing posts from 2013

Programming: Windows Threading Vs Linux Threading (Part 6)

A thread cleanup handler in Linux and Windows thread cancellation: A cleanup handler is a measure, used to deallocate a resource only if the thread exits or canceled. To register a cleanup handler, need to call pthread_cleanup_push() and pass a pointer to cleanup function and the void * argument. The pthread_cleanup_pop() function removes the routine at the top of the calling thread's cancellation cleanup stack and optionally invokes it (if execute is non-zero). The following sample code shows how a dynamically allocated buffer from a thread can be deallocated on canceling the thread in Linux. #include < pthread.h > #include < stdio.h > #include < string.h > #include < unistd.h >  char *pgArray = 0; /* Buffer allocation */ char * allocate_array (size_t size) {     return new char[size]; } void release_array (void *pArg) {     if(pgArray)     {         printf(...

Programming: Windows Threading Vs Linux Threading (Part 5)

Thread Cancellation in GNU/Linux : Today, I'm interested to explore how we can prepare thread in GNU/Linux to ignore thread cancellation. This is acvhieved with pthread_setcancelstate(). The signature of the function is: int pthread_setcancelstate(int state, int *oldstate);  The function is thread and signal safe. The function sets the cancel  state to one of PTHREAD_CANCEL_ENABLE or  PTHREAD_CANCEL_DISABLE and returns the old cancel state. Please see the second parameter. void *Print_Details(void *param) {      printf("This is secondary thread's entry...\n");      int oldState;      pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState);      sleep(1);      for(int i = 0; i < 10; ++i)      {           printf("Inside the secondary thread...\n");      }  ...

Programming: Windows Threading Vs. Linux Threading (Part 4)

Thread Cancellation is a way where it's necessary sometimes to terminate a thread explicitly from another thread. In Windows we have a Function, it's TerminateThread() The function signature : BOOL WINAPI TerminateThread(   _Inout_  HANDLE hThread,   _In_     DWORD dwExitCode ); This function is always asynchronous. It never guarantees that the thread will always terminate by the time the function returns. This function never cleans up a stack of destroyed threads. So, it's not recommended to use this function until it's absolutely necessary. Note : As mentioned by Jeffrey Richter, Microsoft designed this API purposely implemented this way to terminate thread(s). This ensures that other threads are still running and accessing the terminated threads stack will not get an access violation. So, by leaving the terminated threads stack in memory, other threads which are accessing the stack of the killed thread can continue to execute. In Linux we ...

Programming: Windows Threading Vs Linux Threading (Part 3)

Continued from Part 2: In Linux, normally (when we use default pthread_attribute , aka sending null to pthread_create()), we're creating the  joinable thread . There is another type of thread named detached thread , which We'll see later. A joinable thread is like a process, isn't automatically cleaned up by GNU/Linux when it terminates. Instead, its exit states hang around the system (like a zombie process) until the thread called pthread_join() obtains its return value. Let's see what happens in the Windows world: When the thread terminates (the normal way, aka the thread function returns), it ensures the following : 1. All C++ objects created in the thread function will be destroyed properly via their destructor. 2. The OS will clean up memory owned by the thread's stack. 3. The system will decrement threads kernel objects usage count. The following code snippet (GNU/Linux) shows a thread created using pthread_create() with default pthread_attr_t...

Programming: Windows Threading Vs Linux Threading (Part 2)

This is in continuation of the previous article 'Windows Threading Vs. Linux Threading ', here we'll see a subtle but significant difference in the  thread start routine which gets a call from CreateThread() API in the Windows world or pthread_create() function call in the Linux world. The ThreadProc function in Windows : DWORD WINAPI ThreadProc(   _In_  LPVOID lpParameter ); This is an application-defined function that serves as the starting address for a thread. Note: As per MSDN, Do not declare this callback function with a void return type and cast the function pointer to LPTHREAD_START_ROUTINE when creating the thread. Code that does this is common, but it can crash on 64-bit Windows . The return value indicates the success or failure of this function. The return value should never be set to STILL_ACTIVE (259). In Linux : The function passed as start_routine in the pthread_create() function should correspond to the following C function prototype: ...

Programming: Windows Threading Vs Linux Threading

In this article, I'm trying to show some differences between Windows and Linux thread creation and their respective usage. Creating Threads: 1.     a. In Windows: CreateThread() API is used to create a thread to execute within the virtual address space of the calling process.     b. In Linux: pthread_create() function creates a thread.     Function Signature:     // Windows     HANDLE WINAPI CreateThread(           _In_opt_   LPSECURITY_ATTRIBUTES lpThreadAttributes,           _In_       SIZE_T dwStackSize,           _In_       LPTHREAD_START_ROUTINE lpStartAddress,           _In_opt_   LPVOID lpParameter,           _In_       DWORD ...

A STL vector usage through shared_ptr

We know vector can store homogeneous kind of stuff. That is, it can store type int, string etc individually but not element of type int with string etc. However, sometimes we might have requirements that it can store elements which are in inheritance relation and can do stuff by calling function of respective element stored in vector. As an example, I've a Shape class from which I've derived Circle, Polygon etc. Now I want to store Circle, Polygon object in a vector and then access each element by its iterator and draw shape accordingly. C++ 2011 made it possible via shared_ptr. Thanks to Stephan aka STL. Code snippet #include < iostream > #include < memory > #include < vector > using namespace std; class Shape { public:     Shape(){}     virtual ~Shape(){}     virtual void draw(int x, int y)     {         cout << "Shape::draw(" << x << ", " << y <...

How do we list out files in Recycle Bin (Windows 7)

In this post, I tried to enumerate files within recycle bin using a small Win32 program. As we know that recycle bin is a special folder on Windows File System. The location of this directory is not in the registry; it is marked with hidden and system attributes to prevent the user from moving or deleting it. The steps to list out the contents of Recycle bin are as below: 1. It's a special folder denoted by CSIDL_BITBUCKET, which we need to pass to the function SHGetFolderLocation() method. 2. Source code snippet, I've avoided checks as much as possible to make the code simple and clean: int _tmain(int argc, _TCHAR* argv[]) {     LPITEMIDLIST pidlWinRecycleFiles    = NULL;     LPITEMIDLIST pidlItems                = NULL;     IShellFolder *psfWinRecycleFiles    = NULL;     IShellFolder *psfDeskTop       ...

Locking a physical disk on windows....

In this, I've tried to lock a physical disk using a small Windows C++ program. The steps to follow to achieve this are: 1. Get the Physical Drive and volume mapping. Say, the computer is attached with three physical drives, and we're interested to lock the Physical Drive 1 ("\\\\.\\PhysicalDrive1"). Then we need to figure out how many volumes are there on that physical disk. 2. Then Lock that volume one by one using control code FSCTL_LOCK_VOLUME . 3. Do the stuff we'd like to perform on the disk and then unlock each volume using control code  FSCTL_UNLOCK_VOLUME . 4. Close disk and volume handle(s). Few things to remember here. As per Microsoft documentation, a. The NTFS file system treats a locked volume as a dismounted volume. b. Lock volume call will fail with Access Code 5 (Access Denied) if the volume is in use. If we're not sure who's using the volume, just unmount it once. c. The FSCTL_DISMOUNT_VOLUME control code functions similarl...

Starting with Windows Media

I've decided to spend some more time on a few areas which I've learned during my association with my gurus in the software industry. There are few people in the United States and also in India who have helped me to shape myself. Predominantly I'm not an outspoken person, but those seniors understood that I had little hunger for knowledge and provided me that information and helped me to come to this stage. Windows Media Stack, when I started working on it, I was the most nervous person because very soon I realized this is not going to be easy stuff to handle. Indeed, it's the most complex programming world I've ever faced or challenged before. I started my journey on Media Stack for Windows with the help of James Dailey. I can remember those days when he came from the US and delivered his series of lectures. It was amazing. This was an entry towards a world where programming, troubleshooting, debugging, etc isn't an easy task at all but also full of great lear...

Deep Dive to Windows, Part 4

Launched a process sample_Hello through WinDbg and observed following events: ModLoad: 00400000 0041c000    Sample_Hello.exe ModLoad: 77980000 77b00000    ntdll.dll ModLoad: 76b10000 76c20000    C:\Windows\syswow64\kernel32.dll ModLoad: 76d20000 76d67000    C:\Windows\syswow64\KERNELBASE.dll ModLoad: 67fd0000 680ce000    C:\Windows\WinSxS\x86_microsoft.vc80.debugcrt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_e4a70117006762dd\MSVCP80D.dll ModLoad: 670e0000 67201000    C:\Windows\WinSxS\x86_microsoft.vc80.debugcrt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_e4a70117006762dd\MSVCR80D.dll ModLoad: 77050000 770fc000    C:\Windows\syswow64\msvcrt.dll (3c0.1324): Break instruction exception - code 80000003 (first chance) eax=00000000 ebx=00000000 ecx=fb480000 edx=0008e3c8 esi=fffffffe edi=00000000 eip=77a20fab esp=0018fb08 ebp=0018fb34 iopl=0          nv up ei pl zr na pe...

Detect Antivirus installed on Windows 7

In this article, I've tried to show how we can detect antivirus product installed on a Windows system. The code is written is specifically for Windows 7. The basic idea here is to use WMI from C++. Here are the steps: 1. To Setup WMI consumer, set up COM by calling CoInitializeEx . 2. Initialized COM process security by calling CoInitializeSecurity . 3. Obtained the initial locator to WMI by calling CoCreateInstance. 4. Obtained a pointer to IWbemServices for the root\cimv2 namespace on the local computer by calling IWbemLocator::ConnectServer . 5. Set IWbemServices proxy security so the WMI service can impersonate the client by calling CoSetProxyBlanket . 6.Used the IWbemServices pointer to make requests of WMI. This executes a WQL query for the antivirus product installed by calling IWbemServices::ExecQuery . The following WQL query is one of the method arguments. SELECT * FROM AntiVirusProduct The result of this query is stored in an IEnumWbemClassO...

About Windows Executable File Size

This post is basically an effort to know what happens when we compile a simple Hello World program on Windows. In this case, I've used Visual Studio 2005. First I've written a small usual Hello World program with all default settings provided by Visual Studio 2005. The program looks like below: int main(void) {     printf("Hello World build on VS 2005--Default\n");     return 0; } The program compiled against the default C-runtime library. No changes have been done in any settings. I've built it in Debug as well as in release mode. In Debug build, the program size is  40 KB . In release build: Its size is 6 KB . Now I've written another Hello World Program but switched off the default C-Runtime library. Rather, I've used the standard Windows library and provided definitions of functions like printf as well as the CRT start-up function. I've also switched off Buffer Security Check and Basic Runtime checks set to Default. The last two setti...

HDD enumeration and info retreive - another way

In this part I tried to enumerate all physical hard disk drive (HDD) attached to the system and tried to query to those attached physical drive to get the disk information like Vendor ID, Product ID, Product Revision, Serial number etc. In my last blog, I've tried to get physical hard disk drive count through volume map, but in this post, I tried get it through "SetupDiGetClassDevs" API. All the SetupDiXXX APIs are very powerful APIs. These APIs along with DeviceIoControl API helps to retrieve very useful information regarding devices. So, I'm not going to talk much on this rather let MSDN to speak about this APIs. Let's see what are other information that we can get on HDD attached to the system through the usage of this API: void printStorageDeviceProperty(UCHAR *outBuf, const DWORD returnedLength) {     PSTORAGE_DEVICE_DESCRIPTOR            devDesc;     PUCHAR       ...