Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2533 lines
72 KiB

  1. /*++
  2. Copyright (c) 1992 Microsoft Corporation
  3. Module Name:
  4. dataman.cxx
  5. Abstract:
  6. Contains code for the Service Control Database manager. This includes
  7. all the linked list routines. This file contains the following
  8. functions:
  9. ScGetOrderGroupList
  10. ScGetStandaloneGroupList
  11. ScGetServiceDatabase
  12. ScGetUnresolvedDependList
  13. ScActivateServiceRecord
  14. ScCreateImageRecord
  15. ScCreateServiceRecord
  16. ScFreeServiceRecord
  17. ScAddConfigInfoServiceRecord
  18. ScDecrementUseCountAndDelete
  19. ScProcessDeferredList
  20. ScFindEnumStart
  21. ScGetNamedImageRecord
  22. ScGetNamedServiceRecord
  23. ScGetDisplayNamedServiceRecord
  24. ScGetTotalNumberOfRecords
  25. ScInitDatabase
  26. ScProcessCleanup
  27. ScDeleteMarkedServices
  28. ScRemoveService
  29. ScDeleteImageRecord (internal only)
  30. ScDeactivateServiceRecord
  31. ScTerminateServiceProcess (internal only)
  32. ScUpdateServiceRecordConfig
  33. ScNotifyServiceObject
  34. Author:
  35. Dan Lafferty (danl) 04-Feb-1992
  36. Environment:
  37. User Mode -Win32
  38. Revision History:
  39. 22-Oct-1998 jschwart
  40. Convert SCM to use NT thread pool APIs
  41. 22-Oct-1997 JSchwart (after AnirudhS in _CAIRO_ 12-Apr-1995)
  42. Enabled changes made in ifdef _CAIRO_ on 12-Apr-1995.
  43. Removed ScNotifyServiceObject.
  44. 08-Jan-1997 AnirudhS
  45. Replaced ScDatabaseLockFcn and ScGroupListLock with the new
  46. locking scheme in lock.cxx. Rewrote ScDeferredList processing.
  47. 04-Dec-1996 AnirudhS
  48. Added calls to service crash recovery code.
  49. 12-Jul-1996 AnirudhS
  50. ScDecrementUseCountAndDelete: Don't actually process the deferred
  51. list in this routine, because a number of calling routines assume
  52. that the service record does NOT go away when they call this routine.
  53. Instead, process it when a database lock is released.
  54. 25-Jun-1996 AnirudhS
  55. ScProcessCleanup: Fix the use of a freed service record. Don't
  56. try to upgrade shared lock to exclusive, as it can deadlock.
  57. 25-Oct-1995 AnirudhS
  58. ScAddConfigInfoServiceRecord: Fix heap corruption bug caused by
  59. security descriptor being freed twice, the second time by
  60. ScProcessDeferredList.
  61. 20-Sep-1995 AnirudhS
  62. ScDeleteMarkedServices: Fix heap corruption bug caused by service
  63. record being deleted using LocalFree instead of HeapFree.
  64. 26-Jun-1995 AnirudhS
  65. Added ScNotifyServiceObject.
  66. 12-Apr-1995 AnirudhS
  67. Added AccountName field to image record.
  68. 21-Jan-1994 Danl
  69. ScAddConfigInfoServiceRecord: If no DisplayName, or the DisplayName
  70. is an empty string, or the DisplayName is the same as the
  71. ServiceName, then just point to the ServiceName for the DisplayName.
  72. 22-Oct-1993 Danl
  73. Moved Group and Dependency function into groupman.c.
  74. 16-Sept-1993 Danl
  75. ScProcessCleanup: Get the shared lock prior to walking through the
  76. database looking for the one to cleanup. Then get the exclusive
  77. lock to modify it. Remove assert.
  78. 12-Feb-1993 Danl
  79. ScActivateServiceRecord now increments the UseCount. This is to
  80. balance the fact that we decrement the UseCount when we
  81. deactivate the service record.
  82. 28-Aug-1992 Danl
  83. Re-Added ScGetTotalNumberOfRecords function. This is needed
  84. by the ScShutdownAllServices function.
  85. 14-Apr-1992 JohnRo
  86. Use SC_ASSERT() macro.
  87. Made changes suggested by PC-LINT.
  88. 10-Apr-1992 JohnRo
  89. Use ScImagePathsMatch() to allow mixed-case image names.
  90. Make sure DeleteFlag gets a value when service record is created.
  91. Added some assertion checks.
  92. 04-Feb-1992 Danl
  93. created
  94. --*/
  95. //
  96. // INCLUDES
  97. //
  98. #include "precomp.hxx"
  99. #include <userenv.h> // UnloadUserProfile
  100. #include <stdlib.h> // wide character c runtimes.
  101. #include <ntrpcp.h> // MIDL_user_allocate
  102. #include <control.h> // SendControl
  103. #include "scconfig.h" // ScGenerateServiceDB,ScInitSecurityProcess
  104. #include "scsec.h" // ScCreateScServiceObject
  105. #include "account.h" // ScRemoveAccount
  106. #include <sclib.h> // ScImagePathsMatch().
  107. #include "bootcfg.h" // ScDeleteRegTree().
  108. #include <strarray.h> // ScWStrArraySize
  109. extern "C" {
  110. #include <cfgmgr32.h>
  111. #include "cfgmgrp.h" // RegisterServiceNotification
  112. }
  113. //
  114. // Macros
  115. //
  116. // for every service record in the database...
  117. // (a slightly more efficient definition of this macro for use within
  118. // this file)
  119. //
  120. #undef FOR_ALL_SERVICES
  121. #define FOR_ALL_SERVICES(SR) \
  122. SC_ASSERT(ScServiceListLock.Have()); \
  123. for (LPSERVICE_RECORD SR = ServiceDatabase.Next; \
  124. SR != NULL; \
  125. SR = SR->Next)
  126. //
  127. // Defines and Typedefs
  128. //
  129. class DEFER_LIST
  130. {
  131. public:
  132. VOID Add (LPSERVICE_RECORD ServiceRecord);
  133. VOID Process();
  134. private:
  135. DWORD TotalElements; // size of ServiceRecPtr array
  136. DWORD NumElements; // numElements in array
  137. LPSERVICE_RECORD * ServiceRecordPtr; // pointer to array
  138. };
  139. //
  140. // Globals
  141. //
  142. //
  143. // These are the linked list heads for each of the databases
  144. // that are maintained.
  145. //
  146. IMAGE_RECORD ImageDatabase;
  147. SERVICE_RECORD ServiceDatabase;
  148. DWORD ScTotalNumServiceRecs;// number of services
  149. //
  150. // Service Record index number. This allows enumeration to be broken
  151. // up into several calls.
  152. //
  153. DWORD ResumeNumber;
  154. //
  155. // The ScGlobalDeferredList points to a structure that contains an
  156. // array of pointers to service records. The first two elements in
  157. // the structure contain the size and number of element information
  158. // about the array.
  159. // Access to the list is guarded by ScServiceRecordLock.
  160. //
  161. DEFER_LIST ScDeferredList;
  162. //
  163. // ServiceRecord Heap Information
  164. //
  165. // ServiceRecord Heap - is where all the service records are allocated
  166. // from.
  167. // OrderedHash Heap - Service Names can be found via a (very simple) hash
  168. // table. There is an array of pointers (one for each letter of
  169. // alphabet), where each pointer points to the top of an array of
  170. // pointers to service records. All the service records in that array
  171. // will have names beginning with the same letter. The service record
  172. // pointers will be ordered as to the frequency of access.
  173. //
  174. HANDLE ServiceRecordHeap = NULL;
  175. HANDLE OrderedHashHeap = NULL;
  176. //
  177. // Local Function Prototypes
  178. //
  179. VOID
  180. ScDeferredListWorkItem(
  181. IN PVOID pContext
  182. );
  183. //****************************************************************************/
  184. // Miscellaneous Short Functions
  185. //****************************************************************************/
  186. LPSERVICE_RECORD
  187. ScGetServiceDatabase(
  188. VOID
  189. )
  190. {
  191. return ServiceDatabase.Next;
  192. }
  193. /****************************************************************************/
  194. VOID
  195. ScActivateServiceRecord (
  196. IN LPSERVICE_RECORD ServiceRecord,
  197. IN LPIMAGE_RECORD ImageRecord
  198. )
  199. /*++
  200. Routine Description:
  201. This function can be called with or without a pointer to an ImageRecord.
  202. If it is called without the pointer to the ImageRecord, just the
  203. ServiceRecord is initialized to the START_PENDING state, and the UseCount
  204. is incremented.
  205. If it is called with the pointer to the ImageRecord, then the ImageRecord
  206. pointer is added to the ServiceRecord, and the ImageUseCount
  207. is incremented.
  208. Arguments:
  209. ServiceRecord - This is a pointer to the ServiceRecord that is to be
  210. activated.
  211. ImageRecord - This is a pointer to the ImageRecord that the service
  212. record will point to.
  213. Notes:
  214. This routine assumes that the Exclusive database lock has already
  215. been obtained.
  216. Return Value:
  217. returns 0. (It used to return a service count - but it wasn't used
  218. anywhere).
  219. --*/
  220. {
  221. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  222. if (ImageRecord == NULL)
  223. {
  224. ServiceRecord->ImageRecord = NULL;
  225. ServiceRecord->ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
  226. ServiceRecord->ServiceStatus.dwControlsAccepted = 0;
  227. ServiceRecord->ServiceStatus.dwWin32ExitCode = NO_ERROR;
  228. ServiceRecord->ServiceStatus.dwServiceSpecificExitCode = 0;
  229. ServiceRecord->ServiceStatus.dwCheckPoint = 0;
  230. ServiceRecord->ServiceStatus.dwWaitHint = 2000;
  231. ServiceRecord->UseCount++;
  232. SC_LOG2(USECOUNT, "ScActivateServiceRecord: " FORMAT_LPWSTR
  233. " increment USECOUNT=%lu\n",
  234. ServiceRecord->ServiceName,
  235. ServiceRecord->UseCount);
  236. }
  237. else
  238. {
  239. //
  240. // Increment the service count in the image record.
  241. //
  242. ServiceRecord->ImageRecord = ImageRecord;
  243. ServiceRecord->ImageRecord->ServiceCount++;
  244. }
  245. return;
  246. }
  247. /****************************************************************************/
  248. DWORD
  249. ScCreateImageRecord (
  250. OUT LPIMAGE_RECORD *ImageRecordPtr,
  251. IN LPWSTR ImageName,
  252. IN LPWSTR AccountName,
  253. IN DWORD Pid,
  254. IN HANDLE PipeHandle,
  255. IN HANDLE ProcessHandle,
  256. IN HANDLE TokenHandle,
  257. IN HANDLE ProfileHandle,
  258. IN DWORD ImageFlags
  259. )
  260. /*++
  261. Routine Description:
  262. This function allocates storage for a new Image Record, and links
  263. it into the Image Record Database. It also initializes all fields
  264. in the record with the passed in information.
  265. Arguments:
  266. ImageRecordPtr - This is a pointer to where the image record pointer
  267. is to be placed.
  268. ImageName - This is a pointer to a NUL terminated string containing
  269. the name of the image file.
  270. AccountName - This is either NULL (to represent the LocalSystem account)
  271. or a pointer to a NUL terminated string containing the name of the
  272. account under which the image was started.
  273. Pid - This is the Process ID for that the image is running in.
  274. PipeHandle - This is a handle to the pipe that is used to communicat
  275. with the image process.
  276. ProcessHandle - This is a handle to the image process object.
  277. TokenHandle - This is a handle to the process's logon token. It
  278. is NULL if the process runs in the LocalSystem context.
  279. ProfileHandle -
  280. ImageFlags -
  281. Return Value:
  282. NO_ERROR - The operation was successful.
  283. ERROR_NOT_ENOUGH_MEMORY - Unable to allocate buffer for the image
  284. record.
  285. ERROR_LOCKED - Exclusive access to the database could
  286. not be obtained.
  287. Note:
  288. This routine temporarily acquires the exclusive database lock.
  289. --*/
  290. {
  291. LPIMAGE_RECORD imageRecord; // The new image record pointer
  292. LPIMAGE_RECORD record ; // Temporary pointer
  293. LPWSTR stringArea; // String area in allocated buffer.
  294. TOKEN_STATISTICS TokenStats;
  295. DWORD dwError;
  296. //
  297. // Allocate space for the new record (including the string)
  298. //
  299. imageRecord = (LPIMAGE_RECORD)LocalAlloc(LMEM_ZEROINIT,
  300. sizeof(IMAGE_RECORD)
  301. + WCSSIZE(ImageName)
  302. + (AccountName ? WCSSIZE(AccountName) : 0)
  303. );
  304. if (imageRecord == NULL)
  305. {
  306. SC_LOG(TRACE,"CreateImageRecord: Local Alloc failure rc=%ld\n",
  307. GetLastError());
  308. return(ERROR_NOT_ENOUGH_MEMORY);
  309. }
  310. //
  311. // Copy the strings into the new buffer space.
  312. //
  313. stringArea = (LPWSTR)(imageRecord + 1);
  314. (VOID) wcscpy (stringArea, ImageName);
  315. imageRecord->ImageName = stringArea;
  316. if (AccountName)
  317. {
  318. stringArea += (wcslen(stringArea) + 1);
  319. (VOID) wcscpy (stringArea, AccountName);
  320. imageRecord->AccountName = stringArea;
  321. }
  322. else
  323. {
  324. imageRecord->AccountName = NULL;
  325. }
  326. //
  327. // Update the rest of the fields in the Image Record
  328. //
  329. imageRecord->Next = NULL;
  330. imageRecord->Pid = Pid;
  331. imageRecord->PipeHandle = PipeHandle;
  332. imageRecord->ProcessHandle = ProcessHandle;
  333. imageRecord->ServiceCount = 0;
  334. imageRecord->TokenHandle = TokenHandle;
  335. imageRecord->ProfileHandle = ProfileHandle;
  336. imageRecord->ObjectWaitHandle = NULL;
  337. imageRecord->ImageFlags = ImageFlags;
  338. if (TokenHandle == NULL)
  339. {
  340. LUID SystemLuid = SYSTEM_LUID;
  341. RtlCopyLuid(&imageRecord->AccountLuid, &SystemLuid);
  342. }
  343. else
  344. {
  345. //
  346. // Get the unique session ID for this process
  347. //
  348. if (!GetTokenInformation(TokenHandle,
  349. TokenStatistics, // Information wanted
  350. &TokenStats,
  351. sizeof(TokenStats), // Buffer size
  352. &dwError)) // Size required
  353. {
  354. dwError = GetLastError();
  355. SC_LOG1(ERROR,
  356. "ScCreateImageRecord: GetTokenInformation FAILED %d\n",
  357. dwError);
  358. LocalFree(imageRecord);
  359. return dwError;
  360. }
  361. imageRecord->AccountLuid.LowPart = TokenStats.AuthenticationId.LowPart;
  362. imageRecord->AccountLuid.HighPart = TokenStats.AuthenticationId.HighPart;
  363. }
  364. //
  365. // Add record to the Image Database linked list.
  366. //
  367. CServiceRecordExclusiveLock Lock;
  368. record = &ImageDatabase;
  369. ADD_TO_LIST(record, imageRecord);
  370. *ImageRecordPtr = imageRecord;
  371. return(NO_ERROR);
  372. }
  373. /****************************************************************************/
  374. DWORD
  375. ScCreateServiceRecord(
  376. IN LPWSTR ServiceName,
  377. OUT LPSERVICE_RECORD *ServiceRecord
  378. )
  379. /*++
  380. Routine Description:
  381. This function creates a new "inactive" service record and adds it to
  382. the service record list. A resume number is assigned so that it
  383. can be used as a key in enumeration searches.
  384. To initialize the service record with the fields from the registry,
  385. call ScAddConfigInfoServiceRecord.
  386. Arguments:
  387. ServiceName - This is a pointer to the NUL terminated service name
  388. string.
  389. ServiceRecord - Receives a pointer to the service record created and
  390. inserted into the service record list.
  391. Return Value:
  392. NO_ERROR - The operation was successful.
  393. ERROR_NOT_ENOUGH_MEMORY - The call to allocate memory for a new
  394. service record failed.
  395. Note:
  396. This routine assumes that the caller has exclusively acquired the
  397. database lock.
  398. --*/
  399. {
  400. DWORD status = NO_ERROR;
  401. LPSERVICE_RECORD record; // Temporary pointer
  402. LPWSTR nameArea; // NameString area in allocated buffer.
  403. DWORD nameSize; // num bytes in service name.
  404. SC_ASSERT(ScServiceListLock.HaveExclusive());
  405. // (The service record lock is not needed here since we don't touch
  406. // the service record after adding it to the service list)
  407. //
  408. // Allocate the new service record.
  409. //
  410. nameSize = (DWORD) WCSSIZE(ServiceName);
  411. (*ServiceRecord) = (LPSERVICE_RECORD)HeapAlloc(
  412. ServiceRecordHeap,
  413. HEAP_ZERO_MEMORY,
  414. nameSize + sizeof(SERVICE_RECORD)
  415. );
  416. if ((*ServiceRecord) == NULL)
  417. {
  418. SC_LOG0(ERROR,"CreateServiceRecord: HeapAlloc failure\n");
  419. return ERROR_NOT_ENOUGH_MEMORY;
  420. }
  421. //
  422. // Copy the ServiceName into the new buffer space.
  423. //
  424. nameArea = (LPWSTR)((LPBYTE)(*ServiceRecord) + sizeof(SERVICE_RECORD));
  425. (VOID) wcscpy (nameArea, ServiceName);
  426. //
  427. // At this point we have the space for a service record, and it
  428. // contains the name of the service.
  429. //
  430. //
  431. // Fill in all the fields that need to be non-zero.
  432. // Note: The display name is initialized to point to the service name.
  433. //
  434. (*ServiceRecord)->ServiceName = nameArea;
  435. (*ServiceRecord)->DisplayName = nameArea;
  436. (*ServiceRecord)->ResumeNum = ResumeNumber++;
  437. (*ServiceRecord)->Signature = SERVICE_SIGNATURE;
  438. (*ServiceRecord)->ImageRecord = NULL;
  439. (*ServiceRecord)->StartDepend = NULL;
  440. (*ServiceRecord)->StopDepend = NULL;
  441. (*ServiceRecord)->ErrorControl = SERVICE_ERROR_NORMAL;
  442. (*ServiceRecord)->StatusFlag = 0;
  443. (*ServiceRecord)->ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  444. (*ServiceRecord)->ServiceStatus.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
  445. (*ServiceRecord)->StartState = SC_NEVER_STARTED;
  446. //
  447. // Add the service to the service record linked list.
  448. //
  449. record = &ServiceDatabase;
  450. ADD_TO_LIST(record, (*ServiceRecord));
  451. ScTotalNumServiceRecs++;
  452. return(status);
  453. }
  454. /****************************************************************************/
  455. VOID
  456. ScFreeServiceRecord(
  457. IN LPSERVICE_RECORD ServiceRecord
  458. )
  459. /*++
  460. Routine Description:
  461. This function frees up a service record that has already been removed
  462. from the service record list.
  463. Arguments:
  464. ServiceRecord - Receives a pointer to the service record to free.
  465. --*/
  466. {
  467. if (!HeapFree(ServiceRecordHeap, 0, ServiceRecord))
  468. {
  469. SC_LOG2(ERROR,
  470. "ScFreeServiceRecord: HeapFree for %ws service failed %d\n",
  471. ServiceRecord->ServiceName,
  472. GetLastError());
  473. }
  474. return;
  475. }
  476. /****************************************************************************/
  477. DWORD
  478. ScAddConfigInfoServiceRecord(
  479. IN LPSERVICE_RECORD ServiceRecord,
  480. IN DWORD ServiceType,
  481. IN DWORD StartType,
  482. IN DWORD ErrorControl,
  483. IN LPWSTR Group OPTIONAL,
  484. IN DWORD Tag,
  485. IN LPWSTR Dependencies OPTIONAL,
  486. IN LPWSTR DisplayName OPTIONAL,
  487. IN PSECURITY_DESCRIPTOR Sd OPTIONAL
  488. )
  489. /*++
  490. Routine Description:
  491. This function adds the configuration information to the service
  492. record.
  493. NOTE: This function is called when the service controller is
  494. reading service entries from the registry at startup, as well as
  495. from RCreateServiceW.
  496. Arguments:
  497. ServiceRecord - Pointer to the service record to modify.
  498. DisplayName - A string that is the displayable name for the service.
  499. ServiceType - Indicates whether the ServiceRecord is for a win32 service
  500. or a device driver.
  501. StartType - Specifies when to start the service: automatically at boot or
  502. on demand.
  503. ErrorControl - Specifies the severity of the error if the service fails
  504. to start.
  505. Tag - DWORD identifier for the service. 0 means no tag.
  506. Group - Name of the load order group this service is a member of.
  507. Dependencies - Names of services separated by colon which this service
  508. require to be started before it can run.
  509. Sd - Security descriptor for the service object. If NULL, i.e. could
  510. not read from registry, create a default one.
  511. Return Value:
  512. NO_ERROR - The operation was successful.
  513. ERROR_NOT_ENOUGH_MEMORY - The call to allocate memory for a new
  514. service record or display name failed.
  515. Note:
  516. This routine assumes that the caller has exclusively acquired both the
  517. database lock and the GroupListLock.
  518. If this call is successful, do the following before freeing the memory
  519. of the service record in ScDecrementUseCountAndDelete:
  520. ScDeleteStartDependencies(ServiceRecord);
  521. ScDeleteGroupMembership(ServiceRecord);
  522. ScDeleteRegistryGroupPointer(ServiceRecord);
  523. --*/
  524. {
  525. DWORD status;
  526. SC_ASSERT(ScGroupListLock.HaveExclusive());
  527. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  528. //
  529. // Fill in the service record.
  530. //
  531. ServiceRecord->StartType = StartType;
  532. ServiceRecord->ServiceStatus.dwServiceType = ServiceType;
  533. ServiceRecord->ErrorControl = ErrorControl;
  534. ServiceRecord->Tag = Tag;
  535. //
  536. // The display name in the service record already points to the
  537. // ServiceName string. If the DisplayName is present and different
  538. // from the ServiceName, then allocate storage for it and copy the
  539. // string there.
  540. //
  541. SC_LOG0(SECURITY,"ScAddConfigInfoServiceRecord: Allocate for display name\n");
  542. if ((DisplayName != NULL) && (*DisplayName != L'\0') &&
  543. (_wcsicmp(DisplayName,ServiceRecord->ServiceName) != 0))
  544. {
  545. ServiceRecord->DisplayName = (LPWSTR)LocalAlloc(
  546. LMEM_FIXED,
  547. WCSSIZE(DisplayName));
  548. if (ServiceRecord->DisplayName == NULL)
  549. {
  550. SC_LOG(TRACE,"ScAddConfigInfoServiceRecord: LocalAlloc failure rc=%ld\n",
  551. GetLastError());
  552. return ERROR_NOT_ENOUGH_MEMORY;
  553. }
  554. wcscpy(ServiceRecord->DisplayName,DisplayName);
  555. }
  556. //
  557. // Create a default security descriptor for the service.
  558. //
  559. if (! ARGUMENT_PRESENT(Sd))
  560. {
  561. SC_LOG0(SECURITY,"ScAddConfigInfoServiceRecord: create service obj\n");
  562. if ((status = ScCreateScServiceObject(
  563. &ServiceRecord->ServiceSd
  564. )) != NO_ERROR)
  565. {
  566. goto ErrorExit;
  567. }
  568. }
  569. else
  570. {
  571. SC_LOG1(SECURITY,
  572. "ScAddConfigInfoServiceRecord: Using " FORMAT_LPWSTR
  573. " descriptor from registry\n", ServiceRecord->ServiceName);
  574. ServiceRecord->ServiceSd = Sd;
  575. }
  576. SC_LOG0(SECURITY,"ScAddConfigInfoServiceRecord: Get Group List Lock\n");
  577. //
  578. // Save the group membership information.
  579. //
  580. SC_LOG0(SECURITY,"ScAddConfigInfoServiceRecord: create group memebership\n");
  581. if ((status = ScCreateGroupMembership(
  582. ServiceRecord,
  583. Group
  584. )) != NO_ERROR)
  585. {
  586. goto ErrorExit;
  587. }
  588. SC_LOG0(SECURITY,"ScAddConfigInfoServiceRecord: create Reg Grp Ptr\n");
  589. if ((status = ScCreateRegistryGroupPointer(
  590. ServiceRecord,
  591. Group
  592. )) != NO_ERROR)
  593. {
  594. ScDeleteGroupMembership(ServiceRecord);
  595. goto ErrorExit;
  596. }
  597. //
  598. // Don't create dependencies list yet. Just save the string in
  599. // the service record.
  600. //
  601. if ((Dependencies != NULL) && (*Dependencies != 0))
  602. {
  603. //
  604. // If StartType is BOOT_START or SYSTEM_START, it is invalid
  605. // for the service to be dependent on another service. It can
  606. // only be dependent on a group.
  607. //
  608. // N.B. This check has been removed. There doesn't seem to be
  609. // any point in enforcing it, and remote boot needs to
  610. // allow NetBT to be dependent Tcpip.
  611. //
  612. DWORD DependenciesSize = 0;
  613. DWORD EntryByteCount;
  614. LPWSTR Entry = Dependencies;
  615. while (*Entry != 0)
  616. {
  617. #if 0
  618. if (StartType == SERVICE_BOOT_START ||
  619. StartType == SERVICE_SYSTEM_START)
  620. {
  621. if (*Entry != SC_GROUP_IDENTIFIERW)
  622. {
  623. SC_LOG1(ERROR, "ScAddConfigInfoServiceRecord: Boot or System "
  624. "start driver " FORMAT_LPWSTR " must depend on a group\n",
  625. ServiceRecord->DisplayName);
  626. ScEvent(
  627. EVENT_INVALID_DRIVER_DEPENDENCY,
  628. ServiceRecord->DisplayName
  629. );
  630. status = ERROR_INVALID_PARAMETER;
  631. ScDeleteGroupMembership(ServiceRecord);
  632. ScDeleteRegistryGroupPointer(ServiceRecord);
  633. goto ErrorExit;
  634. }
  635. }
  636. #endif
  637. EntryByteCount = (DWORD) WCSSIZE(Entry); // This entry and its null.
  638. DependenciesSize += EntryByteCount;
  639. Entry = (LPWSTR) ((DWORD_PTR) Entry + EntryByteCount);
  640. }
  641. DependenciesSize += sizeof(WCHAR);
  642. ServiceRecord->Dependencies = (LPWSTR)LocalAlloc(
  643. 0,
  644. DependenciesSize
  645. );
  646. if (ServiceRecord->Dependencies == NULL)
  647. {
  648. ScDeleteGroupMembership(ServiceRecord);
  649. ScDeleteRegistryGroupPointer(ServiceRecord);
  650. goto ErrorExit;
  651. }
  652. RtlCopyMemory(ServiceRecord->Dependencies, Dependencies, DependenciesSize);
  653. }
  654. return NO_ERROR;
  655. ErrorExit:
  656. if (DisplayName != NULL)
  657. {
  658. LocalFree(ServiceRecord->DisplayName);
  659. }
  660. RtlDeleteSecurityObject(&ServiceRecord->ServiceSd);
  661. //
  662. // Prevent ScProcessDeferredList from trying to free the same heap block
  663. // again later
  664. //
  665. ServiceRecord->ServiceSd = NULL;
  666. return status;
  667. }
  668. /****************************************************************************/
  669. VOID
  670. ScDecrementUseCountAndDelete(
  671. LPSERVICE_RECORD ServiceRecord
  672. )
  673. /*++
  674. Routine Description:
  675. This function decrements the UseCount for a service, and it the
  676. UseCount reaches zero and the service is marked for deletion,
  677. it puts a pointer to the service record into an array of
  678. such pointers that is stored in a deferred list structure. The
  679. pointer to this structure is stored at the global location called
  680. ScDeferredList. Access to this list is synchronized by use of the
  681. ScServiceRecordLock.
  682. A large number of routines in the service controller walk the
  683. service database and sometimes call this function, either directly
  684. or indirectly. It would complicate the programming of all those
  685. routines if they all had to assume that service records could get
  686. deleted under them. Therefore, this function never actually deletes
  687. any service record. Instead, it starts a separate thread that first
  688. acquires all three locks exclusively and then processes the deferred
  689. list.
  690. Note: By jumping through hoops, it is possible to avoid creating
  691. that thread in certain cases, but since service deletion is a rather
  692. rare operation, it was not considered worthwhile to create very-
  693. difficult-to-maintain code to optimize it.
  694. NOTE: The caller is expected to hold the Exclusive DatabaseLock
  695. prior to calling this function.
  696. The following functions call this routine:
  697. ScDeactivateServiceRecord
  698. RCloseServiceHandle
  699. ScGetDriverStatus
  700. ScStartServiceAndDependencies
  701. Arguments:
  702. ServiceRecord - This is a pointer to the service record that is having
  703. its use count deleted.
  704. Return Value:
  705. none.
  706. --*/
  707. {
  708. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  709. if (ServiceRecord->UseCount == 0)
  710. {
  711. //
  712. // The use count should not ever be zero when we enter this routine.
  713. //
  714. SC_LOG1(ERROR,"ScDecrementUseCountAndDelete: Attempt to decrement UseCount beyond zero.\n"
  715. "\t"FORMAT_LPWSTR" \n", ServiceRecord->ServiceName);
  716. SC_ASSERT(FALSE);
  717. }
  718. else
  719. {
  720. if ((ServiceRecord->UseCount == 1) &&
  721. (DELETE_FLAG_IS_SET(ServiceRecord)))
  722. {
  723. //
  724. // If the use count is one, we have a special case. We want
  725. // to postpone decrementing this last time until we have the
  726. // group list lock.
  727. //
  728. //
  729. // Put the service record pointer in the list, and start a
  730. // separate thread to process the list.
  731. //
  732. ScDeferredList.Add(ServiceRecord);
  733. }
  734. else
  735. {
  736. //
  737. // If the use count is greater than one, or the service is
  738. // NOT marked for delete, then we want to decrement the use
  739. // count and that is all.
  740. //
  741. ServiceRecord->UseCount--;
  742. SC_LOG2(USECOUNT, "ScDecrementUseCountAndDelete: " FORMAT_LPWSTR
  743. " decrement USECOUNT=%lu\n", ServiceRecord->ServiceName, ServiceRecord->UseCount);
  744. }
  745. }
  746. return;
  747. }
  748. /****************************************************************************/
  749. VOID
  750. DEFER_LIST::Add(
  751. LPSERVICE_RECORD ServiceRecord
  752. )
  753. /*++
  754. Routine Description:
  755. This function adds a service record to the list of service records to
  756. be deleted. It then starts a thread that will acquire all the locks
  757. and perform the actual deletion, if such a thread hasn't already been
  758. started.
  759. ScServiceRecordLock is used to ensure that only one thread accesses
  760. the deferred list at a time.
  761. The following functions call this routine:
  762. ScDecrementUseCountAndDelete
  763. --*/
  764. {
  765. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  766. if (NumElements + 1 > TotalElements)
  767. {
  768. //
  769. // Reallocate the array with a bit more room
  770. //
  771. DWORD NewTotalElements = TotalElements + 4;
  772. LPSERVICE_RECORD * NewArray = (LPSERVICE_RECORD *)
  773. LocalAlloc(0, NewTotalElements * sizeof(LPSERVICE_RECORD));
  774. if (NewArray == NULL)
  775. {
  776. SC_LOG(ERROR, "DEFER_LIST::Add: LocalAlloc FAILED %lu\n", GetLastError());
  777. return;
  778. }
  779. if (ServiceRecordPtr != NULL)
  780. {
  781. RtlCopyMemory(NewArray, ServiceRecordPtr,
  782. NumElements * sizeof(LPSERVICE_RECORD));
  783. LocalFree(ServiceRecordPtr);
  784. }
  785. TotalElements = NewTotalElements;
  786. ServiceRecordPtr = NewArray;
  787. }
  788. //
  789. // At this point we have a deferred list that can hold the new element.
  790. //
  791. ServiceRecordPtr[NumElements] = ServiceRecord;
  792. NumElements++;
  793. SC_LOG(LOCKS, "Added %ws service to deferred list\n",
  794. ServiceRecord->ServiceName);
  795. //
  796. // If we created the deferred list, queue a workitem (start a
  797. // thread) to process it.
  798. //
  799. if (NumElements == 1)
  800. {
  801. NTSTATUS ntStatus;
  802. ntStatus = RtlQueueWorkItem(ScDeferredListWorkItem, // callback function
  803. NULL, // context
  804. WT_EXECUTEONLYONCE); // flags
  805. if (!NT_SUCCESS(ntStatus))
  806. {
  807. SC_LOG(ERROR,"Couldn't add DeferredListWorkItem, 0x%x\n",
  808. ntStatus);
  809. }
  810. else
  811. {
  812. SC_LOG0(LOCKS,"Work item will process deferred list\n");
  813. }
  814. }
  815. }
  816. /****************************************************************************/
  817. VOID
  818. DEFER_LIST::Process(
  819. VOID
  820. )
  821. /*++
  822. Routine Description:
  823. This function loops through each service record pointer in the
  824. ScDeferredList, and decrements the UseCount for that ServiceRecord.
  825. If that count becomes zero, and if the ServiceRecord is marked
  826. for deletion, This routine will delete the service record and
  827. the registry entry for that service.
  828. This function frees the memory pointed to by ScDeferredList, when
  829. it is done processing the list.
  830. This routine acquires all 3 database locks.
  831. The following functions call this routine:
  832. CGroupListLock::Release
  833. Arguments:
  834. none.
  835. Return Value:
  836. none.
  837. --*/
  838. {
  839. //
  840. // Wait until we have acquired all 3 locks in the proper order
  841. //
  842. SC_LOG0(LOCKS, "In ScProcessDeferredList, waiting for locks\n");
  843. CGroupListExclusiveLock GLock;
  844. CServiceListExclusiveLock LLock;
  845. CServiceRecordExclusiveLock RLock;
  846. //
  847. // For each element in the list, delete the service information, and
  848. // free up its associated resources.
  849. //
  850. for (DWORD i=0; i<NumElements; i++)
  851. {
  852. LPSERVICE_RECORD ServiceRecord = ServiceRecordPtr[i];
  853. if (ServiceRecord->UseCount == 0)
  854. {
  855. SC_LOG1(ERROR,"ScProcessDeferredList: Attempt to decrement UseCount beyond zero.\n"
  856. "\t"FORMAT_LPWSTR" \n", ServiceRecord->ServiceName);
  857. SC_ASSERT(FALSE);
  858. }
  859. else
  860. {
  861. //
  862. // The use count is not zero, so we want to decrement it.
  863. // NOTE that even though the count was 1 when we put it in
  864. // the deferred list, it may have been incremented in the
  865. // mean-time.
  866. // CODEWORK: Why doesn't ScDecrementUseCountAndDelete just
  867. // decrement the UseCount to zero itself? If it did, we
  868. // wouldn't need RLock at all here, just LLock.
  869. //
  870. ServiceRecord->UseCount--;
  871. SC_LOG2(USECOUNT, "ScProcessDeferredList: " FORMAT_LPWSTR
  872. " decrement USECOUNT=%lu\n", ServiceRecord->ServiceName, ServiceRecord->UseCount);
  873. }
  874. if ((ServiceRecord->UseCount == 0) &&
  875. (DELETE_FLAG_IS_SET(ServiceRecord)))
  876. {
  877. SC_LOG1(USECOUNT,"ScProcessDeferredList:DELETING THE ("FORMAT_LPWSTR") SERVICE\n",
  878. ServiceRecord->ServiceName);
  879. //
  880. // Check to see if there is an LSA secret object to delete
  881. //
  882. if (ServiceRecord->ServiceStatus.dwServiceType & SERVICE_WIN32_OWN_PROCESS)
  883. {
  884. HKEY ServiceNameKey;
  885. LPWSTR AccountName;
  886. //
  887. // Open the service name key.
  888. //
  889. if (ScOpenServiceConfigKey(
  890. ServiceRecord->ServiceName,
  891. KEY_READ,
  892. FALSE, // Create if missing
  893. &ServiceNameKey
  894. ) == NO_ERROR)
  895. {
  896. //
  897. // Read the account name from the registry.
  898. //
  899. if (ScReadStartName(
  900. ServiceNameKey,
  901. &AccountName
  902. ) == NO_ERROR)
  903. {
  904. if (AccountName != NULL
  905. &&
  906. _wcsicmp(AccountName, SC_LOCAL_SYSTEM_USER_NAME) != 0)
  907. {
  908. ScRemoveAccount(ServiceRecord->ServiceName);
  909. }
  910. LocalFree(AccountName);
  911. } // Got the StartName
  912. ScRegCloseKey(ServiceNameKey);
  913. }
  914. } // endif SERVICE_WIN32_OWN_PROCESS
  915. LocalFree(ServiceRecord->Dependencies);
  916. //
  917. // Free up the DisplayName space.
  918. //
  919. if (ServiceRecord->DisplayName != ServiceRecord->ServiceName)
  920. {
  921. LocalFree(ServiceRecord->DisplayName);
  922. }
  923. ScDeleteGroupMembership(ServiceRecord);
  924. ScDeleteRegistryGroupPointer(ServiceRecord);
  925. ScDeleteStartDependencies(ServiceRecord);
  926. ScDeleteStopDependencies(ServiceRecord);
  927. if (ServiceRecord->ServiceSd != NULL)
  928. {
  929. RtlDeleteSecurityObject(&ServiceRecord->ServiceSd);
  930. }
  931. delete ServiceRecord->CrashRecord;
  932. //*******************************
  933. // Delete the registry node for
  934. // This service.
  935. //*******************************
  936. DeleteServicePlugPlayRegKeys(ServiceRecord->ServiceName);
  937. ScDeleteRegServiceEntry(ServiceRecord->ServiceName);
  938. REMOVE_FROM_LIST(ServiceRecord);
  939. ScFreeServiceRecord(ServiceRecord);
  940. } // End If service can be deleted.
  941. } // End for each element in the list.
  942. //
  943. // The deferred list is no longer needed free it.
  944. //
  945. LocalFree(ServiceRecordPtr);
  946. ServiceRecordPtr = NULL;
  947. TotalElements = 0;
  948. NumElements = 0;
  949. SC_LOG0(LOCKS, "Returning from ScProcessDeferredList\n");
  950. }
  951. /****************************************************************************/
  952. BOOL
  953. ScFindEnumStart(
  954. IN DWORD ResumeIndex,
  955. OUT LPSERVICE_RECORD *ServiceRecordPtr
  956. )
  957. /*++
  958. Routine Description:
  959. This function finds the first service record to begin the enumeration
  960. search with by finding the next service record folloing the resumeIndex.
  961. Service records are indexed by a ResumeNum value that is stored in
  962. each service record. The numbers increment as the linked list is
  963. walked.
  964. Arguments:
  965. ResumeIndex - This index is compared against the ResumeNum in the
  966. services records. The pointer to the next service record beyond
  967. the ResumeIndex is returned.
  968. ServiceRecordPtr - This is a pointer to a location where the pointer
  969. to the returned service record is to be placed.
  970. Return Value:
  971. TRUE - Indicates that there are service records beyond the resume index.
  972. FALSE - Indicates that there are no service records beyond the resume
  973. index.
  974. Note:
  975. --*/
  976. {
  977. FOR_SERVICES_THAT(serviceRecord, serviceRecord->ResumeNum > ResumeIndex)
  978. {
  979. *ServiceRecordPtr = serviceRecord;
  980. return TRUE;
  981. }
  982. return FALSE;
  983. }
  984. /****************************************************************************/
  985. BOOL
  986. ScGetNamedImageRecord (
  987. IN LPWSTR ImageName,
  988. OUT LPIMAGE_RECORD *ImageRecordPtr
  989. )
  990. /*++
  991. Routine Description:
  992. This function searches for an Image Record that has a name matching
  993. that which is passed in.
  994. NOTE: If this function is called, it is to find a shareable Image Record
  995. of the given name.
  996. Arguments:
  997. ImageName - This is a pointer to a NUL terminated image name string.
  998. This may be in mixed case.
  999. ImageRecordPtr - This is a pointer to a location where the pointer to
  1000. the Image Record is to be placed.
  1001. Note:
  1002. The Database Lock must be held with at least shared access prior to
  1003. calling this routine.
  1004. Return Value:
  1005. TRUE - if the record was found.
  1006. FALSE - if the record was not found.
  1007. --*/
  1008. {
  1009. if (ImageName == NULL)
  1010. {
  1011. SC_LOG(TRACE,"GetNamedImageRecord: Name was NULL\n",0);
  1012. return (FALSE);
  1013. }
  1014. SC_ASSERT(ScServiceRecordLock.Have());
  1015. //
  1016. // Check the database of running images
  1017. //
  1018. for (PIMAGE_RECORD imageRecord = ImageDatabase.Next;
  1019. imageRecord != NULL;
  1020. imageRecord = imageRecord->Next)
  1021. {
  1022. //
  1023. // We need a shareable Image Record, so check the ImageFlags
  1024. //
  1025. if (ScImagePathsMatch(imageRecord->ImageName, ImageName) &&
  1026. (imageRecord->ImageFlags & CANSHARE_FLAG))
  1027. {
  1028. *ImageRecordPtr = imageRecord;
  1029. return TRUE;
  1030. }
  1031. }
  1032. return FALSE;
  1033. }
  1034. /****************************************************************************/
  1035. DWORD
  1036. ScGetNamedServiceRecord (
  1037. IN LPWSTR ServiceName,
  1038. OUT LPSERVICE_RECORD *ServiceRecordPtr
  1039. )
  1040. /*++
  1041. Routine Description:
  1042. Uses the service name to look through the service and device linked
  1043. lists until it finds a match. Inactive services can be identified by
  1044. finding CurrentState = SERVICE_STOPPED.
  1045. Arguments:
  1046. ServiceName - This is a pointer to a NUL terminated service name string.
  1047. ServiceRecordPtr - This is a pointer to a location where the pointer to
  1048. the Service Record is to be placed.
  1049. Return Value:
  1050. NO_ERROR - if the record was found.
  1051. ERROR_SERVICE_DOES_NOT_EXIST - if the service record was not found in
  1052. the linked list.
  1053. ERROR_INVALID_NAME - if the service name was NULL.
  1054. Note:
  1055. The caller is expected to grab the lock before calling this routine.
  1056. --*/
  1057. {
  1058. if (ServiceName == NULL)
  1059. {
  1060. SC_LOG0(TRACE,"GetNamedServiceRecord: Name was NULL\n");
  1061. return ERROR_INVALID_NAME;
  1062. }
  1063. //
  1064. // Check the database of running services
  1065. //
  1066. FOR_SERVICES_THAT(serviceRecord,
  1067. _wcsicmp(serviceRecord->ServiceName, ServiceName)== 0)
  1068. {
  1069. *ServiceRecordPtr = serviceRecord;
  1070. return NO_ERROR;
  1071. }
  1072. return ERROR_SERVICE_DOES_NOT_EXIST;
  1073. }
  1074. /****************************************************************************/
  1075. DWORD
  1076. ScGetDisplayNamedServiceRecord (
  1077. IN LPWSTR ServiceDisplayName,
  1078. OUT LPSERVICE_RECORD *ServiceRecordPtr
  1079. )
  1080. /*++
  1081. Routine Description:
  1082. Uses the service display name to look through the service and device
  1083. linked lists until it finds a match.
  1084. Arguments:
  1085. ServiceDisplayName - This is a pointer to a NUL terminated service
  1086. display name string.
  1087. ServiceRecordPtr - This is a pointer to a location where the pointer to
  1088. the Service Record is to be placed.
  1089. Return Value:
  1090. NO_ERROR - if the record was found.
  1091. ERROR_SERVICE_DOES_NOT_EXIST - if the service record was not found in
  1092. the linked list.
  1093. ERROR_INVALID_NAME - if the service display name was NULL.
  1094. Note:
  1095. The caller is expected to grab the lock before calling this routine.
  1096. --*/
  1097. {
  1098. if (ServiceDisplayName == NULL)
  1099. {
  1100. SC_LOG0(TRACE,"GetDisplayNamedServiceRecord: Name was NULL\n");
  1101. return ERROR_INVALID_NAME;
  1102. }
  1103. //
  1104. // Check the database of running services
  1105. //
  1106. SC_ASSERT(ScServiceRecordLock.Have());
  1107. FOR_SERVICES_THAT(serviceRecord,
  1108. _wcsicmp(serviceRecord->DisplayName, ServiceDisplayName)== 0)
  1109. {
  1110. *ServiceRecordPtr = serviceRecord;
  1111. return NO_ERROR;
  1112. }
  1113. return ERROR_SERVICE_DOES_NOT_EXIST;
  1114. }
  1115. /****************************************************************************/
  1116. DWORD
  1117. ScGetTotalNumberOfRecords (VOID)
  1118. /*++
  1119. Routine Description:
  1120. Finds the total number of installed Service Records in the database.
  1121. This is used in the Enum case where only the installed services are
  1122. enumerated.
  1123. Arguments:
  1124. none
  1125. Return Value:
  1126. TotalNumberOfRecords
  1127. --*/
  1128. {
  1129. return(ScTotalNumServiceRecs);
  1130. }
  1131. /****************************************************************************/
  1132. BOOL
  1133. ScInitDatabase (VOID)
  1134. /*++
  1135. Routine Description:
  1136. This function initializes the Service Controllers database.
  1137. Arguments:
  1138. none
  1139. Return Value:
  1140. TRUE - Initialization was successful
  1141. FALSE - Initialization failed
  1142. --*/
  1143. {
  1144. ScTotalNumServiceRecs = 0;
  1145. ImageDatabase.Next = NULL;
  1146. ImageDatabase.Prev = NULL;
  1147. ServiceDatabase.Next = NULL;
  1148. ServiceDatabase.Prev = NULL;
  1149. ScInitGroupDatabase();
  1150. ResumeNumber = 1;
  1151. //
  1152. // Create the database lock.
  1153. // NOTE: This is never deleted. It is assumed it will be deleted
  1154. // when the process goes away.
  1155. //
  1156. ScServiceRecordLock.Initialize(" R", "ServiceRecord");
  1157. ScServiceListLock.Initialize(" L ", "ServiceList");
  1158. //
  1159. // Initialize the group list lock used for protecting the
  1160. // OrderGroupList and StandaloneGroupList
  1161. //
  1162. ScGroupListLock.Initialize("G ", "GroupList");
  1163. //
  1164. // This routine does the following:
  1165. // - Read the load order group information from the registry.
  1166. // - Generate the database of service records from the information
  1167. // stored in the registry.
  1168. //
  1169. if (!ScGenerateServiceDB())
  1170. {
  1171. return(FALSE);
  1172. }
  1173. return(TRUE);
  1174. }
  1175. /****************************************************************************/
  1176. VOID
  1177. ScProcessCleanup(
  1178. HANDLE ProcessHandle
  1179. )
  1180. /*++
  1181. Routine Description:
  1182. This function is called when a process has died, and the service
  1183. record in the database needs cleaning up. This function will
  1184. use the ProcessHandle as a key when scanning the ServiceRecord
  1185. database. All of the service records referencing that handle
  1186. are cleaned up, and then the image record that they reference
  1187. is deleted.
  1188. In cleaning up a service record, CurrentState is set to
  1189. SERVICE_STOPPED, and the ExitCode is set to a unique value that
  1190. indicates that the service died unexpectedly and without warning.
  1191. Arguments:
  1192. ProcessHandle - This is the handle of the process that died
  1193. unexpectedly.
  1194. Return Value:
  1195. none.
  1196. --*/
  1197. {
  1198. PIMAGE_RECORD imageRecord;
  1199. {
  1200. //
  1201. // Get exclusive use of database so that it can be modified.
  1202. //
  1203. // If the service record's update flag is set, we may have to
  1204. // modify the group list (within ScDeactivateServiceRecord),
  1205. // so lock the group list too.
  1206. //
  1207. CGroupListExclusiveLock GLock;
  1208. CServiceListSharedLock LLock;
  1209. CServiceRecordExclusiveLock RLock;
  1210. //
  1211. // Find the image record that has this ProcessHandle.
  1212. //
  1213. for (imageRecord = ImageDatabase.Next;
  1214. imageRecord != NULL;
  1215. imageRecord = imageRecord->Next)
  1216. {
  1217. if (ProcessHandle == imageRecord->ProcessHandle)
  1218. {
  1219. break;
  1220. }
  1221. }
  1222. if (imageRecord == NULL)
  1223. {
  1224. SC_LOG(ERROR, "ScProcessCleanup: No image record has handle %#lx!\n",
  1225. ProcessHandle);
  1226. return;
  1227. }
  1228. SC_LOG2(ERROR, "Service process %ld (%ws) died\n", imageRecord->Pid,
  1229. imageRecord->ImageName);
  1230. //
  1231. // Deregister the wait. Note that this must be done
  1232. // even if the WT_EXECUTEONLYONCE flag was specified)
  1233. //
  1234. if (imageRecord->ObjectWaitHandle != NULL)
  1235. {
  1236. NTSTATUS ntStatus = RtlDeregisterWait(imageRecord->ObjectWaitHandle);
  1237. if (!NT_SUCCESS(ntStatus))
  1238. {
  1239. SC_LOG1(ERROR,
  1240. "ScProcessCleanup: RtlDeregisterWait FAILED %#x\n",
  1241. ntStatus);
  1242. }
  1243. }
  1244. DWORD serviceCount = imageRecord->ServiceCount;
  1245. //
  1246. // The image record's service count must include at least this service
  1247. //
  1248. if (serviceCount == 0)
  1249. {
  1250. SC_ASSERT(0);
  1251. // Do something sensible if this ever does happen
  1252. serviceCount = imageRecord->ServiceCount = 1;
  1253. }
  1254. //
  1255. // The Image may have several services running in it.
  1256. // Find the service records for all running services in this
  1257. // image.
  1258. //
  1259. // NOTE: If the service is typed as a SERVICE_WIN32_OWN_PROCESS, this
  1260. // means that only one service can exist in the process that
  1261. // went down. However, the serviceCount should correctly
  1262. // indicate as such in that case.
  1263. //
  1264. FOR_SERVICES_THAT(serviceRecord,
  1265. (serviceRecord->ImageRecord == imageRecord)
  1266. &&
  1267. (serviceRecord->ServiceStatus.dwCurrentState != SERVICE_STOPPED))
  1268. {
  1269. SC_LOG2(ERROR, "Dead process contained %ws service in state %#lx\n",
  1270. serviceRecord->ServiceName,
  1271. serviceRecord->ServiceStatus.dwCurrentState);
  1272. //
  1273. // Don't bother notifying PnP if the system is shutting down. This
  1274. // prevents a deadlock where we can get stuck calling PnP, which is
  1275. // stuck calling into the Eventlog, which is stuck calling into us.
  1276. //
  1277. if (!ScShutdownInProgress)
  1278. {
  1279. if (serviceRecord->ServiceStatus.dwControlsAccepted
  1280. &
  1281. (SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_HARDWAREPROFILECHANGE))
  1282. {
  1283. //
  1284. // Tell PnP not to send controls to this service any more
  1285. //
  1286. RegisterServiceNotification((SERVICE_STATUS_HANDLE)serviceRecord,
  1287. serviceRecord->ServiceName,
  1288. 0,
  1289. TRUE);
  1290. }
  1291. //
  1292. // Increment the service's crash count and perform the configured
  1293. // recovery action. Don't bother if the system is shutting down.
  1294. //
  1295. ScQueueRecoveryAction(serviceRecord);
  1296. }
  1297. serviceRecord->StartError = ERROR_PROCESS_ABORTED;
  1298. serviceRecord->StartState = SC_START_FAIL;
  1299. serviceRecord->ServiceStatus.dwWin32ExitCode = ERROR_PROCESS_ABORTED;
  1300. //
  1301. // Clear the server announcement bits in the global location
  1302. // for this service.
  1303. //
  1304. ScRemoveServiceBits(serviceRecord);
  1305. serviceCount = ScDeactivateServiceRecord(serviceRecord);
  1306. if (serviceCount == 0)
  1307. {
  1308. // No need to continue
  1309. break;
  1310. }
  1311. }
  1312. // (If we hit this assert it means that the service database was corrupt:
  1313. // the number of service records pointing to this image record was less
  1314. // than the service count in the image record. Not much we can do now.)
  1315. SC_ASSERT(serviceCount == 0);
  1316. //
  1317. // Remove the ImageRecord from the list and delete it
  1318. //
  1319. REMOVE_FROM_LIST(imageRecord);
  1320. }
  1321. ScDeleteImageRecord(imageRecord);
  1322. return;
  1323. }
  1324. VOID
  1325. ScDeleteMarkedServices(
  1326. VOID
  1327. )
  1328. /*++
  1329. Routine Description:
  1330. This function looks through the service record database for any entries
  1331. marked for deletion. If one is found, it is removed from the registry
  1332. and its entry is deleted from the service record database.
  1333. WARNING:
  1334. This function is to be called during initialization only. It
  1335. is assumed that no services are running when this function is called.
  1336. Therefore, no locks are held during this operation.
  1337. Arguments:
  1338. none
  1339. Return Value:
  1340. none
  1341. --*/
  1342. {
  1343. HKEY ServiceNameKey;
  1344. LPWSTR AccountName;
  1345. FOR_SERVICES_THAT(serviceRecord, DELETE_FLAG_IS_SET(serviceRecord))
  1346. {
  1347. SC_LOG(TRACE,"ScDeleteMarkedServices: %ws is being deleted\n",
  1348. serviceRecord->ServiceName);
  1349. //
  1350. // Open the service name key.
  1351. //
  1352. if (ScOpenServiceConfigKey(
  1353. serviceRecord->ServiceName,
  1354. KEY_READ,
  1355. FALSE, // Create if missing
  1356. &ServiceNameKey) == NO_ERROR)
  1357. {
  1358. //
  1359. // Read the account name from the registry.
  1360. // If this fails, we still want to delete the registry entry.
  1361. //
  1362. if (ScReadStartName(ServiceNameKey, &AccountName) == NO_ERROR
  1363. &&
  1364. AccountName != NULL)
  1365. {
  1366. if (_wcsicmp(AccountName, SC_LOCAL_SYSTEM_USER_NAME) != 0)
  1367. {
  1368. ScRemoveAccount(serviceRecord->ServiceName);
  1369. }
  1370. LocalFree(AccountName);
  1371. } // Got the StartName
  1372. ScRegCloseKey(ServiceNameKey);
  1373. //
  1374. // Delete the entry from the registry
  1375. //
  1376. ScDeleteRegServiceEntry(serviceRecord->ServiceName);
  1377. //
  1378. // Free memory for the DisplayName.
  1379. //
  1380. if (serviceRecord->DisplayName != serviceRecord->ServiceName)
  1381. {
  1382. LocalFree(serviceRecord->DisplayName);
  1383. }
  1384. //
  1385. // Remove the service record from the database
  1386. //
  1387. LPSERVICE_RECORD saveRecord = serviceRecord->Prev;
  1388. REMOVE_FROM_LIST(serviceRecord);
  1389. ScFreeServiceRecord(serviceRecord);
  1390. serviceRecord = saveRecord;
  1391. }
  1392. }
  1393. }
  1394. /****************************************************************************/
  1395. DWORD
  1396. ScRemoveService (
  1397. IN LPSERVICE_RECORD ServiceRecord
  1398. )
  1399. /*++
  1400. Routine Description:
  1401. This should be used to deactivate a service record and shut down
  1402. the process only if it is the last service in the process. It
  1403. will be used for polite shut-down when a service terminates as
  1404. normal. It will always be called by the status routine. If the
  1405. service controller believes that no other services are running in
  1406. the process, it can force termination of the process if it does
  1407. not respond to the process shutdown request.
  1408. This function deactivates the service record (ScDeactivateServiceRecord)
  1409. and checks to see if the ServiceCount in the image record has gone to
  1410. zero. If it has, then it terminates the service process. When that
  1411. is complete, it calls ScDeleteImageRecord to remove the remaining
  1412. evidence.
  1413. Even if an error occurs, and we are unable to terminate the process,
  1414. we delete the image record any - just as we would in the case
  1415. where it goes away.
  1416. Arguments:
  1417. ServiceRecord - This is a pointer to the service record that is to
  1418. be removed.
  1419. Return Value:
  1420. NO_ERROR - The operation was successful.
  1421. NERR_ServiceKillProc - The service process had to be killed because
  1422. it wouldn't terminate when requested. If the process did not
  1423. go away - even after being killed (TerminateProcess), this error
  1424. message is still returned.
  1425. Note:
  1426. Uses Exclusive Locks.
  1427. --*/
  1428. {
  1429. DWORD serviceCount = 0;
  1430. LPIMAGE_RECORD ImageRecord;
  1431. {
  1432. //
  1433. // Get exclusive use of database so that it can be modified.
  1434. // If the service record's update flag is set, we may have to
  1435. // modify the group list, so lock the group list too.
  1436. //
  1437. CGroupListExclusiveLock GLock;
  1438. CServiceListSharedLock LLock; // (needed if update flag set and service has dependencies)
  1439. CServiceRecordExclusiveLock RLock;
  1440. ImageRecord = ServiceRecord->ImageRecord;
  1441. //
  1442. // ImageRecord may be NULL if it had been cleaned up earlier
  1443. //
  1444. if (ImageRecord != NULL)
  1445. {
  1446. //
  1447. // Deactivate the service record.
  1448. //
  1449. serviceCount = ScDeactivateServiceRecord(ServiceRecord);
  1450. //
  1451. // Do as little as possible while holding the locks.
  1452. // Otherwise, we can cause a deadlock or a bottleneck
  1453. // on system shutdown due to contention for the
  1454. // exclusive locks
  1455. //
  1456. if (serviceCount == 0)
  1457. {
  1458. //
  1459. // Remove the Image record from linked list.
  1460. //
  1461. REMOVE_FROM_LIST(ImageRecord);
  1462. }
  1463. }
  1464. }
  1465. //
  1466. // Done with modifications - now allow other threads database access.
  1467. //
  1468. if (ImageRecord != NULL && serviceCount == 0)
  1469. {
  1470. //
  1471. // Now we must terminate the Service Process. The return status
  1472. // from this call is not very interesting. The calling application
  1473. // probably doesn't care how the process died. (whether it died
  1474. // cleanly, or had to be killed).
  1475. //
  1476. ScTerminateServiceProcess(ImageRecord);
  1477. ScDeleteImageRecord (ImageRecord);
  1478. }
  1479. return(NO_ERROR);
  1480. }
  1481. /****************************************************************************/
  1482. VOID
  1483. ScDeleteImageRecord (
  1484. IN LPIMAGE_RECORD ImageRecord
  1485. )
  1486. /*++
  1487. Routine Description:
  1488. This function deletes an ImageRecord from the database by removing it
  1489. from the linked list, and freeing its associated memory. Prior to
  1490. doing this however, it closes the PipeHandle and the ProcessHandle
  1491. in the record.
  1492. Arguments:
  1493. ImageRecord - This is a pointer to the ImageRecord that is being deleted.
  1494. Return Value:
  1495. nothing
  1496. Notes:
  1497. This routine assumes that the image record has already been removed
  1498. from the list before it is called via the REMOVE_FROM_LIST macro. This
  1499. is to allow us to call ScDeleteImageRecord without holding any exclusive
  1500. locks
  1501. --*/
  1502. {
  1503. HANDLE status; // return status from LocalFree
  1504. SC_ASSERT( ImageRecord != NULL );
  1505. //
  1506. // What else can we do except note the errors in debug mode?
  1507. //
  1508. if (CloseHandle(ImageRecord->PipeHandle) == FALSE)
  1509. {
  1510. SC_LOG(TRACE,"DeleteImageRecord: ClosePipeHandle Failed %lu\n",
  1511. GetLastError());
  1512. }
  1513. if (CloseHandle(ImageRecord->ProcessHandle) == FALSE)
  1514. {
  1515. SC_LOG(TRACE,"DeleteImageRecord: CloseProcessHandle Failed %lu\n",
  1516. GetLastError());
  1517. }
  1518. if (ImageRecord->ProfileHandle != (HANDLE) NULL)
  1519. {
  1520. if (UnloadUserProfile(ImageRecord->TokenHandle,
  1521. ImageRecord->ProfileHandle) == FALSE)
  1522. {
  1523. SC_LOG1(ERROR,"DeleteImageRecord: UnloadUserProfile Failed %lu\n",
  1524. GetLastError());
  1525. }
  1526. }
  1527. if (ImageRecord->TokenHandle != (HANDLE) NULL)
  1528. {
  1529. if (CloseHandle(ImageRecord->TokenHandle) == FALSE)
  1530. {
  1531. SC_LOG1(TRACE,"DeleteImageRecord: CloseTokenHandle Failed %lu\n",
  1532. GetLastError());
  1533. }
  1534. }
  1535. status = LocalFree(ImageRecord);
  1536. if (status != NULL)
  1537. {
  1538. SC_LOG(TRACE,"DeleteImageRecord: LocalFree Failed, rc = %d\n",
  1539. GetLastError());
  1540. }
  1541. return;
  1542. }
  1543. /****************************************************************************/
  1544. DWORD
  1545. ScDeactivateServiceRecord (
  1546. IN LPSERVICE_RECORD ServiceRecord
  1547. )
  1548. /*++
  1549. Routine Description:
  1550. This function deactivates a service record by updating the proper
  1551. GlobalCount data structure.
  1552. NOTE: Although the ServiceRecord does not go away, the pointer to
  1553. the ImageRecord is destroyed.
  1554. Arguments:
  1555. ServiceRecord - This is a pointer to the ServiceRecord that is to be
  1556. deleted (moved to uninstalled database).
  1557. Notes:
  1558. This routine assumes that the Exclusive database lock has already
  1559. been obtained. (ScRemoveService & ScProcessCleanup call this function).
  1560. If the service's update flag is set (its configuration was changed
  1561. while it was running), the exclusive group list lock must also have
  1562. been obtained.
  1563. Return Value:
  1564. ServiceCount - This indicates how many services in this service process
  1565. are actually installed.
  1566. --*/
  1567. {
  1568. DWORD serviceCount = 0;
  1569. DWORD status;
  1570. DWORD dwServiceType;
  1571. DWORD dwStartType;
  1572. DWORD dwErrorControl;
  1573. DWORD dwTagId;
  1574. LPWSTR lpDependencies = NULL;
  1575. LPWSTR lpLoadOrderGroup = NULL;
  1576. LPWSTR lpDisplayName = NULL;
  1577. SC_LOG(TRACE,"In DeactivateServiceRecord\n",0);
  1578. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  1579. //
  1580. // Decrement the service count in the image record.
  1581. //
  1582. if (ServiceRecord->ImageRecord != NULL)
  1583. {
  1584. serviceCount = --(ServiceRecord->ImageRecord->ServiceCount);
  1585. }
  1586. ServiceRecord->ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  1587. ServiceRecord->ServiceStatus.dwControlsAccepted = 0;
  1588. ServiceRecord->ServiceStatus.dwCheckPoint = 0;
  1589. ServiceRecord->ServiceStatus.dwWaitHint = 0;
  1590. ServiceRecord->ImageRecord = NULL;
  1591. //
  1592. // If the Update bit is set in the services status flag, we need
  1593. // to read the latest registry configuration information into the
  1594. // service record. If this fails, all we can do is log the error
  1595. // and press on with the existing data in the service record.
  1596. //
  1597. if (UPDATE_FLAG_IS_SET(ServiceRecord))
  1598. {
  1599. SC_ASSERT(ScGroupListLock.HaveExclusive());
  1600. status = ScReadConfigFromReg(
  1601. ServiceRecord,
  1602. &dwServiceType,
  1603. &dwStartType,
  1604. &dwErrorControl,
  1605. &dwTagId,
  1606. NULL, // Don't need dependencies -- they're updated dynamically
  1607. &lpLoadOrderGroup,
  1608. NULL); // Don't need display name -- it's updated dynamically
  1609. if (status == NO_ERROR)
  1610. {
  1611. //
  1612. // Dependencies are NULL since they're updated dynamically
  1613. //
  1614. status = ScUpdateServiceRecordConfig(
  1615. ServiceRecord,
  1616. dwServiceType,
  1617. dwStartType,
  1618. dwErrorControl,
  1619. lpLoadOrderGroup,
  1620. NULL);
  1621. }
  1622. if (status != NO_ERROR)
  1623. {
  1624. SC_LOG1(ERROR,"ScDeactivateServiceRecord:Attempt to update "
  1625. "configuration for stopped service failed\n",status);
  1626. //
  1627. // ERROR_LOG ErrorLog
  1628. //
  1629. }
  1630. LocalFree(lpLoadOrderGroup);
  1631. LocalFree(lpDependencies);
  1632. LocalFree(lpDisplayName);
  1633. CLEAR_UPDATE_FLAG(ServiceRecord);
  1634. }
  1635. //
  1636. // Since the service is no longer running, and no longer has a handle
  1637. // to the service, we need to decrement the use count. If the
  1638. // count is decremented to zero, and the service is marked for
  1639. // deletion, it will get deleted.
  1640. //
  1641. ScDecrementUseCountAndDelete(ServiceRecord);
  1642. return(serviceCount);
  1643. }
  1644. /****************************************************************************/
  1645. DWORD
  1646. ScTerminateServiceProcess (
  1647. IN PIMAGE_RECORD ImageRecord
  1648. )
  1649. /*++
  1650. Routine Description:
  1651. This function sends an SERVICE_STOP control message to the target
  1652. ControlDispatcher. Then it uses the process handle to wait for the
  1653. service process to terminate.
  1654. If the service process fails to terminate with the polite request, it
  1655. will be abruptly killed. After killing the process, this routine will
  1656. wait on the process handle to make sure it enters the signaled state.
  1657. If it doesn't, and the wait times out, we return anyway having given
  1658. it our best shot.
  1659. Arguments:
  1660. ImageRecord - This is a pointer to the Image Record that stores
  1661. information about the service that is to be terminated.
  1662. Return Value:
  1663. NO_ERROR - The operation was successful.
  1664. NERR_ServiceKillProc - The service process had to be killed because
  1665. it wouldn't terminate when requested. If the process did not
  1666. go away - even after being killed (TerminateProcess), this error
  1667. message is still returned.
  1668. Note:
  1669. LOCKS:
  1670. This function always operates within an exclusive database lock.
  1671. It DOES NOT give up this lock when sending the control to the service
  1672. process. We would like all these operations to be atomic.
  1673. It must give this up temporarily when it does the pipe transact.
  1674. --*/
  1675. {
  1676. DWORD returnStatus;
  1677. DWORD status;
  1678. DWORD waitStatus;
  1679. returnStatus = NO_ERROR;
  1680. //
  1681. // Check vs. NULL in case the register failed or the work item
  1682. // was already deregistered in RSetServiceStatus
  1683. //
  1684. if (ImageRecord->ObjectWaitHandle != NULL) {
  1685. status = RtlDeregisterWait(ImageRecord->ObjectWaitHandle);
  1686. if (NT_SUCCESS(status)) {
  1687. ImageRecord->ObjectWaitHandle = NULL;
  1688. }
  1689. else {
  1690. SC_LOG1(ERROR,
  1691. "ScTerminateServiceProcess: RtlDeregisterWait failed 0x%x\n",
  1692. status);
  1693. }
  1694. }
  1695. //
  1696. // Send Uninstall message to the Service Process
  1697. // Note that the ServiceName is NULL when addressing
  1698. // the Service Process.
  1699. //
  1700. SC_LOG(TRACE,"TerminateServiceProcess, sending Control...\n",0);
  1701. //
  1702. // Stop the service's control dispatcher
  1703. //
  1704. status = ScSendControl(
  1705. L"", // no service name.
  1706. L"", // no display name.
  1707. ImageRecord->PipeHandle, // PipeHandle
  1708. SERVICE_STOP, // Opcode
  1709. NULL, // CmdArgs (pointer to vectors).
  1710. 0L, // NumArgs
  1711. NULL); // Ignore handler return value
  1712. if (status == NO_ERROR)
  1713. {
  1714. //
  1715. // Control Dispatcher accepted the request - now
  1716. // wait for it to shut down.
  1717. //
  1718. SC_LOG(TRACE,
  1719. "TerminateServiceProcess, waiting for process to terminate...\n",0);
  1720. waitStatus = WaitForSingleObject (
  1721. ImageRecord->ProcessHandle,
  1722. TERMINATE_TIMEOUT);
  1723. if (waitStatus == WAIT_TIMEOUT)
  1724. {
  1725. SC_LOG3(ERROR,"TerminateServiceProcess: Process %#lx (%ws) did not exit because of timeout: %#ld\n",
  1726. ImageRecord->Pid, ImageRecord->ImageName, WAIT_TIMEOUT);
  1727. //
  1728. // Process didn't terminate. So Now I have to kill it.
  1729. //
  1730. TerminateProcess(ImageRecord->ProcessHandle, 0);
  1731. waitStatus = WaitForSingleObject (
  1732. ImageRecord->ProcessHandle,
  1733. TERMINATE_TIMEOUT);
  1734. if (waitStatus == WAIT_TIMEOUT)
  1735. {
  1736. SC_LOG2(ERROR,"TerminateServiceProcess: Couldn't kill process %#lx because of timeout: %#ld\n",
  1737. ImageRecord->Pid, WAIT_TIMEOUT);
  1738. }
  1739. returnStatus = NO_ERROR;
  1740. }
  1741. }
  1742. else
  1743. {
  1744. //
  1745. // ScSendControl failed -- this can occur if the service calls ExitProcess
  1746. // while handling SERVICE_CONTROL_STOP or SERVICE_CONTROL_SHUTDOWN since
  1747. // the pipe for the image record is now broken (ERROR_BROKEN_PIPE).
  1748. //
  1749. SC_LOG3(ERROR,
  1750. "TerminateServiceProcess:SendControl to stop process %#lx (%ws) failed, %ld\n",
  1751. ImageRecord->Pid, ImageRecord->ImageName, status);
  1752. TerminateProcess(ImageRecord->ProcessHandle, 0);
  1753. waitStatus = WaitForSingleObject (
  1754. ImageRecord->ProcessHandle,
  1755. TERMINATE_TIMEOUT);
  1756. if (waitStatus == WAIT_TIMEOUT)
  1757. {
  1758. SC_LOG2(ERROR,"TerminateServiceProcess: Couldn't kill process because of timeout: %ld\n",
  1759. 0, WAIT_TIMEOUT);
  1760. }
  1761. returnStatus = NO_ERROR;
  1762. }
  1763. SC_LOG(TRACE,"TerminateServiceProcess, Done terminating Process!\n",0);
  1764. return(returnStatus);
  1765. }
  1766. VOID
  1767. ScDeferredListWorkItem(
  1768. IN PVOID pContext
  1769. )
  1770. /*++
  1771. Routine Description:
  1772. This function acquires all the database locks, and allows
  1773. the group list lock routine to process the deferred list.
  1774. --*/
  1775. {
  1776. ScDeferredList.Process();
  1777. }
  1778. DWORD
  1779. ScUpdateServiceRecordConfig(
  1780. IN LPSERVICE_RECORD ServiceRecord,
  1781. IN DWORD dwServiceType,
  1782. IN DWORD dwStartType,
  1783. IN DWORD dwErrorControl,
  1784. IN LPWSTR lpLoadOrderGroup,
  1785. IN LPBYTE lpDependencies
  1786. )
  1787. /*++
  1788. Routine Description:
  1789. This function updates the service record with the latest config
  1790. information (passed in).
  1791. It assumed that exclusive locks are held before calling this function.
  1792. Arguments:
  1793. Return Value:
  1794. Note:
  1795. --*/
  1796. #define SERVICE_TYPE_CHANGED 0x00000001
  1797. #define START_TYPE_CHANGED 0x00000002
  1798. #define ERROR_CONTROL_CHANGED 0x00000004
  1799. #define BINARY_PATH_CHANGED 0x00000008
  1800. #define LOAD_ORDER_CHANGED 0x00000010
  1801. #define TAG_ID_CHANGED 0x00000020
  1802. #define DEPENDENCIES_CHANGED 0x00000040
  1803. #define START_NAME_CHANGED 0x00000080
  1804. {
  1805. DWORD status;
  1806. DWORD backoutStatus;
  1807. LPWSTR OldLoadOrderGroup = NULL;
  1808. LPWSTR OldDependencies = NULL;
  1809. DWORD OldServiceType;
  1810. DWORD OldStartType;
  1811. DWORD OldErrorControl;
  1812. DWORD Progress = 0;
  1813. DWORD bufSize;
  1814. DWORD MaxDependSize = 0;
  1815. SC_ASSERT(ScGroupListLock.HaveExclusive());
  1816. SC_ASSERT(ScServiceRecordLock.HaveExclusive());
  1817. OldServiceType = ServiceRecord->ServiceStatus.dwServiceType;
  1818. OldStartType = ServiceRecord->StartType;
  1819. OldErrorControl= ServiceRecord->ErrorControl;
  1820. //==============================
  1821. // UPDATE DWORDs
  1822. //==============================
  1823. if (dwServiceType != SERVICE_NO_CHANGE)
  1824. {
  1825. ServiceRecord->ServiceStatus.dwServiceType = dwServiceType;
  1826. }
  1827. if (dwStartType != SERVICE_NO_CHANGE)
  1828. {
  1829. ServiceRecord->StartType = dwStartType;
  1830. }
  1831. if (dwErrorControl != SERVICE_NO_CHANGE)
  1832. {
  1833. ServiceRecord->ErrorControl = dwErrorControl;
  1834. }
  1835. Progress |= (SERVICE_TYPE_CHANGED |
  1836. START_TYPE_CHANGED |
  1837. ERROR_CONTROL_CHANGED );
  1838. //==============================
  1839. // UPDATE Dependencies
  1840. //==============================
  1841. if (lpDependencies != NULL)
  1842. {
  1843. //
  1844. // Generate the current (old) list of dependency strings.
  1845. //
  1846. ScGetDependencySize(ServiceRecord,&bufSize, &MaxDependSize);
  1847. if (bufSize > 0)
  1848. {
  1849. OldDependencies = (LPWSTR)LocalAlloc(LMEM_FIXED, bufSize);
  1850. if (OldDependencies == NULL)
  1851. {
  1852. status = GetLastError();
  1853. goto Cleanup;
  1854. }
  1855. status = ScGetDependencyString(
  1856. ServiceRecord,
  1857. MaxDependSize,
  1858. bufSize,
  1859. OldDependencies);
  1860. if (status != NO_ERROR)
  1861. {
  1862. goto Cleanup;
  1863. }
  1864. }
  1865. ScDeleteStartDependencies(ServiceRecord);
  1866. status = ScCreateDependencies(ServiceRecord, (LPWSTR) lpDependencies);
  1867. if (status != NO_ERROR)
  1868. {
  1869. goto Cleanup;
  1870. }
  1871. Progress |= DEPENDENCIES_CHANGED;
  1872. }
  1873. //==============================
  1874. // UPDATE LoadOrderGroup
  1875. //==============================
  1876. if (lpLoadOrderGroup != NULL)
  1877. {
  1878. if (*lpLoadOrderGroup != 0)
  1879. {
  1880. //
  1881. // The string in lpLoadOrderGroup should match that in
  1882. // the RegistryGroup in the service record.
  1883. //
  1884. if (_wcsicmp(lpLoadOrderGroup, ServiceRecord->RegistryGroup->GroupName) != 0)
  1885. {
  1886. SC_LOG2(ERROR,"ScUpdateServiceRecordConfig: New Group [%ws] Doesn't "
  1887. "match that stored in the service database [%ws]\n",
  1888. lpLoadOrderGroup,
  1889. ServiceRecord->RegistryGroup->GroupName);
  1890. status = ERROR_GEN_FAILURE;
  1891. goto Cleanup;
  1892. }
  1893. }
  1894. //
  1895. // Save Old MemberOfGroup name for error recovery
  1896. //
  1897. if (ServiceRecord->MemberOfGroup != NULL)
  1898. {
  1899. OldLoadOrderGroup = (LPWSTR)LocalAlloc(
  1900. LMEM_FIXED,
  1901. WCSSIZE(ServiceRecord->MemberOfGroup->GroupName));
  1902. //
  1903. // If this allocation fails, just pretend that it doesn't exist.
  1904. //
  1905. if (OldLoadOrderGroup != NULL)
  1906. {
  1907. wcscpy(OldLoadOrderGroup, ServiceRecord->MemberOfGroup->GroupName);
  1908. }
  1909. }
  1910. //
  1911. // Delete MemberOfGroup & Add RegistryGroup to MemberOfGroup so that
  1912. // they are the same.
  1913. // REMEMBER that RegistryGroup and lpLoadOrderGroup are the same!
  1914. //
  1915. ScDeleteGroupMembership(ServiceRecord);
  1916. status = ScCreateGroupMembership(ServiceRecord, lpLoadOrderGroup);
  1917. if (status != NO_ERROR)
  1918. {
  1919. ScDeleteGroupMembership(ServiceRecord);
  1920. if ((OldLoadOrderGroup != NULL) && (*OldLoadOrderGroup))
  1921. {
  1922. backoutStatus = ScCreateGroupMembership(
  1923. ServiceRecord,
  1924. OldLoadOrderGroup);
  1925. if (backoutStatus != NO_ERROR)
  1926. {
  1927. // Do what? - we may want to write to ERROR LOG?
  1928. }
  1929. }
  1930. goto Cleanup;
  1931. }
  1932. }
  1933. status = NO_ERROR;
  1934. Cleanup:
  1935. if (status != NO_ERROR)
  1936. {
  1937. ServiceRecord->ServiceStatus.dwServiceType = OldServiceType;
  1938. ServiceRecord->StartType = OldStartType;
  1939. ServiceRecord->ErrorControl = OldErrorControl;
  1940. if (Progress & DEPENDENCIES_CHANGED)
  1941. {
  1942. ScDeleteStartDependencies(ServiceRecord);
  1943. if ((OldDependencies != NULL) && (*OldDependencies != 0))
  1944. {
  1945. backoutStatus = ScCreateDependencies(
  1946. ServiceRecord,
  1947. OldDependencies);
  1948. if (backoutStatus != NO_ERROR)
  1949. {
  1950. // Do what? - we may want to write to ERROR LOG?
  1951. }
  1952. }
  1953. }
  1954. }
  1955. LocalFree(OldDependencies);
  1956. LocalFree(OldLoadOrderGroup);
  1957. return(status);
  1958. }
  1959. BOOL
  1960. ScAllocateSRHeap(
  1961. DWORD HeapSize
  1962. )
  1963. /*++
  1964. Routine Description:
  1965. Arguments:
  1966. Return Value:
  1967. --*/
  1968. {
  1969. ServiceRecordHeap = HeapCreate(0,HeapSize,0);
  1970. if (ServiceRecordHeap == NULL)
  1971. {
  1972. SC_LOG0(ERROR,"Could not allocate Heap for Service Database\n");
  1973. return(FALSE);
  1974. }
  1975. return(TRUE);
  1976. }