Subscribe to Windows IT Pro
June 13, 2000 08:17 AM

Inside Win32 Services, Part 2

Windows IT Pro
InstantDoc ID #8943
Rating: (2)

Service Shutdown
When Winlogon calls the Win32 ExitWindowsEx API, ExitWindowsEx sends a message to CSRSS, the Win32 subsystem process, that invokes CSRSS's shutdown routine. CSRSS loops through all active processes and notifies them that the system is shutting down. For every system process except the SCM, CSRSS waits for the number of seconds that HKEY_USERS\.DEFAULT\Control Panel\Desktop\WaitToKillAppTimeout specifies (the default is 20 seconds) for the process to exit before moving to the next process. When CSRSS encounters the SCM process, CSRSS notifies the SCM that the system is shutting down and employs a timeout specific to the SCM. The process ID that the SCM used when it registered with CSRSS during system initialization lets CSRSS recognize the SCM. The SCM's timeout differs from that of other processes because the SCM communicates with services that need to perform cleanup when they shut down; thus, an administrator might need to tune only the SCM's timeout. The SCM's timeout value resides in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\WaitToKillServicesTimeout Registry value and defaults to 30 seconds.

The SCM's shutdown handler sends shutdown notifications to all services that request shutdown notification when they initialize with the SCM. The SCM function ScShutdownAllServices loops through the SCM services database searching for services that request shutdown notification and sends each such service a shutdown command. For each service to which ScShutdownAllServices sends a shutdown command, the SCM records the value of the service's wait hint, a value that a service also specifies when it registers with the SCM. The SCM keeps track of the largest wait hint it records. After ScShutdownAllServices sends shutdown messages, the SCM waits until one of the services notified of shutdown exits or until the largest wait hint's timeout passes.

If the wait hint expires before a service exits, the SCM determines whether one or more of the services upon which it was waiting has sent a message notifying the SCM that the service is progressing in its shutdown process. If at least one service made progress toward shutdown, the SCM waits again for the duration of the largest wait hint's timeout. The SCM continues this wait loop until either all the services have exited or none of the services upon which it is waiting has sent notification of shutdown progress within the wait hint's timeout.

After the SCM has directed services to shut down and is waiting for the services to exit, CSRSS waits for the SCM to exit. If CSRSS's wait ends before the SCM exits (i.e., the WaitToKillServicesTimeout expires), CSRSS simply continues the shutdown process. Thus, CSRSS leaves running those services (as well as the SCM) that fail to shut down in a timely manner as the system shuts down. Unfortunately, administrators have no way of knowing whether they should raise the WaitToKillServicesTimeout value on systems on which services are not getting a chance to completely shut down before the system shuts down.

Shared Service Processes
Running every service in its own process, rather than having services share a process when sharing is possible, wastes system resources. However, when services share a process, any service in the shared process that has a bug that causes the process to exit also causes all the services in the process to terminate. Win2K includes many built-in services, so Microsoft chose a mix of approaches to maximize system stability and minimize resource usage.

In both Win2K and NT 4.0, the SCM process hosts many services, including the EventLog service, the file-server service (LanmanServer), and the LAN Manager name-resolution service. Table 1 lists the services that the SCM hosts in Win2K (not every service is active on every system). You can use the Tlist program from the Win2K support tools CD-ROM with the /s option to obtain a list of which services run in processes.

In NT 4.0, the SCM is the only process that the system uses to host multiple built-in services. Several other services, such as the Remote Procedure Call Subsystem service (RpcSs), the Telephony API service (TapiSrv), and Remote Access Manager (RasMan), use separate processes.

Because of the increased number of built-in services in Win2K, Microsoft decided to include more services in the Win2K SCM and to add new processes to act as service hosts. In NT 4.0, the LSASS process included only the Netlogon service. In Win2K, several security-related services (e.g., the Security Accounts Manager Subsystem—SamSs—the Netlogon service, and the Win2K Policy Agent service) share the LSASS process.

Win2K also introduces Service Host (SvcHost—\winnt\system32\svchost.exe), an application that exists solely to execute in processes that host services. A Win2K system can start multiple instances of SvcHost running in different processes. Services that run in SvcHost processes include TapiSrv, RpcSs, and RasMan. Win2K implements services that run in SvcHost as DLLs and includes an ImagePath definition of the form \%systemroot%\system32\svchost.exe -k netsvcs in the services' Registry key. The services' Registry key must also have a Registry value of ServiceDll under a Parameters subkey that points to the services' DLL file.

All services that share a common SvcHost process specify the same parameter (-k netsvcs in the previous example) so that they each have the same entries in the SCM's image database. When the SCM first encounters a service during service startup with a SvcHost ImagePath and a particular parameter, the SCM creates a new image database entry and launches a SvcHost process with the parameter. The new SvcHost process looks under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SvcHost for a value that has the same name as the service's parameter. SvcHost interprets the contents of the value as a list of service names; when it registers with the SCM, SvcHost notifies the SCM that the SvcHost process is hosting those services. Figure 5 presents an example of a SvcHost Registry key that shows that a SvcHost process started with the -k netsvcs parameter is prepared to host many different network-related services.

When the SCM encounters a SvcHost service during service startup with an ImagePath that matches an entry that already appears in the SCM's image database, the SCM doesn't launch a second process. Rather, the SCM sends a start command for the service to the SvcHost process that is already started for that ImagePath value. The existing SvcHost process reads the ServiceDll parameter in the service's Registry key and loads the DLL into the service's process to start the service.

Service Control Programs
SCPs are standard Win32 applications that use SCM APIs that ADVAPI32 exports. APIs that the SCM implements include CreateService, OpenService, StartService, ControlService, QueryServiceStatus, and DeleteService. To use a SCM API, an SCP must first call the OpenSCManager API to open a communications channel to the SCM. At the time of the open call, the SCP must specify the types of actions it wants to perform. For example, if an SCP wants to enumerate and display the services in the SCM's database, the SCP requests enumerate-service access in its call to OpenSCManager. As the SCM initializes, it creates an internal object that represents the SCM database. The SCM uses the Win2K security APIs to protect the internal object, a security descriptor that specifies which accounts can open the object with which access permissions. For example, the security descriptor specifies that the Everyone group (of which every account is a member) has permission to open the SCM internal object with enumerate-service access. However, only administrators have permission to open the object with the access required to create or delete a service.

The SCM implements security for services, as it does for the SCM database. When an SCP uses the CreateService API to create a service, the SCP specifies a security descriptor that the SCM internally associates with the service's entry in the service database. The SCM stores the security descriptor in the service's Registry key as the Security value and reads the value when it scans the Registry's Services key during initialization. This setup ensures that the security settings persist across reboots. Just as an SCP must specify in its call to OpenSCManager what types of access the SCP wants to the SCM database, an SCP must tell the SCM in a call to OpenService what access the SCP wants to a service. Accesses that an SCP can request include the ability to query a service's status and to configure, stop, and start a service.

The SCP that you're likely most familiar with is the Control Panel Services applet in NT 4.0 and the Services MMC snap-in in Win2K. The NT 4.0 Control Panel Services applet implements its SCP in the \winnt\system32\srvmgr.cpl library, and in Win2K, the SCP resides in \winnt\system32\filemgr.dll. The Microsoft Windows NT Server 4.0 Resource Kit and the Microsoft Windows 2000 Resource Kit include sc.exe, a command-line SCP.

SCPs sometimes layer service policy over services that the SCM implements. A good example is the timeout that the Services MMC snap-in implements when you start a service manually. The snap-in displays a progress bar that represents the service's startup progress. Whereas the SCM waits indefinitely for a service to respond to a start command, the Services snap-in waits only 2 minutes before the progress bar reaches 100 percent and the snap-in announces that the service didn't start in a timely manner. Services indirectly interact with SCPs by adjusting their configuration status to reflect their progress as they respond to SCM commands such as the start command. SCPs query services' status with the QueryServiceStatus API. Thus, SCPs can tell when a service actively updates its status or appears to be hung, and the SCM can take action to notify users about the service's activity.

SrvAny
The Win2K and NT 4.0 resource kits include the SrvAny utility, which lets you run any application as a service. (For information about how to use SrvAny, see Mark Minasi, This Old Resource Kit, February 2000 and March 2000.) SrvAny is similar to SvcHost—both are generic service-host applications. As in SvcHost, a SrvAny process reads the path of the service file that it loads from the Parameters subkey of the service's Registry key. When SrvAny starts, it notifies the SCM that it is hosting a particular service. Then, when SrvAny receives a start command, it launches the service executable file as a child process. Because the child process receives a copy of the SrvAny process' access token and a reference to the same window station, the executable file runs in the same security account and with the same interactivity setting that you specified when you configured the SrvAny process. Unlike SvcHost, however, SrvAny services don't have the share-process Type value. Therefore, each application you install as a service in SrvAny runs in a separate process with a different instance of the SrvAny host program.

Network Drive Letters
In addition to its role as a services interface, the SCM has another responsibility: It notifies GUI applications in a system whenever the system creates or deletes a network drive-letter connection. The SCM waits for the LAN Manager Workstation service to signal the ScNetDrvMsg named event. (The Workstation service signals ScNetDrvMsg whenever an application assigns a drive letter to a remote network share or deletes a remote-share drive letter assignment.) When the Workstation service signals the event, the SCM uses the GetDriveType Win32 API to query the list of connected network drive letters. If the list changes across the event signal, the SCM sends a type WM_DEVICECHANGE Windows broadcast message. The SCM uses either DBT_DEVICEREMOVECOMPLETE or DBT_DEVICEARRIVAL as the message's subtype. This message is intended primarily for Windows Explorer, so that it can update any open My Computer windows to show the presence or absence of a network drive letter.

A Better Handle on Services
Although the SCM remained mostly unchanged from NT 4.0 to Win2K, it picked up the powerful new capability of detecting service process failures and taking recovery steps to restart services or run arbitrary programs. In addition, Win2K's use of the SvcHost application reduces the overhead otherwise incurred with the increase in the number of built-in Win2K services. This information about service startup and shutdown can help you better understand what is going on behind the scenes so that you can troubleshoot service-related problems you might encounter.

Related Content:

ARTICLE TOOLS

Comments
  • Anonymous User
    7 years ago
    Apr 18, 2005

    I have created an error signature szappname:
    svchost.exe szappver:5. 1.0.0 sz mod name:

  • Anonymous User
    8 years ago
    Nov 06, 2004

    You are supposed to post comments here, not ask questions.

  • Shiva
    8 years ago
    May 04, 2004

    I would like to start a service S1 after S2 is started. How do I do it?

    Thanks

  • hiep
    9 years ago
    Dec 24, 2003

    This is very great article. One thing is missing? When a service starts as "Autmatic", what is the PATH the system used to find out all of the services' dependent DLL(s) if the service depends on those DLL(s).

    Thanks

    Hiep

  • Nitin Chhabra
    9 years ago
    Oct 09, 2003

    Great article!
    I have written a service that is created and started by an app. SUppose tthe service is running and I reboot the system. After reboot My service just crashes. IT is 'Auto start' sertvice. ANy ideas or comments will be greatly appreciated.

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.