Saturday, September 4, 2010

Svchost From A To Z - Part 3

In the beginning of this post, i want to remind you with the difference between 2 variables that you should be aware of.
1)ServiceNames is a global variable that points at the REG_MULTI_SZ extracted from the registry representing the names of the services under the current category.

2)ServiceArray which is an array to elements each of type _SERVICE_ARRAY_ELEMNT
struct _SERVICE_ARRAY_ELEMENT
{
wchar_t* srv_name;
_SRV_DLL_INFO* srv_dll_info;
char* SvcMainName;
unsigned long Count;
FUNCPTR d;
};
None of _SERVICE_ARRAY_ELEMENT memebrs except srv_name is filled till now.
As you can see in the figure above,each _SERVICE_ARRAY_ELEMENT::srv_name points at a string in ServiceNames.
///-----
Now after you became aware of the difference between ServiceNames and ServiceArray,we will now go to the Service Table and how it is constructed.
Generally,the service Table is an array of _SERVICE_TABLE_ELEMENT
struct _SERVICE_TABLE_ELEMENT
{
wchar_t* lpServiceName;
FUNCPTR2 lpFuncPtr;
};
Documented in MSDN under the name of SERVICE_TABLE_ENTRY.
First member of this structure is the service name
Second member is the service code entry point.
//-------------------------
Function BuildServiceTable has the task of constructing the service table.
It does the following
1)Given ServiceCount ,Memory for the service table is allocated.
2)Each _SERVICE_TABLE_ELEMENT::lpServiceName takes _SERVICE_ARRAY_ELEMENT::srv_name.
i.e it is also made to point at a string in ServiceNames.
3)Each _SERVICE_TABLE_ELEMENT::lpFuncPtr is made to hold the address of a function residing in svchost.exe called ServiceStarter.
And this function is the Entry point for every service ,responsible for doing some initialization tasks then calling the service specific entry point.
N.B The last Service table element must be zero.
And here is the c++ code for this function
Once the service table is constructed,it should be passed to StartServiceCtrlDispatcher.
StartServiceCtrlDispatcher connects the svchost instance main thread to the SCM(Service control manager) which decides which service of the ones in the Service table to be started.
For each service approved by the scm to be started,a new thread for this Service is created within svchost instance.
For more info about the SCM and StartServiceCtrlDispatcher ,refer to the MSDN.

In earlier posts,we categoried the functions within svchost into
1)functions running once per instance
like BuildCommandOptions,BuildServiceArray,BuildServiceTable and StartServiceCtrlDispatcher.
2)functions running per service.
like ServerStarter

we finished discussing the first category.
So in the next post we will discuss the function ServiceStarter.

Any suggestions or ideas are very welcome.

No comments:

Post a Comment