Monday, November 29, 2010

Dependency Walker


Tip - The dependency walker, has version upgrades with several new features. 

Details  -
 The depends.exe distributed with VS6, has undergone several changes. From V1.0 to 2.2, it has became capable of displaying C++ name mangling resolved symbols, detecting delay loaded DLLs (see previous tip about delay loaded DLL) and a profiling option to resolve the dynamic dependencies.  Original depends.exe V 1.0 do not show the delay loaded dlls, and eventually became untrustworthy for resolving dependencies when VC++ 6 started supporting delay loading of DLLs. So, beware of the version being used when trying the dependency walker; it can betray you. The name mangling resolved symbols are very helpful being much more readable than the original representation. Profiling, which require to run the application using depends profiles, will apply the detected dynamic dependencies (say, a LoadLibrary() ‘ed DLL) to its display on-the-fly.



Reference         -

Posted By :Praveen E

Mutex vs Semaphore

Tip  : Mutex and semaphore has some behavior mismatch is there in certain scenarios.
Details : Most of us are familiar with both mutex and semaphore.  These objects are used for synchronize the code flow and properly handle the shared resource used in our code flow. Now we can check the major difference between mutex and semaphore.
Mutex:
Is a key to a shelf. One person can have the key to use the shelf at the time. When his usage is finished, the person gives (frees) the key to the next person in the queue.
Theoretically: "Mutexes are typically used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section."
Semaphore:
It is the number of free identical shelf keys. Example, say we have four shelves with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the shelf, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Theoretically: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)."
Some of the document we can find the single semaphore is equal to mutex. But in certain scenarios behavior of mutex and semaphore are different.
1.       Within single thread, we can create more than one mutex without release the previous handle. But if we use single semaphore, second semaphore will not create properly and it will wait for previous semaphore to release its handle. So if we need to synchronize recursive calling sequence, it is better to use mutex instead of semaphore. Otherwise there is some chance for dead lock and all.
2.       Suppose one application is waiting for second application to release a particular semaphore. During that waiting time if second application terminated abnormally. In this case semaphore will not signal the waiting client about the semaphore release information. In case of mutex, waiting application will get the return code as ‘WAIT_ABANDONED’ during the locked application abnormal termination time.

Reference    :

Posted By :Arun M. S.

AFX_MANAGE_STATE

Tip                   :   Usage of AFX_MANAGE_STATE
Details  : 
What is the use of AFX_MANAGE_STATE
We are familiar with Dynamic Link Libraries (DLLs) and most of our daily application development activities are using it. If you have an exported function in DLL and you don’t use any resources from the DLL itself  then you could invoke it from an executable module and it will work fine.
But you want to launch a dialog from the DLL module and which is from it’s own resource part. What will happen if you invoke the domodal of a dialog from any of the exported function in the DLL. No doubt, the domodal will return -1.

How we can do that
Actually what is happening here, once we try to launch a dialog from the DLL from its own resource – but the application holds the resource handle of the main application. So we need to switch the module state for the correct handle to be used. We can do this by adding the following code to the beginning of the exported function in the DLL,
AFX_MANAGE_STATE( AfxGetStaticModuleState() );
This swaps the current module state with  the state returned from AfxGetStaticModuleState( ) until the end of the current scope. This is a macro used to protect an exported function in a DLL.

Code snippet
Regular DLL exported function



Main application function


Note
 That’s working fine in the Regular DLL, now if we try the same routine with the MFC Extension DLL it may lead to a link error, please refer the below link for further details

Reference    :

Posted By :Arun M. S.

Wednesday, November 24, 2010

Capturing mouse input

Tip -We can capture mouse input even after mouse pointer went outside our window.

Details -
There are two functions which helps in capturing mouse input, it’s called SetCapture and ReleaseCapture and a helper function called GetCapture which returns a handle to the capture window associated with the current thread. If no window in the thread has captured the mouse, the return value is NULL.

Why do we need to capture mouse?
An example is when doing rubber band drawing. If mouse goes out of our window we won’t be able to get mouse movement events, but with a call to SetCapture this will be possible as a result our line keeps moving vertically and horizontally according to mouse movement. Ideal flow for drawing rubber band lines should be…
  1. OnLButtonDown – Capture mouse using SetCapture
  2. OnMouseMove – We’ll continue drawing rubber band lines, also clear previous line.
  3. OnLButtonUp – Release mouse using ReleaseCapture
  4. Neatly handle WM_CAPTURECHANGED just in case in someone captures mouse in between the drawing process.
Some points to note…
  1. Only one window at a time can capture mouse input.
  2. Only the foreground window can capture mouse input.
  3. Background windows can capture mouse input but they’ll receive mouse notifications only when mouse moves over their visible region.
  4. Menu hotkeys and accelerators don’t work when mouse is captured.
Don’t forget to handle WM_CAPTURECHANGED message, because if another window calls SetCapture then this message is fired to the window that is losing mouse capture. To release captured mouse call ReleaseCapture.


Posted By :Arun M. S.

Sunday, November 21, 2010

Points need to take care during Asynchronous Write operation

Tip - While implementing asynchronous IO operations for performance tuning, we need to take care certain points.
Details -
Ø  We will get the write operation status in its associated callback function. In that call back function, we should check the operation status and number of bites written etc. Because the operation completion status is returned in the callback function only.
Ø  Make sure that write operation is completed before perform the following operations
o   Releasing buffer used for write operation
o   Closing the file handle
[Note: We will get execution control before finishing asynchronous IO operations]
Ø  Maximum buffer we can write using WriteFileEx is 64 MB(For X64 systems, the maximum buffer size is just under 32MB). So if we need to write more than the size limit, We need to make write operation in chunk or we need to write buffer before grow the file size up to required size.
Ø  For effective working of asynchronous IO operation, an alert able wait function should be invoked after asynchronous IO operation. Otherwise it will work just like synchronous IO operation.

Reference :



Posted By :Arun M. S.

Configuring a COM server to be run as a single instance in Server 2008.

Tip - RunAs(COM)-Configures a class to run under a specific user account when activated by a remote client without being written as a service application.
Details - When COM clients in the client sessions query interfaces of COM servers that are running in session 0, multiple instance of  the COM servers gets instantiate in client sessions even though COM server is running.  This can be avoided by changing the value of following registry key as “nt authority\system”.
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID
   {AppID_GUID}
      RunAs = nt authority\system
Note: We cannot use "nt authority\system" with a COM server that is not already started. 


Posted By : Merlin S. Thadathil

Wednesday, November 17, 2010

Enable the application to prompt for UAC notifications

Tip -How to elevate an application in VC++

Details -If your application requires administrative privileges to run correctly (for example, if it modifies the HKLM node of the registry or if it writes to protected areas of the disk, such as the Windows directory), you must modify the application as given below.
Ø  Go to Project -> Properties -> Configuration Properties -> Linker ->Manifest File and do the following settings,
Ø  Enable User Account control(UAC) ->yes
Ø  Change UAC Execution Level -> requireAdministrator
Ø  Rebuild application
Note:
·         An executable that is marked as "requireAdministrator" in its manifest cannot be started from a non-elevated process using CreateProcess().  
·         A new process with elevated privileges can be spawned from within a  native Win32 application as follows,
o    “ShellExecute(hwnd, "runas", "C:\\Windows\\Notepad.exe", 0, 0, SW_SHOWNORMAL);”
·         If the application is in requireAdministrator modes, failure to provide confirmation results in the program not being launched. Make sure the user belongs to the administrator group.

Posted By : Merlin S. Thadathil

User Account Control– Feature of Windows from vista onwards

Tip -How to adjust UAC notifications

Details - UAC enables users to perform common tasks as non-administrators, called standard users in Windows Vista, and as administrators without having to switch users, log off, or use Run As. Also it help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of the user account. This makes it so that even if you're using an administrator account, changes cannot be made to your computer without you knowing about it, which can help prevent malicious software (malware) and spyware from being installed on or making changes to your computer.
In Windows server 2008/Windows 7, you can adjust how often UAC notifies you when changes are made to your computer.


How to adjust UAC notifications:  Open User Account Control Settings by clicking the Start button, and then clicking Control Panel. In the search box, type uac, and then click Change User Account Control settings.

Note: It is recommend that you choose either the Always notify or the Default - Notify me only when programs try to make changes to my computer UAC setting when using websites.



Posted By : Merlin S. Thadathil

Monday, November 15, 2010

Terminal Services RemoteApp

Tip - How to configure RemoteApp.

Details - In the past, with Windows Terminal Server, remote users could only access the entire Windows desktop of the machine they were connecting to. With RemoteApp, the administrator can configure the server to allow users to connect to just a single application using RDP / Terminal Services. “RemoteApps” can be distributed with either .MSI package installers, .RDP files, or users can access the remoteapps through the new Windows Terminal Server web access.


How to configure: Applications are configured as RemoteApps using the RemoteApp Manager tool.
1.       Start RemoteApp Manager from the Start -> All Programs -> Remote Desktop Services -> RemoteApp Manager or by running remoteprograms.msc in a Run dialog or at a command prompt.
2.       Click on the Add RemoteApp Programs link in the Actions panel. (Refer the attached figure)
3.       Select the application to be runned as RemoteAPP.
4.       Select the RemoteApp program from RemoteApp Manager’s RemoteApp Programs list and select Create .rdp File from the menu.
5.       Copy the .rdp file generated in Step 4 to client computer.



Reference : http://technet.microsoft.com/en-us/library/cc755055.aspx


Posted By : Merlin S. Thadathil

Session 0 isolation – Feature of Windows OS from windows vista onwards


Tip  -Solution for solving session 0 isolation issues.

Details - In Windows XP, Windows Server 2003, and earlier versions of Windows, all services run in Session 0 along with applications. This situation poses a security risk. In Windows Vista, Windows Server 2008, and later versions of Windows, the operating system isolates services in Session 0 and runs applications in other sessions, so services are protected from attacks that originate in application code.


Application classes affected by this feature include:
·         Services that create UI.
·         A service that tries to use window-message functions such as SendMessage and PostMessage to communicate with an application.
·         Applications creating globally named objects.
Remedies:
·         Use client or server mechanisms such as remote procedure call (RPC) or named pipes to communicate between services and applications.
·         Use the WTSSendMessage function to create a simple message box on the user’s desktop. This allows the service to give the user a notification and request a simple response.
·         For more complex UI, use the CreateProcessAsUser function to create a process in the user's session.
·         Explicitly choose either the Local\ or Global\ namespace for any named objects, such as events or mapped memory that the service makes available.





Posted By : Merlin S. Thadathil

Sunday, November 14, 2010

Application Verifier - A runtime verification tool

Title               :        Application Verifier - A runtime verification tool

Tip                 :        Using Application Verifier to Troubleshoot Programs.

Details           :        The Microsoft Application Verifier (AppVerifier) is a runtime verification tool for unmanaged code that assists in finding subtle programming errors, security issues and limited user account privilege problems that can be difficult to identify with normal application testing techniques.


To use AppVerifier:

   1. Click Add to add a program to the list.
   2. Select the appropriate tests from the Test settings list.
   3. Start your application and exercise it.
   4. After you complete the testing, click View Logs to see the log entries that were generated.
   5. Remove the program from AppVerifier when testing is complete.
  
 Screenshots of  AppVerifier :






Reference :


Posted By : Febil Chacko

Thursday, November 11, 2010

LeakDiag - An Effective Memory Leak Analysis Tool

Tip                 :         How to analyze memory leak using LeakDiag and LDGrapher.

Details           :         LeakDiag is memory leak analysis tool that helps developers to diagnose memory leaks, fragmentation, and other memory-related issues in applications or services. LeakDiag intercepts calls to specified memory allocations and tracks the various call stacks. It reports on the memory that has been allocated but not yet freed. With correct debug symbols, even the line of code that requested the allocations can be seen.


How to run LeakDiag:
1.       Configure the public symbol path as well as your local symbol path using LeakDiag Option dialog.
2.       We can resolve the symbols when logging itself. In the case of large application, we can resolve symbols after the logging using  sdecode.exe.
3.       We need to select the Process and memory allocator from LeakDiag main window.
4.       Press the start button.
5.       Take snapshot of stacks by clicking the log button. This will collect all stack frames which have allocated the memory and are not freed up till then. We need to take as many snapshots as possible, more the snapshots it is easier to find out the leaking stacks.
6.       The logs will available in the location specified in the option dialog.
7.       We need to take multiple files and track each stack in these files one by one, if the totalsize of stack value goes on increasing or even if it is remaining constant for a long time, then we can take that stack as a doubtful stack and check if memory allocated by that particular stack is getting freed correctly. Repeat the above process till we reach the suspicious code portion.

LDGrapher:                 The memory analysis using XML is a time consuming task.  To solve this, we can use LDGrapher. This is a redistributable tool provided by Microsoft and is available on ftp://ftp.microsoft.com/PSS/Tools/Developer%20Support%20Tools/LDGrapher/.
We can provide the generated XML files as an input and this tool will give us the graphical representation of our stacks.

The screenshots of LeakDiag and LDGrapher are shown below.



Reference :

Posted By : Febil Chacko

Wednesday, November 10, 2010

Process Viewer & Performance Monitor

Tip -Process Viewer & Performance Monitor, Windows Utility

Details -With the PView process viewer (PVIEW.EXE), you can examine and modify many characteristics of the processes and threads running on your system.

Using this tool we will get the solution for the below  questions:
    * How much memory does the program allocate at various points in its execution, and how much memory is being paged out?
    * Which processes and threads are using the most CPU time?
    * How does the program run at different system priorities?

 To start PView
   1. Click the Start button on the Windows taskbar and highlight Programs.
   2. On the resulting Programs submenu, highlight Microsoft Visual C++ 6.0.
   3. Next, highlight Microsoft Visual C++ 6.0 Tools then click Process Viewer.  PView opens by displaying the main Process Viewer Application dialog box.


Perfmon Details:
Performance Monitor (perfmon.exe) to monitor the amount of memory a single instance of a report process is using

The following steps will explain how to use Performance Monitor to determine the amount of memory being used during the report analysis.
   1. Open Performance Monitor (it can be opened by typing perfmon.exe from the command line).
   2. Under Performance Logs and Alerts, select counter logs.
   3. In the right panel, right-click and select New Log settings.
   4. Assign (type) the name of the new log.
   5. Select add counter.
   6. Select the following:
          * The computer running Firewall Suite
          * Performance Object: Process
          * Counter as Private Bytes
          * Instance as runevent.exe
   7. Click Apply to save.
   8. Schedule the monitor to run next time you do an analysis.



Reference :

Posted By : Febil Chacko