Sunday, January 30, 2011

Disables file system redirection in 64bit OS

Tip - Wow64DisableWow64FsRedirection() Wow64RevertWow64FsRedirection()

Details - This function is useful for 32-bit applications that want to gain access to the native “%SystemRoot%\System32” directory in 64bit OS. By default, WOW64 file system redirection is enabled.

BOOL WINAPI Wow64DisableWow64FsRedirection(
  __out  PVOID *OldValue
);

To restore file system redirection, the Wow64RevertWow64FsRedirection function is used. Every successful call to the Wow64DisableWow64FsRedirection function must have a matching call to the Wow64RevertWow64FsRedirection function. This will ensure redirection is re-enabled and frees associated system resources.

BOOL WINAPI Wow64RevertWow64FsRedirection(
  __in  PVOID OldValue
);

The following example uses Wow64DisableWow64FsRedirection to disable file system redirection so that a 32-bit application that is running under WOW64 can open the 64-bit version of Notepad.exe in %SystemRoot%\System32 instead of being redirected to the 32-bit version in %SystemRoot%\SysWOW64.

void main()
{
    HANDLE hFile = INVALID_HANDLE_VALUE;
    PVOID OldValue = NULL;

    //  Disable redirection immediately prior to the native API
    //  function call.
    if( Wow64DisableWow64FsRedirection(&OldValue) )
    {
        //  Any function calls in this block of code should be as concise
        //  and as simple as possible to avoid unintended results.
        hFile = CreateFile(TEXT("C:\\Windows\\System32\\Notepad.exe"),
            GENERIC_READ,
            FILE_SHARE_READ,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        //  Immediately re-enable redirection. Note that any resources
        //  associated with OldValue are cleaned up by this call.
        if ( FALSE == Wow64RevertWow64FsRedirection(OldValue) )
        {
            //  Failure to re-enable redirection should be considered
            //  a criticial failure and execution aborted.
            return;
        }
    }
   
    //  The handle, if valid, now can be used as usual, and without
    //  leaving redirection disabled.
    if( INVALID_HANDLE_VALUE != hFile ) 
    {
        // Use the file handle
    }
}

Reference   -

Posted By : Velayudhan Pillai K

Creates a thread that runs in the virtual address space of another process.

Tip - CreateRemoteThread()

Details - The CreateRemoteThread function causes a new thread of execution to begin in the address space of the specified process. The thread has access to all objects that the process opens.

HANDLE WINAPI CreateRemoteThread(
  __in   HANDLE hProcess,
  __in   LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in   SIZE_T dwStackSize,
  __in   LPTHREAD_START_ROUTINE lpStartAddress,
  __in   LPVOID lpParameter,
  __in   DWORD dwCreationFlags,
  __out  LPDWORD lpThreadId
);

The hProcess parameter specifies a handle to the process in which the thread is to be created. If the function succeeds, the return value is a handle to the new thread. The new thread handle is created with full access to the new thread. If a security descriptor is not provided, the handle may be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread. The thread object remains in the system until the thread has terminated and all handles to it are closed through a call to CloseHandle function.

Reference   -

Posted By : Velayudhan Pillai K

Writing Data to an area of memory in a specified process

Tip - WriteProcessMemory()

Details - WriteProcessMemory() API copies the data from the specified buffer in the current process to the address range of the specified process.

BOOL WINAPI WriteProcessMemory(
  __in   HANDLE hProcess,
  __in   LPVOID lpBaseAddress,
  __in   LPCVOID lpBuffer,
  __in   SIZE_T nSize,
  __out  SIZE_T *lpNumberOfBytesWritten
);
 
Any process that has a handle with PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process to be written to, can call the function. The entire area to be written to must be accessible, and if it is not accessible, the function fails. The parameter lpBaseAddress is a pointer to the base address in the specified process to which data is written. Before data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for write access, and if it is not accessible, the function fails.

Reference   -

Posted By : Velayudhan Pillai K

Listing the loaded modules of the specified process

Tip - EnumerateLoadedModules(): Enumerates the loaded modules for the specified process.

Details - EnumerateLoadedModules() API can be used to get the loaded modules for an application. While writing Error Handler frameworks, for crash dumps etc. the list of loaded modules can be dumped using this API, which helps in debugging purpose.
BOOL WINAPI EnumerateLoadedModules(
                                    __in  HANDLE hProcess,
                                    __in  PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback,
                                    __in_opt PVOID UserContext
                                   );
For calling EnumerateLoadedModules() we need to provide a callback pointer. The EnumerateLoadedModules() will send the loaded module information as callback to that provided function. For example:
#include <Dbghelp.h>
// Callback function.
BOOL CALLBACK EnumerateLoadedModulesProc( PSTR ModuleName,
                                                                     ULONG ModuleBase,
                                                                                     ULONG ModuleSize,
                                           PVOID UserContext )
{
    // Print the module name.
    cout << ModuleName << endl;
    return TRUE;
}
int main(int argc, char* argv[])
{
    // Enumerate loaded modules.
    EnumerateLoadedModules(
                        GetCurrentProcess(),   // Process Handle
// Callback function pointer
          (PENUMLOADED_MODULES_CALLBACK) EnumerateLoadedModulesProc,
          0 );         // User context.
    return 0;
}


Reference   -

Posted By :Jijo Krishnan

Thread Information Block (TIB) and FS Register

Tip - TIB is a structure that stores the information about currently running thread. The ‘winnt.h’ contains a structure called NT_TIB which defines the TIB.

Details - The structure is:

typedef struct _NT_TIB
{
    struct _EXCEPTION_REGISTRATION_RECORD *ExceptionList;
    PVOID StackBase;
    PVOID StackLimit;
    PVOID SubSystemTib;
    union
   {
        PVOID FiberData;
        DWORD Version;
   };
    PVOID ArbitraryUserPointer;
    struct _NT_TIB *Self;
} NT_TIB;

The TIB can be accessed as an offset of segment register FS. FS is the data selector to TIB for the first thread. FS maps to a TIB which is embedded in a data block known as the TDB (thread data base). The TIB contains the thread-specific exception handling chain and pointer to the TLS (thread local storage.)

The functions such as GetCurrentProcessId(), GetCurrentThreadId(), GetLastError() etc fetches the values from TIB. For example, the code inside the function GetCurrentProcessId() may look like…
DWORD GetCurrentProcessId()
{
    DWORD dwProcessID = 0;
    __asm
    {
        mov eax, fs:[0x20]
        mov dwProcessID, eax
    }   
    return dwProcessID;
}

Contents of TIB (Please check the reference link for the complete details):
Position
Length
Windows Versions
Description
FS:[0x00]
4
Win9x and NT
Current Structured Exception Handling (SEH) frame
FS:[0x04]
4
Win9x and NT
Top of stack
FS:[0x08]
4
Win9x and NT
Current bottom of stack
FS:[0x10]
4
NT
Fiber data
FS:[0x14]
4
Win9x and NT
Arbitrary data slot
FS:[0x18]
4
Win9x and NT
Linear address of TIB
-
-
NT
End of NT subsystem independent part
FS:[0x20]
4
NT
Process ID
FS:[0x24]
4
NT
Current thread ID
FS:[0x2C]
4
Win9x and NT
Linear address of the thread-local storage array
FS:[0x30]
4
NT
Linear address of Process Environment Block (PEB)
FS:[0x34]
4
NT
Last error number
FS:[0x38]
4
NT
Last status number
FS:[0x3C]
4
NT
Count owned locks
FS:[0x40]
4
NT
Hard errors mode
FS:[0x60]
4
Win95/Win98
Last error number
FS:[0x74]
4
WinME
Last error number


Reference   -

Posted By :Jijo Krishnan

Adding Console into GUI applications

Tip - To add Console into a GUI application (Dialog based, SDI or MDI), use AllocConsole() and freopen(). AllocConsole() allocates a new console for the calling process.

Details - While debugging an application it is often useful to have trace output window for data logging rather than using MessageBox or OutputDebugString. An easiest method is to create a console window and redirect standard I/O to it like the following:

AllocConsole();
freopen("conin$", "r", stdin);
freopen("conout$", "w", stdout);
freopen("conout$", "w", stderr);

After this, all printf and cout calls will output to the console window.

Even input will work for it. We can use getch() from conio.h to pause a thread. A process can be associated with only one console, so the AllocConsole() function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console. This function is primarily used by graphical user interface (GUI) application to create a console window. The standard input handle is a handle to the console's input buffer and the standard output and standard error handles are handles to the console's screen buffer.

Reference   -

Posted By :Jijo Krishnan

Wednesday, January 26, 2011

Using StackWalk, MiniDumpWriteDump APIs for getting CallStack info

Tip -
StackWalk - Obtains a stack trace.
MiniDumpWriteDump - Writes minidump information to the specified file.

Details - 
StackWalk
In some cases we need to display the callstack of the current thread or the callstack of other threads/processes. This will be helpful for the application crash analysis etc.
Syntax:
                    StackWalk(
                 DWORD MachineType,
                 __in HANDLE hProcess,
                 __in HANDLE hThread,
                 __inout LPSTACKFRAME StackFrame,                      
                 __inout PVOID ContextRecord,
                 __in_opt PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
                 __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
                 __in_opt PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
                 __in_opt PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
                 );
This interface is in the dbghelp.dll library. The latest dbghelp.dll can be downloaded with the “Debugging Tools for Windows” available in http://www.microsoft.com/whdc/devtools/debugging/default.mspx.
 
MiniDumpWriteDump
Writes user-mode minidump information to the specified file. This helps to dump the call stack information to the specified file. The dump data can be analyzed using WinDbg. This interface is also in the dbghelp.dll library.
Syntax:
BOOL WINAPI MiniDumpWriteDump(
  __in  HANDLE hProcess,
  __in  DWORD ProcessId,
  __in  HANDLE hFile,
  __in  MINIDUMP_TYPE DumpType,
  __in  PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
  __in  PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
  __in  PMINIDUMP_CALLBACK_INFORMATION CallbackParam
);

Reference   -

Posted By :Jijo Krishnan

ProcDump

Tip - A general process dump utility.

Details - ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.

 

Reference -

Posted By :Sumesh V V

Virtual functions & Inline constructors

Tip -Virtual functions & Inline constructors

Details - When an object containing virtual functions is created, its VPTR must be initialized to point to the proper VTABLE. This must be done before there’s any possibility of calling a virtual function. A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. As you might guess, because the constructor has the job of bringing an object into existence, it is also the constructor’s job to set up the VPTR. The compiler secretly inserts code into the beginning of the constructor that initializes the VPTR. In fact, even if you don’t explicitly create a constructor for a class, the compiler will create one for you with the proper VPTR initialization code (if you have virtual functions). This has several implications.

 

The first concerns efficiency. The reason for inline functions is to reduce the calling overhead for small functions. If C++ didn’t provide inline functions, the preprocessor might be used to create these “macros.” However, the preprocessor has no concept of access or classes, and therefore couldn’t be used to create member function macros. In addition, with constructors that must have hidden code inserted by the compiler, a preprocessor macro wouldn’t work at all.

 

You must be aware when hunting for efficiency holes that the compiler is inserting hidden code into your constructor function. Not only must it initialize the VPTR, it must also check the value of this (in case the operator new returns zero) and call base-class constructors. Taken together, this code can impact what you thought was a tiny inline function call. In particular, the size of the constructor can overwhelm the savings you get from reduced function-call overhead. If you make a lot of inline constructor calls, your code size can grow without any benefits in speed.

 

Of course, you probably won’t make all tiny constructors non-inline right away, because they’re much easier to write as inline. But when you’re tuning your code, remember to remove inline constructors.

 

Reference -

Posted By :Sumesh V V

Behavior of virtual functions in constructors – C++

Tip-Behavior of virtual functions in constructors – C++

Details - The hierarchy of constructor calls brings up an interesting dilemma. What happens if you’re inside the constructor of a base class and you call a virtual function? Inside an ordinary member function you can imagine what will happen – the virtual call is resolved at runtime because the object cannot know whether it belongs to the class the member function is in, or some class derived from it. For consistency, you might think this is what should happen inside constructors. This is not the case. If you call a virtual function from the constructor of a base class, only the local version of the function is used. That is, the virtual mechanism doesn’t work within the constructor of base class.

This behavior makes sense for two reasons. Conceptually, the constructor’s job is to bring the object into existence. Inside any constructor, the object may only be partially formed – you can only know that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A virtual function call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a function in a derived class. If you could do this inside a constructor, you’d be calling a function that might manipulate members that hadn’t been initialized yet, a sure recipe for disaster.
The second reason is a mechanical one. When a constructor is called, one of the first things it does is initialize its VPTR. However, it can only know that it is of the “current” type. The constructor code is completely ignorant of whether or not the object is in the base of another class. When the compiler generates code for that constructor, it generates code for a constructor of that class, not a base class and not a class derived from it (because a class can’t know who inherits it). So the VPTR it uses must be for the VTABLE of that class. The VPTR remains initialized to that VTABLE for the rest of the object’s lifetime this isn’t the last constructor call. If a more-derived constructor is called afterwards, that constructor sets the VPTR to VTABLE, and so on, until the last constructor finishes. The state of the VPTR is determined by the constructor that is called last. This is another reason why the constructors are called in order from base to most-derived.
But while all this series of constructor calls is taking place, each constructor has set the VPTR to its own VTABLE. If it uses the virtual mechanism for function calls, it will produce only a call through its own VTABLE, not the most-derived VTABLE (as would be the case after the constructors were called). In addition, many compilers recognize that a virtual function call is being made inside a constructor, and perform early binding because they know that late-binding will produce a call only to the local function. In either event, you won’t get the results you might expect from a virtual function call inside a constructor.
[Code] 
class Base
{
public:
    Base()
    {
        DoSomething();
    }

    virtual ~Base()
    {
    }

    // This will be overridden in the derived type.
    virtual void DoSomething()
    {
        printf( "Base::DoSomething\r\n" );
    }
};

class DerivedType : public Base
{
public:
    DerivedType ()
    {
    }

    ~DerivedType ()
    {
    }

    void DoSomething()
    {
        printf( "DerivedType::DoSomething\r\n" );
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base *pDerivedType = new DerivedType();
    // Code here
    if( NULL != pDerivedType )
    {
        delete pDerivedType;
        pDerivedType = 0;
    }
    return 0;
}

Output:
Base::DoSomething

Reference   -


Posted By :Sumesh V V