Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


July 2000

Inside Win32 Services, Part 2


RSS
Subscribe to Windows IT Pro | See More Internals and Architecture Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Learn how Win2K optimizes service startup and shutdown

I began this two-part series about Win32 services by presenting the structure of service applications, reviewing restrictions related to service user-account settings, and stepping through the first phases of the Service Control Manager's (SCM's) initialization. This time, I continue with a detailed description of how auto-start services initialize during the system boot. You'll also learn about the steps the SCM takes when a service fails during its startup, and about how the SCM shuts down services. Finally, I cover some new features of Windows 2000's services support, including service failure-recovery options.

Service Startup
SvcCtrlMain (the SCM's startup function) invokes the SCM function ScAutoStartServices to start all services that have an auto-start Start value. (ScAutoStartServices also starts auto-start device drivers, but for the purposes of this article, when I use the term services, I mean services and drivers, unless I indicate otherwise.) ScAutoStartServices' algorithm for starting services in the correct order proceeds in phases; each phase corresponds to a group, and phases proceed in the sequence that the group ordering stored in the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Control\ServiceGroupOrder Registry value defines. As I explained in Part 1, a service belongs to a group if the service's Registry key has a Group value. The ServiceGroupOrder value, which Figure 1, page 58, shows, lists the names of groups in the order in which the SCM starts them. Thus, assigning a service to a group has no effect other than to fine-tune its startup with respect to other services that belong to different groups.

When a phase starts, ScAutoStartServices marks for startup all the service entries that belong to the phase's group. Then, ScAutoStartServices loops through the marked services to determine whether it can start each one. Part of the check ScAutoStartServices makes consists of determining whether a service has a dependency on another group; the DependOnGroup value in the service's Registry key specifies group dependencies. If a dependency exists, then the group on which the service is dependent must already have initialized, and at least one service of the group must have started successfully. If the service depends on a group that starts later in the group startup sequence than the service's group, the SCM notes a circular dependency error for the service and doesn't start the service. If the service depends on any services from its group that haven't yet started, then ScAutoStartServices skips over the service. If ScAutoStartServices is checking a Win32 service and not a device driver, ScAutoStartServices next tries to determine whether the service depends on one or more other services, and if so, whether those other services have already started. The DependOnService Registry value in a service's Registry key stores service dependencies.

Before ScAutoStartServices starts a service that has passed the function's dependencies check, ScAutoStartServices makes a final check to determine whether the service is part of the current boot configuration. When a user boots the system in safe mode, the SCM ensures that either a name or a group identifies the service in the appropriate safe-boot Registry key. Two safe-boot keys, Minimal and Network, exist under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\SafeBoot; which safe-boot key the SCM checks depends on which safe mode the user booted. If the user chose standard safe mode or safe mode with command prompt at the special boot menu (to access the special boot menu, you press F8 when prompted in the boot process), the SCM references the Minimal key. If the user chose networking-enabled safe mode, the SCM references the Network key. The existence of the Option string value under the SafeBoot key signals that the system booted in safe mode and lists the safe-mode type the user selected. (For more information about safe-mode booting options, see "Inside Win2K Reliability Enhancements, Part 1," August 1999.)

After the SCM decides to start a service, it calls ScStartService, which takes different steps to start services than to start device drivers. When ScStartService starts a Win32 service, the function first reads the ImagePath value from the service's Registry key to determine the name of the file that runs the service's process. Then, ScStartService examines the service's Type value; if this value is SERVICE_WIN32_SHARE_PROCESS, the SCM ensures that the process the service runs in, if already started, is logged in using the same account as specified for the service. A service's ObjectName Registry value stores the user account in which the service will run. A service with no ObjectName or with the LocalSystem ObjectName runs in the Local System account, an account with security privileges that I described in Part 1.

To verify that the service's process has not already started in a different account, the SCM checks to see whether the service's ImagePath value has an entry in the image database, an internal SCM database. If the image database doesn't have an entry for the service's ImagePath, the SCM creates the entry. Image database entries store a logon account name and an ImagePath value. When it creates a new image database entry, the SCM includes the logon account name for the service and the service's ImagePath value.

All services must have an ImagePath value; if not, the SCM doesn't start the service and generates an error stating that it couldn't find the service's path. If the SCM locates an existing image database entry with a matching ImagePath value, the SCM ensures that the user-account information for the service is the same as that stored in the database entry. Because a process can be logged on only as one account, the SCM reports an error if a service specifies an account name that is different from the account name of another service that has already started in the same process.

The SCM calls ScLogonAndStartImage to optionally log on a service and start the service's process. To log on services that don't run in the system account, the SCM calls the Local Security Authority Subsystem (LSASS—\winnt\system32\lsass.exe) function LsaLogonUser. LsaLogonUser requires a password, and the SCM signals to LSASS that the password for a service that doesn't run in the system account is stored as a services LSASS secret under the HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets Registry key. When the SCM calls LsaLogonUser, the SCM specifies a service logon as the logon type, so LSASS looks up the password as a name in the form _SC_<service name> under the Secrets subkey. The SCM directs LSASS to store a logon password as a secret when a Service Control Program (SCP) configures a service's logon information. When the logon is successful, LsaLogonUser returns a handle to an access token to the SCM. Win2K uses access tokens to represent a user's security context, and the SCM later associates the token it received from LsaLogonUser with the process that implements the service.

After a successful logon, the SCM calls the UserEnv DLL's (\winnt\system32\userenv.dll) LoadUserProfile function to load the account's profile information, if the information isn't already loaded. LoadUserProfile loads the Registry hive (i.e., Registry file) that the user's profile key under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Winlogon\ProfileList points to, making the hive the HKEY_CURRENT_USER key for the service.

An interactive service must open the WinSta0 window station, but before ScLogonAndStartImage lets an interactive service access WinSta0, the function confirms whether the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\NoInteractiveServices value is set. Administrators set this value to prevent interactive services from displaying windows on the console. This option is desirable in unattended server environments, where no user is present to respond to pop-ups from interactive services.

Next, ScLogonAndStartImage launches the service's process if the process hasn't already started (e.g., for another service). The SCM uses the CreateProcessAsUser Win32 API to start the process in a suspended state. The SCM next creates a named pipe through which it communicates with the service process and assigns the pipe the name \Pipe\Net\NetControlPipex, where x is a number that increments each time the SCM creates a pipe. The SCM uses the ResumeThread API to resume the service process and waits for the service to connect to its SCM pipe. If the Registry value HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServicesPipeTimeout exists, it determines the length of time that the SCM waits for a service to call StartServiceCtrlDispatcher and connect before the SCM gives up, terminates the process, and concludes that the service failed to start. If the ServicesPipeTimeout value doesn't exist, the SCM uses a default timeout of 30 seconds. The SCM uses the same timeout value for all its service communications.

When a service connects to the SCM through the pipe that the SCM created, the SCM sends the service a start command. If the service fails to respond positively to the start command within the timeout period, the SCM moves on to start the next service. When a service doesn't respond to a start request, the SCM doesn't terminate the process (as the SCM does when a service doesn't call StartServiceCtrlDispatcher within the timeout period). Instead, the SCM records an error in the System event log that the service failed to start in a timely manner.

If the service the SCM starts with a call to ScStartService has a SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER Value type, the service is actually a device driver. In that case, ScStartService calls ScLoadDeviceDriver to load the driver. ScLoadDeviceDriver enables the load driver security privilege for the SCM process and invokes the kernel service NtLoadDriver, passing the ImagePath value of the driver's Registry key to the function. Unlike services, drivers don't need to specify an ImagePath value. If a driver doesn't specify an ImagePath value, the SCM concatenates the driver's name with \winnt\system32\drivers to build an ImagePath.

ScAutoStartServices continues looping through the services in a group until all the group's services have either started or generated dependency errors. This looping process is how the SCM automatically orders services within a group according to their DependOnService dependencies. The SCM starts services that other services depend on in earlier loops, leaving the dependent services for subsequent loops. The SCM ignores Tag values for Win32 services. You might come across Tag values in Registry keys under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. The I/O Manager uses Tag values to order device-driver startup for boot and system-start drivers.

After the SCM completes the startup phases for all the groups that the ServiceGroupOrder value lists, the SCM performs a startup phase for services that belong to groups that the value doesn't list. Finally, the SCM completes a final startup phase for services that don't belong to any group.

   Previous  [1]  2  3  Next 


Reader Comments
I am wondering if somebody has seen the following behavior:

An NT_service controls a VB executable and the executable launches through OLE automation multiple external objects using a CreateObject method. This works fine when the VB executable runs as an application but not as an NT service.

Depending on the size of the object when running as an NT Service it fails to create the second or third object.

Is there any parameter in the registry that could fix that problem ?

Stelios Papastratos September 20, 2001


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.

Nitin Chhabra October 09, 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

hiep December 24, 2003


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

Thanks

shiva May 04, 2004


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

Anonymous User November 06, 2004 (Article Rating: )


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

Anonymous User April 18, 2005 (Article Rating: )


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
WinInfo Short Takes: Week of November 24, 2008

An often irreverent look at some of the week's other news, including a Vista Capable dismissal request, Zune price reductions, Morrow musings, Novell and Microsoft sitting in a tree ... two years later, Yahoo!, IE 6 on Windows Mobile, and so much more ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

PsExec

This freeware utility lets you execute processes on a remote system and redirect output to the local system. ...


Related Articles Inside Win32 Services, Part 1

Windows OSs Whitepapers Why SaaS is the Right Solution for Log Management

Related Events Check out our list of Free Email Newsletters!

Windows OSs eBooks Understanding and Leveraging Code Signing Technologies

A Guide to Windows Certification and Public Keys

SQL Server Administration for Oracle DBAs

Related Windows OSs Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro Windows Dev Pro IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing