Copy Constructors and Derived Classes - Copying parent class members
The default constructor for a derived class calls the base class default constructor implicitly, without an explicit call. However, the copy constructor for a derived class does not call the copy constructor of the base class --- it calls the default zero-argument constructor for the base class.
class Base
{
public:
Base() { cout << "Base constructor\n"; } Base(Base &b) { cout << "Base COPY constructor\n"; } }; class Derived : public Base { public: Derived(Derived &b) { cout << "Derived COPY constructor\n"; } }; main() { Derived d1; Derived d2(d1); // copy constructor } This is not what we usually require; more typically a derived class copy constructor will explicitly invoke the base class copy constructor using the special syntax for passing arguments to a base class. class Base { public: Base(Base &b) { cout << "Base COPY constructor\n"; } }; class Derived : public Base { Derived(Derived &b) : Base(b) { cout << "Derived COPY constructor\n"; } }; The Derived object ``b" is passed to the Base class copy constructor. Note that this involves converting the Derived& reference to a Base& reference --- recall that conversion of a pointer/reference is allowed from Derived down to base, but not the reverse.
Assignment Operators and Derived Classes - Copying parent class members
Similarly to the problem with copy constructors in derived classes, the assignment operator in derived classes does not implicitly call the base class assignment operator. In fact, by default, the private data of the base class will not be modified by the derived class assignment operator.
The solution is an explicit call to the Base class assignment operator which can be achieved via the ``this" special pointer, and a type cast to a reference to a reference to the Base class.
void operator=(Derived &d)
{
(Base&)*this = d; // EXPLICIT CALL // The above copies the Base class data
// Now copy the derived class data ....
}
There are a few other alternative methods of explicit calls, such as:
void operator=(Derived &d)
{
(*this).Base::operator=(d); // EXPLICIT CALL
}
(or)
If there is a parent (base) class, those fields must also be copied.
You can accomplish this with the following cryptic statement,
this->Parent::operator=(source); //where Parent is the name of the base class.
//--- file Parent.h
class Parent {...}; // declaration of base class
//--- file Child.h
#include "Parent.h"
class Child : public Parent { // declaration of derived class
public:
Child& Child::operator=(const Child& source);
};//end class Child
//--- file Child.cpp
#include "Child.h"
Child& Child::operator=(const Child& source) {
if (this != &source) {
this->Parent::operator=(source);
. . . // copy all our own fields here.
}
return *this;
}//end operator=
Methods that are implicitly generated by the compiler if they are not explicitly defined are:
a. Default constructor (C::C())
b. Copy constructor (C::C (const C& rhs))
c. Destructor (C::~C())
d. Assignment operator (C& C::operator= (const C& rhs))
e. Address-of operator (C* C::operator&())
f. Address-of operator (const C* C::operator&() const;)
Private Copy Constructor:
1. Use private copy constructor and assignment operator to avoid object copyingIf you don't want users of your class to be able to assign objects of its type (password string objects are a good example), you can declare a private assignment operator and copy constructor.
Please note that the compiler-synthesized copy constructor and assignment operator are public, therefore, you have to define them explicitly as private members in this case.
2. To make sure we can not pass objects by value only by reference.
Links:
http://www.cs.jcu.edu.au/Subjects/cp3120/1996/Lectures/c++/node92.html
C/C++ Memory Corruption And Memory Leaks - http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Search this Blog:
Copy Constructors , Assignment Operator & Derived Classes - Copying parent class members
JAVA CODE REVIEW CHECKLIST
JAVA Code Review CheckList
Error Handling
1. Does the code comply with the accepted Exception Handling Conventions.
a. We need to expand our notion of Exception Handling Conventions.
b. Some method in the call stack needs to handle the exception, so that we don’t display that exception stacktrace to the end user.
2. Does the code make use of exception handling?
a. Exception handling should be consistent throughout the system.
3.Does the code simply catch exceptions and log them?
a. Code should handle exceptions, not just log them.
4.Does the code catch general exception (java.lang.Exception)?
a. Catching general exceptions is commonly regarded as “bad practice”.
5.Does the code correctly impose conditions for “expected” values?
a.For instance, if a method returns null, does the code check for null?
The following code should check for null
Person person = Context.getPersonService().getPerson(personId);
person.getAddress().getStreet();
What should be our policy for detecting null references?
6.Does the code test all error conditions of a method call?
a. Make sure all possible values are tested.
b.Make sure the JUnit test covers all possible values.
Security
1. Does the code appear to pose a security concern?
a. Passwords should not be stored in the code. In fact, we have adopted a policy in which we store passwords in runtime properties files.
b.Connect to other systems securely – i.e. use HTTPS instead of HTTP where possible.
Thread Safeness
1. Does the code practice thread safeness?
a. If objects can be accessed by multiple threads at one time, code altering global variables (static variables) should be enclosed using a synchronization mechanism (synchronized).
b. In general, controllers / servlets should not use static variables.
c. Use synchronization on the smallest unit of code possible. Using synchronization can cause a huge performance penalty, so you should limit its scope by synchronizing only the code that needs to be thread safe.
d. Write access to static variable should be synchronized, but not read access.
e. Even if servlets/controllers are thread-safe, multiple threads can access HttpSession attributes at the same time, so be careful when writing to the session.
f. Use the volatile keyword to warn that compiler that threads may change an instance or class variable – tells compiler not to cache values in register.
g. Release locks in the order they were obtained to avoid deadlock scenarios.
2. Does the code avoid deadlocks?
a. I’m not entirely sure how to detect a deadlock, but we need to make sure we acquire/release locks in a manner that does not cause contention between threads. For instance, if Thread A acquires Lock #1, then Lock #2, then Thread B should not acquire Lock #2, then Lock #1.
b.Avoid calling synchronized methods within synchronized methods.
Resource Leaks
1. Does the code release resources?
a. Close files, database connections, HTTP connections, etc.
2. Does the code release resources more than once?
a. This will sometimes cause an exception to be thrown.
3. Does the code use the most efficient class when dealing with certain resources?
a. For instance, buffered input / output classes.
Miscellaneous:
1.Make sure that we are using StringBuffer if we want to change the contents of a String
2.Always use “.equals” instead of “==” during Object Comparision
3.Use wait()/notify() instead of sleep()
Links:
Checklist: Java Code Review - http://snap.uci.edu/viewXmlFile.jsp?resourceID=1529
http://www.javaworld.com/javaworld/javatips/jw-javatip88.html
http://undergraduate.csse.uwa.edu.au/units/CITS2220/assign2/JavaInspectionCheckList.pdf
http://www.cs.toronto.edu/~sme/CSC444F/handouts/java_checklist.pdf
http://www.deaded.com/staticpages/index.php/codereviewprocess
C++/VC++ CODE REVIEW CHECKLIST
C++ Code Review CheckList
Classes
1 Does the class have any virtual functions? If so, is the destructor non-virtual?
Classes having virtual functions should always have a virtual destructor. This is
necessary since it is likely that you will hold an object of a class with a pointer of a lessderived
type. Making the destructor virtual ensures that the right code will be run if you
delete the object via the pointer.
2 Does the class have any of the following:
Copy-constructor
Assignment operator
Destructor
If so, it generally will need all three. (Exceptions may occasionally be found for some
classes having a destructor with neither of the other two.)
Deallocating Data
1.Are arrays being deleted as if they were scalars?
delete myCharArray;
should be
delete [] myCharArray;
2. Does the deleted storage still have pointers to it?
It is recommended that pointers are set to NULL following deletion, or to another safe
value meaning "uninitialized." This is neither necessary nor recommended within
destructors, since the pointer variable itself will cease to exist upon exiting.
3. Are you deleting already-deleted storage?
This is not possible if the code conforms to 6.2.2. The draft C++ standard specifies that
it is always safe to delete a NULL pointer, so it is not necessary to check for that value.
If C standard library allocators are used in a C++ program (not recommended):
4.Is delete invoked on a pointer obtained via malloc, calloc, or realloc?
5.Is free invoked on a pointer obtained via new?
Both of these practices are dangerous. Program behavior is undefined if you do them, and such
usage is specifically deprecated by the ANSI draft C++ standard.
Constants
1. Does the value of the variable never change?
int months_in_year = 12;
should be
const unsigned months_in_year = 12;
2. Are constants declared with the preprocessor #define mechanism?
#define MAX_FILES 20
should be
const unsigned MAX_FILES = 20;
3. Is the usage of the constant limited to only a few (or perhaps only one) class?
If so, is the constant global?
const unsigned MAX_FOOS = 1000;
const unsigned MAX_FOO_BUFFERS = 40;
should be
class foo {
public:
enum { MAX_INSTANCES = 1000; }
...
private:
enum { MAX_FOO_BUFFERS = 40; }
...
};
If the size of the constant exceeds int, another mechanism is available:
class bar {
public:
static const long MAX_INSTS;
...
};
const long bar::MAX_INSTS = 70000L;
The keyword static ensures there is only one instance of the variable for the entire
class. Static data items are not permitted to be initialized within the class declaration, so
the initialization line must be included in the implementation file for class bar.
Static constant members have one drawback: you cannot use them to declare member
data arrays of a certain size. This is because the value is not available to the compiler at
the point which the array is declared in the class.
Links
"Code Review Checklist" by Charles Vaz - http://charlesconradvaz.wordpress.com/2006/02/16/code-review-checklist-2/
Code Inspection Check List - http://www.chris-lott.org/resources/cstyle/Baldwin-inspect.pdf
C Code Reviw Guide - http://casper.ict.hen.nl/se/SEscripts/CodeReviewGuide.html
Best Practices: Code Reviews - http://msdn.microsoft.com/en-us/library/bb871031.aspx
MISCELLANEOUS
Excerpts:
1. WinInet.dll is Extension to Internet Explorer. It gets installed when we install Internet Explorer. It means that IE6 & IE7 has different versions of WinInet.dll files.
MFC HTTP Programming (ex: CInternetSession...) uses exported functions of WinInet.dll
2. JNI is used to communicate between JAVA & C/C++. JNI is dangerous to use as some exception in your JNI code crashes JRE ... Have to handle JNI exceptions carefully.
3. JAI (Java Advanced API for Imaging) can be used to display a Image(Jpg,Jpeg,GIF...) in JAVA UI. "BufferedImage" class can be used to store a Jpeg/jpg/gif image.
Java ImageIO also can be used to play with images(Jpg,Jpeg,GIF...)
4. winInet.dll => Extension Dll for Internet Explorer. Gets installed with IE. It means IE6 & IE7 will come with two different versions of winInet.dll ;
TCP program HTTP on windows , VC++ can make use of WinInet.dll
CURL Library is portable HTTP Programming Library which can be used across Unix and Windows Programs. WinInet.dll is specific to Windows (IE only)
5. JNI => ByteBuffer datatype can be used for sharing heap memory between JAVA & C++.
6.Common Concurrency Defects
Race Condition
Multiple threads access the same shared data without the appropriate locks to protect
access points.When this defect occurs, one thread may inadvertently overwrite data used by another thread,leading to both loss of information and data corruption.
Thread Block
A thread calls a long-running operation while holding a lock thereby preventing the
progress of other threads.When this defect occurs, application performance can drop dramatically due to a single bottleneck for all threads.
Deadlock
Two or more threads wait for locks in a circular chain such that the locks can never be acquired.
When this defect occurs, the entire software system may halt, as none of the threads can either proceed along their current execution paths or exit.
7. Reliability, Scalability, Security
Reliable - A solution architecture designed to run 24x7 to meet the requirements of round the clock global commerce.
Scalable - To grow as your organization grows, with sustained throughput to meet the most demanding volumes, time frames, and service levels.
Secure - Protecting your assets, meeting regulatory and privacy requirements, and providing comprehensive audit ability with a defense-in-depth architecture designed to enable, rather than inhibit, your expanding B2B activity.
8. Active Directory Administration -
Link: http://articles.techrepublic.com.com/5100-10878_11-6094851.html?tag=btxcsim
Insight for Active Directory assists IT professionals in diagnosing configuration problems and troubleshooting the directory services' interaction with other applications. The utility works by listing the Lightweight Directory Access Protocols (LDAP) calls Active Directory receives from any system within a domain, thereby enabling administrators to track Active Directory activity.
AD Explorer provides a simplified method of locating and changing Active Directory objects and attributes. Using a two-pane window, administrators can find, edit, add and delete Active Directory objects and attributes.
9.Visual Studio Shortcuts You Should Know - http://www.dev102.com/2008/05/06/11-more-visual-studio-shortcuts-you-should-know/
10. Visual Studio Short-Cuts:10 Visual Studio Shortcuts You Must Know http://www.dev102.com/2008/04/17/10-visual-studio-shortcuts-you-must-know/11 More
11. UpdateResource() API
Adds, deletes, or replaces a resource in a portable executable (PE) file. There are some restrictions on resource updates in files that contain Resource Configuration (RC Config) data: language-neutral (LN) files and language-specific resource (.mui) files.
Links
http://msdn.microsoft.com/en-us/library/ms648049(VS.85).aspx
Using UpdateResource() to change the icon of an EXE file - http://www.codeguru.com/forum/printthread.php?threadid=200836
Using UpdateResource to change a string resource - http://www.codeproject.com/KB/string/updatestringresource.aspx
12. Command to stop Windows Shutdown : shutdown -a
Unix System Calls
System calls are functions that a programmer can call to perform the services of the operating system. if you want to see which system calls a program uses, run strace
In general, a process is not supposed to be able to access the kernel. It can't access kernel memory and it can't call kernel functions. The hardware of the CPU enforces this (that's the reason why it's called `protected mode').
System calls are an exception to this general rule. What happens is that the process fills the registers with the appropriate values and then calls a special instruction which jumps to a previously defined location in the kernel (of course, that location is readable by user processes, it is not writable by them). Under Intel CPUs, this is done by means of interrupt 0x80. The hardware knows that once you jump to this location, you are no longer running in restricted user mode, but as the operating system kernel --- and therefore you're allowed to do whatever you want.
The location in the kernel a process can jump to is called system_call. The procedure at that location checks the system call number, which tells the kernel what service the process requested. Then, it looks at the table of system calls (sys_call_table) to see the address of the kernel function to call. Then it calls the function, and after it returns, does a few system checks and then return back to the process (or to a different process, if the process time ran out). If you want to read this code, it's at the source file arch/$<$architecture$>$/kernel/entry.S, after the line ENTRY(system_call).
So, if we want to change the way a certain system call works, what we need to do is to write our own function to implement it (usually by adding a bit of our own code, and then calling the original function) and then change the pointer at sys_call_table to point to our function. Because we might be removed later and we don't want to leave the system in an unstable state, it's important for cleanup_module to restore the table to its original state.
Links:
Linux System Call Quick Reference -
System Calls - http://www.faqs.org/docs/kernel/x931.html
Windows Password Filters
Password filters provide a way for you to implement password policy and change notification.
When a password change request is made, the Local Security Authority (LSA) calls the password filters registered on the system. Each password filter is called twice: first to validate the new password and then, after all filters have validated the new password, to notify the filters that the change has been made
Installing and Registering a Password Filter DLL
You can use the password filter to filter domain or local account passwords. To use the password filter for domain accounts, install and register the DLL on each domain controller in the domain.
Perform the following steps to install your password filter. You can perform these steps manually, or you can write an installer to perform these steps. You need to be an Administrator or belong to the Administrator Group to perform these steps.
To install and register a password filter DLL
1. Copy the DLL to the Windows installation directory on the domain controller or local computer.
2. To register the password filter, update the following system registry key:
HKEY_LOCAL_MACHINE=>SYSTEM=>CurrentControlSet=>Control=>Lsa
If the Notification Packages subkey exists, add the name of your DLL to the existing value data. Do not overwrite the existing values, and do not include the .dll extension.
If the Notification Packages subkey does not exist, add it, and then specify the name of the DLL for the value data. Do not include the .dll extension.
The Notification Packages subkey can add multiple packages.
3. Find the password complexity setting.
In Control Panel, click Performance and Maintenance, click Administrative Tools, double-click Local Security Policy, double-click Account Policies, and then double-click Password Policy.
4. To enforce both the default Windows password filter and the custom password filter, ensure that the Passwords must meet complexity requirements policy setting is enabled. Otherwise, disable the Passwords must meet complexity requirements policy setting.
Password Filter Functions:
The following password filter functions are implemented by custom password filter DLLs to provide password filtering and password change notification.
Function Description
InitializeChangeNotify() => Indicates that a password filter DLL is initialized. PasswordChangeNotify() => Indicates that a password has been changed.
PasswordFilter() => Validates a new password based on password policy
Example Usage of Password Filters:
AD(Active Directory) Password Filters are used to notify Active directory Password changes to custom Products which need to be notified of AD passwords.
Links:
Password Filters - http://msdn.microsoft.com/en-us/library/ms721882.aspx
ISAPI Extentions and Filters
When to Use ISAPI Extensions
ISAPI extensions are best used in situations where you need to integrate a C or C++ library with your web application, or need to have specific, lower-level control over your application. For instance, you may need to integrate a proprietary database engine. Although in this case you could use native DLL calls from a .NET application, the amount of work to integrate the two could well be massive. An ISAPI extension is much like a CGI application (an executable that is similar to a script, and returns an HTML page), but with important differences. The most significant difference is that ISAPI extensions reside in IIS’s memory space, meaning a new process does not have to be created for every request. This by itself makes them far more scalable than CGI applications.
When to Use ISAPI Filters
ISAPI filters intercept a request at various stages as it moves through the pipeline. Filters are server-wide or site-wide, although they can be made to be applied only to certain requests. ISAPI filters were, for a long time, the only way to provide this functionality. Now ASP.NET HTTP modules, which reside completely inside the ASP.NET pipeline and are separate from IIS, provide a filter-like ability for ASP.NET pages.
Overview
Every ISAPI Extension is contained in a separate DLL written as Internet Web Server applications are required to export two entry points: GetExtensionVersion and HttpExtensionProc (TerminateExtension is optional).
Every ISAPI filter is contained in a separate DLL with two common entry points: GetFilterVersion and HttpFilterProc. When the DLL is loaded, GetFilterVersion is called. This lets the filter know the version of the server and also lets the filter tell the server the filter version and the events that the filter is interested in.
ISAPI is an API that allows developers to extend the IIS web server by plugging in native DLLs, written usually in C or C++ (although it's quite possible to write extensions in other languages that support compiling to native code and can import a C API, such as Delphi).
ISAPI actually plays two very separate roles in interaction with the web server. ISAPI extensions provide a way for native code to be executed to return a page (similar to an ASP script, for example).
ISAPI filters on the other hand deal with the request itself, as it moves through IIS, and can intercept and manipulate a request at many different stages in its lifetime.
ISAPI Filters are comparable to Apache modules, if you are familiar with the Apache web server.
Links:
ISAPI Programming - http://msdn2.microsoft.com/en-us/library/at50e70y(VS.80).aspx
ISAP Extensions and Filters - http://microsoft.apress.com/asptodayarchive/73978/isapi-extensions-and-filters
Developing ISAPI Extensions and Filters -
http://pcdoc.bibliothek.uni-halle.de/web-kurs/api/isapimrg.htm
ISAPI - http://www.microsoft.com/msj/0498/iis/iis.aspx
ISAPI Extensions - http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/iisbook/c06_isapi_extensions_and_filters.mspx?mfr=true
Internationalization(i18n) & Localization(L10n)
i18n - Internationatioanlization
l10n - Localization
Making your Software ready for Locanguage specifica Translation is called Internationalization(i18n)
Translating the Strings/Messages to particular Language(German,Italian,Japanese) is called Localization(l10n)
i18n Check-List
1.Isolating Hard Coded Messages (ex: Error Messages, Log Messages …) from the Source Code.
C++
Windows : ResourceDll
UNIX : Message Catalogue
Java : Resource Bundle (Property Files)
.NET : ResourceManager(System.Resources.ResourceManager) , Satelite Assemblies
2. Format DATE, TIME, NUMBERS & CURRENCIES accordingly
3. String Comparisons:
Normal String Functions (ex: strcmp () in C++) do Binary Comparisons of Strings. As UNICODE needs 2 Bytes Binary Comparison does not work. We need to use Collator Functions
C++ : strcoll ()
Java : Collator Class
4. Converting Non-Unicode Text to Unicode text
C++
Windows : MultiByteToWideChar (), WideCharToMultiByte ()
UNIX : Mbstowcs (), Wcstombs ()
Java : GetBytes ()
What is the difference between Stateful and Stateless encoding?
In stateful encoding, the data stream has special sign (i.e. escape sequence or shift-in shift-out). For example, ISO-2022-JP is a stateful encoding.
In ISO-2022-JP data stream, if we have Kanji character in the stream, it must at least 2 ‘ESC’ character. So you have to seek the stream from the beginning of it.
ISO-2022-JP is used for e-mail message in Japanese environment. All most of your development, I think you don’t need to consider about it.
Links:
Java Code Internationalization checklist - http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
.NET Localization - http://www.ondotnet.com/pub/a/dotnet/2002/09/30/manager.html
How To Create Localized Resource DLLs for MFC Application -http://support.microsoft.com/kb/198846
UTF-8, UTF-16, UTF-32 & BOM - http://unicode.org/faq/utf_bom.html
Zachman Framework
In 1987, John Zachman published the Zachman Framework for Enterprise Architecture. He wrote "To keep the business from disintegrating, the concept of information systems architecture is becoming less of an option and more of a necessity."
Intent
The Zachman Framework is influenced by principles of classical architecture that establish a common vocabulary and set of perspectives for describing complex enterprise systems. This influence is reflected in the set of rules that govern an ordered set of relationships that are balanced and orthogonal. By designing a system according to these rules, the architect can be assured of a design that is clean, easy to understand, balanced, and complete in itself. Zachman's Framework provides the blueprint, or architecture, for an organization's information infrastructure.
Scope
The Zachman Framework describes a holistic model of an enterprise's information infrastructure from six perspectives: planner, owner, designer, builder, subcontractor, and the working system. There is no guidance on sequence, process, or implementation of the framework. The focus is on ensuring that all aspects of an enterprise are well-organized and exhibit clear relationships that will ensure a complete system regardless of the order in which they are established.
Principles
By defining clear architectural design principles, Zachman ensures that any tailored or extended implementation will be equally well built as long as the designer and builder continue to follow the rules.
The major principles that guide the application of the Zachman Framework include:
1. A complete system can be modeled by depicting answers to the questions -
why, who,what, how, where, and when.
2. The six perspectives capture all the critical models required for system development.
3. The constraints for each perspective are additive; those of a lower row are added to those of the rows above to provide a growing number of restrictions.
4. The columns represent different abstractions in an effort to reduce the complexity of any s ingle model that is built.
5. The columns have no order.
6. The model in each column must be unique.
7. Each row represents a unique perspective.
8. Each cell is unique.
9. The inherent logic is recursive.
Remote Debugging using VC++ Editor & MSGina Debugging
To perform remote debugging, the Remote Debug Monitor is implemented. The Remote Debug Monitor is a small program that sits on the target computer, which communicates with the debugger and controls the execution of the program being debugged.
To install the Remote Debug Monitor on the target computer, do the following:
1. Copy the following files to the target computer
a. msvcmon.exe
b. msvcrt.dll
c. tln0t.dll
d. dm.dll
e. msvcp60.dll
f. msdis110.dll
g.psapi.dll is required only for Windows NT.
2.If you are using Windows 95/98, move the msvcrt.dll file to the Windows System directory and restart the computer.
a. On a Win32 computer, use these files:
b. msvcmon.exe
c. tlw3com.dll
d. dmw3.dll
(The files can be located in the ...\Microsoft Visual Studio\Common\MSDev98\bin subdirectory)
3. Set up a shared directory that can be viewed by both the remote machine and the local machine. The project should reside on the local machine.
4. Load the project into the Visual C++ development environment.
5. Open the Project Setting dialog box (Alt+F7). Then set the following options:
a. Executable for Debug Session—Enter the name and path of the executable as the local machine references it.
b. Additional DLLs—Enter the name and path of any DLLs as the local machine sees them.
c. Remote Executable Path—Enter the name and path of the executable as the remote computer sees it.
d. File Name— Enter the name of the file.
e. Working Directory—Should be blank.
6. Start msvcmon.exe on the remote machine to start the debugger. Click the Connect button to start the connection. (To start the debugger on Win32s platform, click the Visual C++ Debug Monitor icon from the Win32s program group.)
7. On the host computer, choose Debugger Remote Connection from the Build menu. Choose Network (TCP/IP) and then Settings. Enter the remote machine name or the IP address (password is not needed).
8. You now can begin debugging.
If a sharable directory cannot be made, copy the executable and any needed DLLs to the remote computer. The executables and DLLs must remain exactly the same all the time throughout the debugging process. Whenever they change on one machine, they must be copied to the other. All the other steps remain the same.
(If you are making use of VC++ .NET,
Copy the following files to the target computer:
a.msvcmon.exe
b.msvcr71.dll
c. natdbgtlnet.dll
d. natdbgdm.dll
e.psapi.dll (Windows NT 4.0 only)
(For dump support (for more information, see Dumps), install this file as well:
dbghelp.dll (supports dumps) )
Example: Debugging MSGina using Remote Debugging Technique
One of the instances where “Remote Debugging” can be used is while debugging MSGINA …
Remote GINA Debugging Technique
Debugging a GINA is somewhat of a hit and miss affair. Primarily, sufficient levels of debug logs can serve as the greatest tool that can provide an insight into what's going on between winlogon and GINA. Apart from that psychic powers can be beneficial. But, nothing can replace the real thing and thus the debugger is greatly missed. This could be easily remedied with Visual Studio remote debug tools. No longer debugging over serial cable is neccessary.
Rough instructions:
Create a debugging directory on target machine and add it to the %PATH%
Copy MSVCMON.EXE (The remote debugging server) to the debugging directory (along with all the DLLs it needs which are in the same directory as MSVCMON).
Install the debug GINA on target machine.
Get srvany and set it up to start msvcmon as a service on the target machine. I had to use tcpip as transport protocol (-tcpip) and allow all user connections (-anyuser). One more thing, the service has to run under an interactive user's account as LocalSystem? doesn't have network access.
So now we have the GINA DLL (and its dependencies) and the MSVCMON starting as a service on the target sysetm.
Load up the GINA project in Visual Studio on the system where debugging is to be done.
Choose to open the processes on the target machine remotely via TCP/IP. If everything worked, one should see a list of processes on the target machine. We choose Winlogon and attach to it...
At this point we can set breakpoints in the GINA source and get GINA on the remote machine to go over relevant execution paths to hit those breakpoints in the debugger!
XML Security: XACML and SAML
XACML and SAML: How different and how similar?
XACML architecture is tightly intertwined with SAML architecture. They both share a lot of concepts and a domain -- the domain of authentication, authorization, and access control. However, the problems they address in the same domain are different. While SAML addresses authentication and provides a mechanism for transferring authentication and authorization decisions between cooperating entities, XACML focuses on the mechanism for arriving at those authorization decisions.
The SAML standard provides interfaces that allow third parties to send their requests for authentication and authorization. How these authorization requests are processed internally is addressed by XACML standards. XACML not only processes the authorization requests, but it defines the mechanism for creating the complete infrastructure of rules, policies, and policy sets to arrive at the authorization decisions. Given that both SAML and XACML share the same domain, it is highly likely and desirable that these two specifications will eventually be merged into one.
Links:
Demystifying SAML - http://dev2dev.bea.com/lpt/a/456
XML Security: Control information access with XACML - http://www-128.ibm.com/developerworks/xml/library/x-xacml/
Opensource Testing Automation Frameworks/Tools Links FAQ
Links:
http://www.opensourcetesting.org/
http://www.developer.com/java/ent/article.php/3372151
http://www.sqa-test.com/toolpage.html
http://triumvir.org/articles/guitest-wd-mag/
http://www.tessella.com/Literature/supplements/pdf/autoGUI.pdf
http://www.manageability.org/blog/stuff/open-source-automated-test-tools-written-in-java/view
http://java-source.net/open-source/testing-tools
http://www.softwareqatest.com/qatweb1.html
http://www.aptest.com/resources.html
http://www.verifysoft.com/en_ctapp.html
http://www.parasoft.com/jsp/products/home.jsp?product=CppTest
http://www.veritest.com/services/scalability.asp
http://www.alertsite.com/web_load_testing.shtm
Why Unit Tests Matter and How They Will Save You Time - http://www.ddj.com/development-tools/208403755?cid=RSSfeed_DDJ_All
C++ Portability Rules
C++ Portability Rules.
1. Don't use C++ templates. (*)
2. Don't use static constructors.
3. Don't use exceptions.
4. Don't use Run-time Type Information.
5. Don't use namespace facility.
6. main() must be in a C++ file.
7. Use the common denominator between members of a C/C++ compiler family.
8. Don't put C++ comments in C code.
9. Don't put carriage returns in XP code.
10. Put a new line at end-of-file.
11. Don't put extra top-level semi-colons in code.
12. C++ filename extension is .cpp.
13. Don't mix varargs and inlines.
14. Don't use initializer lists with objects.
15. Always have a default constructor.
16. Don't put constructors in header files.
17. Be careful with inner-classes.
18. Be careful of variable declarations that require construction or initialization.
19. Make header files compatible with C and C++.
20. Be careful of the scoping of variables declared inside for() statements.
21. Declare local initialized aggregates as static.
22. Expect complex inlines to be non-portable.
23. Don't use return statements that have an inline function in the return expression.
24. Be careful with the include depth of files and file size.
25. Use virtual declaration on all subclass virtual member functions.
26. Always declare a copy constructor and assignment operator.
27. Be careful of overloaded methods with like signatures.
28.Type scalar constants to avoid unexpected ambiguities.
29.Always use PRBool or XP_Bool for Boolean variables in XP code.
30.Use macros for C++ style casts.
31.Don't use mutable.
32.Don't use reserved words as identifiers.
Stuff that is good to do for C or C++.
1.Do not wrap include statements with an #ifdef.
2.#include statements should include only simple filenames.
3.Macs complain about assignments in Boolean expressions.
4.Every source file must have a unique name.
5.Use #if 0 rather than comments to temporarily kill blocks of code.
6.Turn on warnings for your compiler, and then write warning free code
Links:
http://www.mozilla.org/hacking/portable-cpp.html
http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap18.html
http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap22.html
http://www.lisp-p.org/portable/portable.html
Frameworks vs (Class Libraries , Abstract Classes , Design Patterns)
Frameworks vs Class Libraries
Class libraries and framework s are (by definition) set of classes. But framework s have some distinctive characteristics that are not met by class libraries. Frameworks implement the concept of inversion of control while classes in class libraries are used and methods in these classes are called by the main program. This main control flow is written by the user not the developer of the class library. Class groups in frameworks almost always share invariants while classes in class libraries do not usually share invariants. Classes libraries have shared invariants if they incorporate frameworks.
Frameworks prescribe architecture for a problem solution and collaboration between the
objects. Class libraries do not describe architecture and implement only a very limited functionality. There are, of course, some class libraries which incorporate frameworks. In that case both the characteristics for the frameworks as well as the qualities for the class libraries hold.
Frameworks vs Abstract Classes
Both, the framework and the abstract class are abstract designs with a responsibility.Framework s almost always incorporate abstract classes and, therefore, use the concept of abstract classes.
But, the differences between abstract classes and framework s are:
An abstract class is exactly one class while a framework is a set of classes.
An abstract class is a small design with a limited functionality. A framework however,represents a larger design for an entire application or a subsystem.
Frameworks vs Design Patterns
At the first sight, it seems as if framework s were implemented design patterns. Even a careful analysis of the definitions of design pattern and framework does not help. A pattern is ``a recognizable way in which something is done, organized or happens'' .This definition certainly matches a framework. The definition of design pattern is too broad to be useful.
The definition of pattern in the pattern community is based on the observation that there is reoccurring solution to reoccurring problems. Thus, the problem a pattern solves is just as much a part of the pattern as the arrangement of objects that makes up the solution. A pattern is, therefore, ``a solution to problem in a context''. These patterns can not be easily expressed in object-oriented languages as we know them today.
On the other side, a framework is more than a design pattern as it is also code. A framework is an abstract design expressed in abstract classes and, therefore, in code. A framework contains a model for the object interaction and defines the kinds of classes. A framework will contain several design patterns.
So, both framework s and design pattern s are abstract designs to a given problem or problem family. But, design pattern s are much smaller and more abstract while frameworks use design pattern s and are expressed in code.
Links
URL Link: http://swt.cs.tu-berlin.de/~ron/diplom/node42.html
VC++ Function Calling Conventions
Most popular Function Calling Conventions:
1. _cdecl
2. pascal
3. _stdcall
4. _fastcall
Here is what each one does:
_cdecl
1. Arguments Passed from Right to Left
2. Calling Function Clears the Stack
3. ‘this’ pointer is passed via stack last in case of Programs using OOP
4. Functions using _cdecl are preceded by an “_”
Pascal
1. Arguments Passed from Left to Right
2. Called Function Clears the Stack
_stdcall
1. Arguments Passed from Right to Left
2. Called Function Clears the Stack
3. ‘this’ pointer passed via Stack Last
4. Functions Using _stdcall are preceded by a ‘_’ and end with ‘@’
_fastcall
1. Passes Arguments Via Registers. In case of unavailability of registers arguments are passed via the Stack.
2. Functions using Fastcall precede with a ‘@’.
Why Use Dynamic Loading of DLL ???
1. You don't have a lib file to link with - this is a pretty lame reason, since if you worked at it you could generate a LIB file. On the whole, though, generating a LIB file is probably more
work than just using LoadLibrary/GetProcAddress to dynamically load a DLL. A DLL may not always be present - if you want to provide for some graceful program degradation, you must dynamically load any DLL that may or may not be present on the target machine (example: UXTHEME.DLL, which exists only on XP). If you used implicit linking, your application would never have the chance to degrade gracefully - the system simply would not allow your app to start, and would instead display some alarming message to your user.
2. You need to support multiple feature sets - this is one of the historically valid reasons for using dynamic loading. If you have a product that supports many different features, and you
want to load only those features that the customer has paid for, then what you do is package
each feature set in its own DLL, and ship the DLL to the customer when he orders it. This is
also a very convenient way to add new features (read: plug-ins) to your product, essentially
making it open-ended.
3. You need to support multiple platforms - this is also one of the historically valid reasons for using dynamic loading. You need to support multiple platforms (Win98, Win2000, WinXP) and each platform requires slightly different code for some reason. A simple solution is to segregate the code for each platform in its own DLL.
4. You need to speed up the time it takes to load your application - this is another historical reason for using dynamic loading. You will start thinking about this when customers start complaining about how slow your app is to load. The idea is to identify what DLLs are necessary to display the core UI, and then dynamically load all the other DLLs that your app needs.
Composition vs Aggregation
In UML terms, a role can have one of three types:
1. Association
2. Composition
3. Aggregation.
Associations indicate that the two classes have a relationship as discussed above. Composition and aggregation indicate something more about the relationship:
Composition (Call By Value ) indicates that one class belongs to the other. It’s strong Aggregation ( represented by Blackend Diamond in UML) Whole is responsible for the parts Creation and Destruction . A polygon is made up of several points. If the polygon is destroyed, so are the points. A Owner has a house ; ( Aggregation ) ; A house has a chair ( Aggregation ) ; A house has Wall , Roof , Floor ( Composition ) ; A chair can exist independent of House ; When a house is destroyed Wall, Roof anf Floor will be destroyed,
Aggregation (Call by Reference ) is similar to composition, but is a less rigorous way of grouping things. It’s week Whole-Part Relationship ; ( Represented by Hallow Diamond in UML) ( Call By Reference ) An order is made up of several products, but a product continues to exist even if the order is destroyed.
Both aggregation and composition are special kinds of associations. Aggregation is used to represent ownership or a whole/part relationship, and composition is used to represent an even stronger form of ownership. With composition, we get coincident lifetime of part with the whole. The composite object has sole responsibility for the disposition of its parts in terms of creation and destruction. In implementation terms, the composite is responsible for memory allocation and deallocation.
Moreover, the multiplicity of the aggregate end may not exceed one; i.e., it is unshared. An object may be part of only one composite at a time. If the composite is destroyed, it must either destroy all its parts or else give responsibility for them to some other object. A composite object can be designed with the knowledge that no other object will destroy its parts.
Composition can be used to model by-value aggregation, which is semantically equivalent to an attribute. In fact, composition was originally called aggregation-by-value in an earlier UML draft, with “normal” aggregation being thought of as aggregation-by-reference. The definitions have changed slightly, but the general ideas still apply. The distinction between aggregation and composition is more of a design concept and is not usually relevant during analysis.
Finally, a word of warning on terminology:
While UML uses the terms association, aggregation, and composition with specific meanings, some object-oriented authors use one or more of these terms with slightly different interpretations. For example, it is fairly common to see all three UML relationships grouped under a single term, say composition, and then to discuss object-oriented relationships as being either inheritance (generalization) or composition.
Example:
class Professor;
class Department
{
...
private:
// Aggregation
Professor* members[5];
...
};
class University
{
...
private:
std::vector< Department > faculty;
...
create_dept()
{
...
// Composition (must limit to 20)
faculty.push_back( Department(...) );
faculty.push_back( Department(...) );
...
}
};
ref:
http://en.wikipedia.org/wiki/Object_composition#Aggregation
DESIGN PATTERNS
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups:
1. Creational
2. Structural
3. Behavioral
Creational Patterns
Abstract Factory - Creates an instance of several families of classes
Builder - Separates object construction from its representation
Factory Method - Creates an instance of several derived classes
Prototype - A fully initialized instance to be copied or cloned
Singleton - A class of which only a single instance can exist
Structural Patterns
Adapter - Match interfaces of different classes
Bridge - Separates an object’s interface from its implementation
Composite - A tree structure of simple and composite objects
Decorator - Add responsibilities to objects dynamically
Facade - A single class that represents an entire subsystem
Flyweight - A fine-grained instance used for efficient sharing
Proxy - An object representing another object
Behavioral Patterns
Chain of Resp - A way of passing a request between a chain of objects
Command - Encapsulate a command request as an object
Interpreter - A way to include language elements in a program
Iterator - Sequentially access the elements of a collection
Mediator - Defines simplified communication between classes
Memento - Capture and restore an object's internal state
Observer - A way of notifying change to a number of classes
State - Alter an object's behavior when its state changes
Strategy - Encapsulates an algorithm inside a class
Template Method - Defer the exact steps of an algorithm to a subclass
Visitor - Defines a new operation to a class without change
Links:
Non-Software Examples of Software Design Patterns -
http://www2.ukdw.ac.id/kuliah/info/TR3063/NonSoftwareExamplesOfSoftwareDesignPatterns.pdf
Design Patterns, Pattern Languages, and Frameworks -http://www.cs.wustl.edu/~schmidt/patterns.html
Microsoft Application Architecture Guide 2.0 eBook -http://www.codeplex.com/AppArchGuide/Release/ProjectReleases.aspx?ReleaseId=20586
Design Patterns Sample Code (C++ & Java) - http://www.vincehuston.org/dp/
Microsoft Architecture Journal - http://msdn.microsoft.com/en-us/architecture/bb410935.aspx
Microsoft Architecture Journal Reader (Beta) -http://www.microsoft.com/downloads/details.aspx?FamilyID=dd466bbb-1b7d-438e-9f9a-954ce2058f15&displaylang=en
Microsoft’s Home for Design patterns & practices – http://msdn.microsoft.com/en-us/practices/default.aspx
Inject Some Life into Your Applications: Getting to Know the Unity Application Block - http://msdn.microsoft.com/en-us/library/cc816062.aspx
Design Patterns: Solidify Your C# Application Architecture with Design Patterns – http://msdn.microsoft.com/en-us/magazine/cc301852.aspx
CSharp(C#) Design Patterns(with Sample Code) - http://www.dofactory.com/Patterns/Patterns.aspx
Java Design Patterns - http://www.patterndepot.com/put/8/JavaPatterns.htm
J2EE Patterns Catalog - http://java.sun.com/blueprints/patterns/catalog.html
J2EE Design Patterns - http://www.onjava.com/pub/a/onjava/2002/01/16/patterns.html
Gopalan Suresh Raj's blog - http://gsraj.tripod.com/
C Programming - Pointers
Pointers Varieties
(1) int *p; // p is a pointer to an integer quantity
(2) int *p[10]; // p is a 10-element array of pointers to integer quantities
(3) int (*p)[10]; // p is a pointer to a 10-element integer array
(4) int *p(void); // p is a function that returns a pointer to an integer quantity
(5) int p(char *a); // p is a function that accepts an argument which is a pointer to a character returns an // integer quantity
(6) int *p(char *a); // p is a function that accepts an argument which is a pointer to a character returns a // pointer to an integer quantity
(7) int (*p)(char *a); // p is pointer to a function that accepts an argument which is a pointer to a character // returns an integer quantity
(8) int (*p(char *a))[10]; // p is a function that accepts an argument which is a pointer to a character returns a // pointer to a 10-element integer array
(9) int p(char (*a)[]); // p is a function that accepts an argument which is a pointer to a character array returns // an integer quantity
(10) int p(char *a[]); // p is a function that accepts an argument which is a array of pointers to characters // returns an integer quantity
(11) int *p(char a[]); // p is a function that accepts an argument which is a character array returns a pointer to // to an integer quantity
(12) int *p(char (*a)[]); // p is a function that accepts an argument which is a pointer to a character array returns a // pointer to an integer quantity
(13) int *p(char *a[]); // p is a function that accepts an argument which is an array of pointers to characters // returns a pointer to an integer quantity
(14) int (*p)(char (*a)[]); // p is pointer to a function that accepts an argument which is a pointer to a character array // returns an integer quantity
(15) int *(*p)(char (*a)[]); // p is pointer to a function that accepts an argument which is a pointer to a character array // returns a pointer to an integer quantity
(16) int *(*p)(char *a[]); // p is pointer to a function that accepts an argument which is a array of pointers to // characters returns a pointer to an integer quantity
(17) int (*p[10])(void); // p is 10-element array of pointers to functions; each function returns an integer quantity
(18) int (*p[10])(char a); // p is 10-element array of pointers to functions; each function accepts an argument which is // a character and returns an integer quantity
(19) int *(*p[10])(char a); // p is 10-element array of pointers to functions; each function accepts an argument which is // a character and returns a pointer to an integer quantity
(20) int *(*p[10])(char *a); // p is 10-element array of pointers to functions; each function accepts an argument which is // a pointer to a character and returns a pointer to an integer quantity
Pointer-to-Pointer and Reference-to-Pointer
This article explains the reason behind using pointer-to-pointer and reference-to-pointer to modify a pointer passed to a function, to better understand their usage.
When we use "pass by pointer" to pass a pointer to a function, only a copy of the pointer is passed to the function. We can say "pass by pointer" is passing a pointer using "pass by value." In most cases, this does not present a problem. But, a problem arises when you modify the pointer inside the function. Instead of modifying the variable, it points to it by de-referencing. When you modify the pointer, you are only modifying a copy of the pointer and the original pointer remains unmodified.
Please look at the "Pointer-to-Pointer and Reference-to-Pointer" for the complete example.
All the Best !!!
Links
www.c4swimmers.net
Pointer-to-Pointer and Reference-to-Pointer -http://www.codeguru.com/cpp/cpp/cpp_mfc/pointers/article.php/c4089/
http://www.codeproject.com/KB/cpp/PtrToPtr.aspx
Linux Performance and Development Tools
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
- Brian W. Kernighan
Performance Analysis Tools
Benchmarks
LMbench - Low-level performance benchmark tools.
STREAM - Sustainable memory bandwidth benchmark.
Calibrator - A cache-memory and TLB latency measurement tool.
Bonnie++ - A disk I/O benchmark.
System Analysis
KCachegrind - Source intermixed with profiling data.
OProfile - A system-wide profiler.
The Linux Trace Toolkit - A kernel-level tracer.
Syscalltrack - Track invocations of system calls (a system-wide strace).
Dynamic Probes - Linux debugger that can be used to insert software probes dynamically into executing code.
Development Tools
Static Code Analysis
Splint - A static checker (was called clint).
RATS - Rough Auditing Tool for Security. Similar to Flawfinder.
Flawfinder - a program that examines source code for security issues. Similar to RATS.
Smatch - The Source Matcher, based on papers about the Stanford Checker.
Sparse - a static type-checking tool for the Linux kernel (written by Linus Torvalds).
Dynamic Debugging
Dmalloc - Debug malloc library.
Mpatrol - another debugging malloc library.
Valgrind - An open-source memory debugger.
Electric Fence - A memory bounds checker.
BFBTester - A tool that does quick proactive security checks of binaries.
Compilation and Documentation Tools
Ccache - A compiler cache. This is a MUST HAVE.
Doxygen - A documentation system.
Code Coverage Tools
Gcov - A code coverage tool that works with gcc
Ggcov - A GUI for gcov
Other Possibly Interesting Stuff
LSM - Linux Security Modules.
Mudflap and Libmudflap - Patches for gcc/egcs.
Static Code Analysis
Flawfinder - Static security analysis tool (written in Python).
ITS4 - Software Security Tool. Not under GPL.
Cqual - A tool for adding type qualifiers to C.
MOPS - MOdelchecking Programs for Security properties.
BOON - Buffer Overrun detectiON.
Test Suites
Linux Test Project
Open POSIX Test Suite
Links:
http://www.mostang.com/~davidm/papers/expo97/paper/doc004.html
Note:
All above information is available in Internet … I just gathered the info and put here … Just recompilation nothing more than that. Thanks a lot to the Webpage owners.
UNIX Commands
1. UNIX Mount Commands:
AIX: mount –r –v cdrfs /dev/cd0 /cdrom
HP-UX: mount –o cdcase –F cdfs /dev/dsk/c0t0d0 /cdrom
SCO OpenServer: mount –r /dev/cd0 /cdrom
SCO UnixWare: mount –F cdfs –o ro /dev/cdrom/cdrom1 /cdrom
Solaris: mount –r –F hsfs /dev/cd0 /cdrom
Linux: mount –r –t iso9660 /dev/cdrom /cdro
2. grep Command
Command to recursively grep for a pattern in a directory => find . xargs grep pattern