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.

1177 lines
29 KiB

  1. /*++
  2. Copyright (c) 1991 Microsoft Corporation
  3. Module Name:
  4. bowutils.c
  5. Abstract:
  6. This module implements various useful routines for the NT datagram
  7. receiver (bowser).
  8. Author:
  9. Larry Osterman (larryo) 6-May-1991
  10. Revision History:
  11. 24-Sep-1991 larryo
  12. Created
  13. --*/
  14. #include "precomp.h"
  15. #pragma hdrstop
  16. #ifdef ALLOC_PRAGMA
  17. #pragma alloc_text(PAGE, BowserMapUsersBuffer)
  18. #pragma alloc_text(PAGE, BowserLockUsersBuffer)
  19. #pragma alloc_text(PAGE, BowserConvertType3IoControlToType2IoControl)
  20. #pragma alloc_text(PAGE, BowserPackNtString)
  21. #pragma alloc_text(PAGE, BowserPackUnicodeString)
  22. #pragma alloc_text(PAGE, BowserRandom)
  23. #pragma alloc_text(PAGE, BowserTimeUp)
  24. #pragma alloc_text(PAGE, BowserReferenceDiscardableCode)
  25. #pragma alloc_text(PAGE, BowserDereferenceDiscardableCode)
  26. #pragma alloc_text(PAGE, BowserUninitializeDiscardableCode)
  27. #pragma alloc_text(INIT, BowserInitializeDiscardableCode)
  28. #if DBG
  29. #ifndef PRODUCT1
  30. #pragma alloc_text(PAGE, BowserTrace)
  31. #endif
  32. #pragma alloc_text(PAGE, BowserInitializeTraceLog)
  33. #pragma alloc_text(PAGE, BowserOpenTraceLogFile)
  34. #pragma alloc_text(PAGE, BowserUninitializeTraceLog)
  35. #pragma alloc_text(PAGE, BowserDebugCall)
  36. #endif
  37. #endif
  38. BOOLEAN
  39. BowserMapUsersBuffer (
  40. IN PIRP Irp,
  41. OUT PVOID *UserBuffer,
  42. IN ULONG Length
  43. )
  44. /*++
  45. Routine Description:
  46. This routine will probe and lock the buffer described by the
  47. provided Irp.
  48. Arguments:
  49. IN PIRP Irp - Supplies the IRP that is to be mapped.
  50. OUT PVOID *Buffer - Returns a buffer that maps the user's buffer in the IRP
  51. Return Value:
  52. TRUE - The buffer was mapped into the current address space.
  53. FALSE - The buffer was NOT mapped in, it was already mappable.
  54. --*/
  55. {
  56. PAGED_CODE();
  57. if (Irp->MdlAddress) {
  58. *UserBuffer = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, LowPagePriority);
  59. return FALSE;
  60. } else {
  61. if (Irp->AssociatedIrp.SystemBuffer != NULL) {
  62. *UserBuffer = Irp->AssociatedIrp.SystemBuffer;
  63. } else if (Irp->RequestorMode != KernelMode) {
  64. PIO_STACK_LOCATION IrpSp;
  65. IrpSp = IoGetCurrentIrpStackLocation( Irp );
  66. if ((Length != 0) && (Irp->UserBuffer != 0)) {
  67. if ((IrpSp->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) ||
  68. (IrpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL)) {
  69. ULONG ControlCode = IrpSp->Parameters.DeviceIoControl.IoControlCode;
  70. if ((ControlCode & 3) == METHOD_NEITHER) {
  71. ProbeForWrite( Irp->UserBuffer,
  72. Length,
  73. sizeof(UCHAR) );
  74. } else {
  75. ASSERT ((ControlCode & 3) != METHOD_BUFFERED);
  76. ASSERT ((ControlCode & 3) != METHOD_IN_DIRECT);
  77. ASSERT ((ControlCode & 3) != METHOD_OUT_DIRECT);
  78. }
  79. } else if ((IrpSp->MajorFunction == IRP_MJ_READ) ||
  80. (IrpSp->MajorFunction == IRP_MJ_QUERY_INFORMATION) ||
  81. (IrpSp->MajorFunction == IRP_MJ_QUERY_VOLUME_INFORMATION) ||
  82. (IrpSp->MajorFunction == IRP_MJ_QUERY_SECURITY) ||
  83. (IrpSp->MajorFunction == IRP_MJ_DIRECTORY_CONTROL)) {
  84. ProbeForWrite( Irp->UserBuffer,
  85. Length,
  86. sizeof(UCHAR) );
  87. } else {
  88. ProbeForRead( Irp->UserBuffer,
  89. Length,
  90. sizeof(UCHAR) );
  91. }
  92. }
  93. *UserBuffer = Irp->UserBuffer;
  94. }
  95. return FALSE;
  96. }
  97. }
  98. NTSTATUS
  99. BowserLockUsersBuffer (
  100. IN PIRP Irp,
  101. IN LOCK_OPERATION Operation,
  102. IN ULONG BufferLength
  103. )
  104. /*++
  105. Routine Description:
  106. This routine will probe and lock the buffer described by the
  107. provided Irp.
  108. Arguments:
  109. IN PIRP Irp - Supplies the IRP that is to be locked.
  110. IN LOCK_OPERATION Operation - Supplies the operation type to probe.
  111. Return Value:
  112. None.
  113. --*/
  114. {
  115. NTSTATUS Status = STATUS_SUCCESS;
  116. PAGED_CODE();
  117. if ((Irp->MdlAddress == NULL)) {
  118. try {
  119. Irp->MdlAddress = IoAllocateMdl(Irp->UserBuffer,
  120. BufferLength,
  121. FALSE,
  122. TRUE,
  123. NULL);
  124. if (Irp->MdlAddress == NULL) {
  125. return(STATUS_INSUFFICIENT_RESOURCES);
  126. }
  127. //
  128. // Now probe and lock down the user's data buffer.
  129. //
  130. MmProbeAndLockPages(Irp->MdlAddress,
  131. Irp->RequestorMode,
  132. Operation);
  133. } except (BR_EXCEPTION) {
  134. Status = GetExceptionCode();
  135. if (Irp->MdlAddress != NULL) {
  136. //
  137. // We blew up in the probe and lock, free up the MDL
  138. // and set the IRP to have a null MDL pointer - we are failing the
  139. // request
  140. //
  141. IoFreeMdl(Irp->MdlAddress);
  142. Irp->MdlAddress = NULL;
  143. }
  144. }
  145. }
  146. return Status;
  147. }
  148. NTSTATUS
  149. BowserConvertType3IoControlToType2IoControl (
  150. IN PIRP Irp,
  151. IN PIO_STACK_LOCATION IrpSp
  152. )
  153. /*++
  154. Routine Description:
  155. This routine does the work necessary to convert a type 3 IoCtl to a
  156. type 2 IoCtl. We do this when we have to pass a user IRP to the FSP.
  157. Arguments:
  158. IN PIRP Irp - Supplies an IRP to convert
  159. IN PIO_STACK_LOCATION IrpSp - Supplies an Irp Stack location for convenience
  160. Return Value:
  161. NTSTATUS - Status of operation
  162. Note: This must be called in the FSD.
  163. --*/
  164. {
  165. NTSTATUS Status;
  166. PAGED_CODE();
  167. if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength != 0) {
  168. Status = BowserLockUsersBuffer(Irp, IoWriteAccess, IrpSp->Parameters.DeviceIoControl.OutputBufferLength);
  169. //
  170. // If we were unable to lock the users output buffer, return now.
  171. //
  172. if (!NT_SUCCESS(Status)) {
  173. return Status;
  174. }
  175. }
  176. ASSERT (Irp->AssociatedIrp.SystemBuffer == NULL);
  177. try {
  178. if (IrpSp->Parameters.DeviceIoControl.InputBufferLength != 0) {
  179. PCHAR InputBuffer = IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;
  180. ULONG InputBufferLength = IrpSp->Parameters.DeviceIoControl.InputBufferLength;
  181. Irp->AssociatedIrp.SystemBuffer = ExAllocatePoolWithQuotaTag(PagedPool,
  182. InputBufferLength, ' GD');
  183. if (Irp->AssociatedIrp.SystemBuffer == NULL) {
  184. return STATUS_INSUFFICIENT_RESOURCES;
  185. }
  186. //
  187. // If called from a user process,
  188. // probe the buffer to ensure it is in the callers address space.
  189. //
  190. if (Irp->RequestorMode != KernelMode) {
  191. ProbeForRead( InputBuffer,
  192. InputBufferLength,
  193. sizeof(UCHAR));
  194. }
  195. RtlCopyMemory( Irp->AssociatedIrp.SystemBuffer,
  196. InputBuffer,
  197. InputBufferLength);
  198. Irp->Flags |= (IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER);
  199. } else {
  200. Irp->AssociatedIrp.SystemBuffer = NULL;
  201. }
  202. } except (BR_EXCEPTION) {
  203. if (Irp->AssociatedIrp.SystemBuffer != NULL) {
  204. ExFreePool(Irp->AssociatedIrp.SystemBuffer);
  205. }
  206. return GetExceptionCode();
  207. }
  208. return STATUS_SUCCESS;
  209. }
  210. ULONG
  211. BowserPackNtString(
  212. PUNICODE_STRING string,
  213. ULONG_PTR BufferDisplacement,
  214. PCHAR dataend,
  215. PCHAR * laststring
  216. )
  217. /** BowserPackNtString
  218. *
  219. * BowserPackNtString is used to stuff variable-length data, which
  220. * is pointed to by (surpise!) a pointer. The data is assumed
  221. * to be a nul-terminated string (ASCIIZ). Repeated calls to
  222. * this function are used to pack data from an entire structure.
  223. *
  224. * Upon first call, the laststring pointer should point to just
  225. * past the end of the buffer. Data will be copied into the buffer from
  226. * the end, working towards the beginning. If a data item cannot
  227. * fit, the pointer will be set to NULL, else the pointer will be
  228. * set to the new data location.
  229. *
  230. * Pointers which are passed in as NULL will be set to be pointer
  231. * to and empty string, as the NULL-pointer is reserved for
  232. * data which could not fit as opposed to data not available.
  233. *
  234. * Returns: 0 if could not fit data into buffer
  235. * else size of data stuffed (guaranteed non-zero)
  236. *
  237. * See the test case for sample usage. (tst/packtest.c)
  238. */
  239. {
  240. LONG size;
  241. PAGED_CODE();
  242. dlog(DPRT_PACK, ("BowserPackNtString:\n"));
  243. dlog(DPRT_PACK, (" string=%Fp, *string=%Fp, **string=\"%us\"\n",
  244. string, *string, *string));
  245. dlog(DPRT_PACK, (" end=%Fp\n", dataend));
  246. dlog(DPRT_PACK, (" last=%Fp, *last=%Fp, **last=\"%us\"\n",
  247. laststring, *laststring, *laststring));
  248. ASSERT (dataend < *laststring);
  249. //
  250. // is there room for the string?
  251. //
  252. size = string->Length;
  253. if ((*laststring - dataend) < size) {
  254. string->Length = 0;
  255. return(0);
  256. } else {
  257. *laststring -= size;
  258. RtlCopyMemory(*laststring, string->Buffer, size);
  259. string->Buffer = (PWSTR)((*laststring) - BufferDisplacement);
  260. return(size);
  261. }
  262. }
  263. ULONG
  264. BowserPackUnicodeString(
  265. IN OUT PWCHAR * string, // pointer by reference: string to be copied.
  266. IN ULONG StringLength, // Length of this string (in bytes) (w/o trailing zero)
  267. IN ULONG_PTR OutputBufferDisplacement, // Amount to subtract from output buffer
  268. IN PVOID dataend, // pointer to end of fixed size data.
  269. IN OUT PVOID * laststring // pointer by reference: top of string data.
  270. )
  271. /*++
  272. Routine Description:
  273. BowserPackUnicodeString is used to stuff variable-length data, which
  274. is pointed to by (surpise!) a pointer. The data is assumed
  275. to be a nul-terminated string (ASCIIZ). Repeated calls to
  276. this function are used to pack data from an entire structure.
  277. Upon first call, the laststring pointer should point to just
  278. past the end of the buffer. Data will be copied into the buffer from
  279. the end, working towards the beginning. If a data item cannot
  280. fit, the pointer will be set to NULL, else the pointer will be
  281. set to the new data location.
  282. Pointers which are passed in as NULL will be set to be pointer
  283. to and empty string, as the NULL-pointer is reserved for
  284. data which could not fit as opposed to data not available.
  285. See the test case for sample usage. (tst/packtest.c)
  286. Arguments:
  287. string - pointer by reference: string to be copied.
  288. dataend - pointer to end of fixed size data.
  289. laststring - pointer by reference: top of string data.
  290. Return Value:
  291. 0 - if it could not fit data into the buffer. Or...
  292. sizeOfData - the size of data stuffed (guaranteed non-zero)
  293. --*/
  294. {
  295. DWORD size;
  296. DWORD Available = (DWORD)((PCHAR)*laststring - (PCHAR)dataend);
  297. WCHAR StringBuffer[1] = L"";
  298. PAGED_CODE();
  299. //
  300. // Verify that there is room left for the string. If a NULL string
  301. // is input, there must be at least room for a UNICODE NULL, so set
  302. // size to sizeof(WCHAR) in this case.
  303. //
  304. if (*string == NULL) {
  305. StringLength = 0;
  306. *string = StringBuffer;
  307. }
  308. size = StringLength + sizeof(WCHAR);
  309. if (*laststring < dataend || size > Available) {
  310. *string = UNICODE_NULL;
  311. return(0);
  312. }
  313. *((PCHAR *)laststring) -= size;
  314. RtlCopyMemory(*laststring, *string, size-sizeof(WCHAR));
  315. *string = *laststring;
  316. (*string)[StringLength/2] = L'\0';
  317. *(PCHAR*)string -=OutputBufferDisplacement;
  318. return(size);
  319. } // BowserUnicodePackString
  320. ULONG
  321. BowserTimeUp(
  322. VOID
  323. )
  324. /*++
  325. Routine Description:
  326. BowserTimeUp is used to return the number of seconds the browser has been
  327. running.
  328. Arguments:
  329. None
  330. Return Value:
  331. Number of seconds the browser has been up.
  332. --*/
  333. {
  334. LARGE_INTEGER CurrentTime;
  335. LARGE_INTEGER TimeDelta;
  336. LARGE_INTEGER TimeUp;
  337. //
  338. // These are the magic numbers needed to do our extended division. The
  339. // only numbers we ever need to divide by are
  340. //
  341. // 10,000 = convert 100ns tics to millisecond tics
  342. //
  343. //
  344. // These values were stolen from ntos\rtl\time.c
  345. //
  346. LARGE_INTEGER Magic10000 = {0xe219652c, 0xd1b71758};
  347. #define SHIFT10000 13
  348. PAGED_CODE();
  349. KeQuerySystemTime(&CurrentTime);
  350. TimeDelta.QuadPart = CurrentTime.QuadPart - BowserStartTime.QuadPart;
  351. //
  352. // TimeDelta is the number of 100ns units the bowser has been up. Convert
  353. // it to milliseconds using the magic routine.
  354. //
  355. TimeUp = RtlExtendedMagicDivide(TimeDelta, Magic10000, SHIFT10000);
  356. //
  357. // Please note that TimeUp.LowPart wraps after about 49 days,
  358. // this means that if a machine has been up for more than 49 days,
  359. // we peg at 0xffffffff.
  360. //
  361. if (TimeUp.HighPart != 0) {
  362. return(0xffffffff);
  363. }
  364. return(TimeUp.LowPart);
  365. }
  366. ULONG
  367. BowserRandom(
  368. IN ULONG MaxValue
  369. )
  370. /*++
  371. Routine Description:
  372. BowserRandom is used to return a random number between 0 and MaxValue
  373. Arguments:
  374. MaxValue - The maximum value to return.
  375. Return Value:
  376. Random # between 0 and MaxValue
  377. --*/
  378. {
  379. PAGED_CODE();
  380. return RtlRandom(&BowserRandomSeed) % MaxValue;
  381. }
  382. VOID
  383. BowserReferenceDiscardableCode(
  384. DISCARDABLE_SECTION_NAME SectionName
  385. )
  386. /*++
  387. Routine Description:
  388. BowserReferenceDiscardableCode is called to reference the browsers
  389. discardable code section.
  390. If the section is not present in memory, MmLockPagableCodeSection is
  391. called to fault the section into memory.
  392. Arguments:
  393. None.
  394. Return Value:
  395. None.
  396. --*/
  397. {
  398. PAGED_CODE();
  399. RdrReferenceDiscardableCode(SectionName);
  400. }
  401. VOID
  402. BowserDereferenceDiscardableCode(
  403. DISCARDABLE_SECTION_NAME SectionName
  404. )
  405. /*++
  406. Routine Description:
  407. BowserDereferenceDiscardableCode is called to dereference the browsers
  408. discardable code section.
  409. When the reference count drops to 0, a timer is set that will fire in <n>
  410. seconds, after which time the section will be unlocked.
  411. Arguments:
  412. None.
  413. Return Value:
  414. None.
  415. --*/
  416. {
  417. PAGED_CODE();
  418. RdrDereferenceDiscardableCode(SectionName);
  419. }
  420. VOID
  421. BowserInitializeDiscardableCode(
  422. VOID
  423. )
  424. {
  425. }
  426. VOID
  427. BowserUninitializeDiscardableCode(
  428. VOID
  429. )
  430. {
  431. PAGED_CODE();
  432. }
  433. #if BOWSERPOOLDBG
  434. typedef struct {
  435. ULONG Count;
  436. ULONG Size;
  437. PCHAR FileName;
  438. ULONG LineNumber;
  439. } POOL_STATS, *PPOOL_STATS;
  440. typedef struct _POOL_HEADER {
  441. // LIST_ENTRY ListEntry;
  442. ULONG NumberOfBytes;
  443. PPOOL_STATS Stats;
  444. } POOL_HEADER, *PPOOL_HEADER;
  445. ULONG CurrentAllocationCount;
  446. ULONG CurrentAllocationSize;
  447. ULONG NextFreeEntry = 0;
  448. POOL_STATS PoolStats[POOL_MAXTYPE+1];
  449. PVOID
  450. BowserAllocatePool (
  451. IN POOL_TYPE PoolType,
  452. IN ULONG NumberOfBytes,
  453. IN PCHAR FileName,
  454. IN ULONG LineNumber,
  455. IN ULONG Tag
  456. )
  457. {
  458. PPOOL_HEADER header;
  459. KIRQL oldIrql;
  460. #if 1
  461. ULONG i;
  462. #endif
  463. #if POOL_TAGGING
  464. header = ExAllocatePoolWithTag( PoolType, sizeof(POOL_HEADER) + NumberOfBytes, Tag );
  465. #else
  466. header = ExAllocatePool( PoolType, sizeof(POOL_HEADER) + NumberOfBytes );
  467. #endif
  468. if ( header == NULL ) {
  469. return NULL;
  470. }
  471. header->NumberOfBytes = NumberOfBytes;
  472. // DbgPrint( "BOWSER: allocated type %d, size %d at %x\n", AllocationType, NumberOfBytes, header );
  473. ACQUIRE_SPIN_LOCK( &BowserTimeSpinLock, &oldIrql );
  474. CurrentAllocationCount++;
  475. CurrentAllocationSize += NumberOfBytes;
  476. #if 1
  477. //
  478. // Lets see if we've already allocated one of these guys.
  479. //
  480. for (i = 0;i < POOL_MAXTYPE ; i+= 1 ) {
  481. if ((PoolStats[i].LineNumber == LineNumber) &&
  482. (PoolStats[i].FileName == FileName)) {
  483. //
  484. // Yup, remember this allocation and return.
  485. //
  486. header->Stats = &PoolStats[i];
  487. PoolStats[i].Count++;
  488. PoolStats[i].Size += NumberOfBytes;
  489. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  490. return header + 1;
  491. }
  492. }
  493. for (i = NextFreeEntry; i < POOL_MAXTYPE ; i+= 1 ) {
  494. if ((PoolStats[i].LineNumber == 0) &&
  495. (PoolStats[i].FileName == NULL)) {
  496. PoolStats[i].Count++;
  497. PoolStats[i].Size += NumberOfBytes;
  498. PoolStats[i].FileName = FileName;
  499. PoolStats[i].LineNumber = LineNumber;
  500. header->Stats = &PoolStats[i];
  501. NextFreeEntry = i+1;
  502. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  503. return header + 1;
  504. }
  505. }
  506. header->Stats = &PoolStats[i];
  507. PoolStats[POOL_MAXTYPE].Count++;
  508. PoolStats[POOL_MAXTYPE].Size += NumberOfBytes;
  509. #endif
  510. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  511. return header + 1;
  512. }
  513. PVOID
  514. BowserAllocatePoolWithQuota (
  515. IN POOL_TYPE PoolType,
  516. IN ULONG NumberOfBytes,
  517. IN PCHAR FileName,
  518. IN ULONG LineNumber,
  519. IN ULONG Tag
  520. )
  521. {
  522. PPOOL_HEADER header;
  523. KIRQL oldIrql;
  524. #if 1
  525. ULONG i;
  526. #endif
  527. #if POOL_TAGGING
  528. header = ExAllocatePoolWithTagQuota( PoolType, sizeof(POOL_HEADER) + NumberOfBytes, Tag );
  529. #else
  530. header = ExAllocatePoolWithQuota( PoolType, sizeof(POOL_HEADER) + NumberOfBytes );
  531. #endif
  532. if ( header == NULL ) {
  533. return NULL;
  534. }
  535. header->NumberOfBytes = NumberOfBytes;
  536. // DbgPrint( "BOWSER: allocated type %d, size %d at %x\n", AllocationType, NumberOfBytes, header );
  537. ACQUIRE_SPIN_LOCK( &BowserTimeSpinLock, &oldIrql );
  538. CurrentAllocationCount++;
  539. CurrentAllocationSize += NumberOfBytes;
  540. #if 1
  541. //
  542. // Lets see if we've already allocated one of these guys.
  543. //
  544. for (i = 0;i < POOL_MAXTYPE ; i+= 1 ) {
  545. if ((PoolStats[i].LineNumber == LineNumber) &&
  546. (PoolStats[i].FileName == FileName)) {
  547. //
  548. // Yup, remember this allocation and return.
  549. //
  550. header->Stats = &PoolStats[i];
  551. PoolStats[i].Count++;
  552. PoolStats[i].Size += NumberOfBytes;
  553. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  554. return header + 1;
  555. }
  556. }
  557. for (i = NextFreeEntry; i < POOL_MAXTYPE ; i+= 1 ) {
  558. if ((PoolStats[i].LineNumber == 0) &&
  559. (PoolStats[i].FileName == NULL)) {
  560. PoolStats[i].Count++;
  561. PoolStats[i].Size += NumberOfBytes;
  562. PoolStats[i].FileName = FileName;
  563. PoolStats[i].LineNumber = LineNumber;
  564. header->Stats = &PoolStats[i];
  565. NextFreeEntry = i+1;
  566. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  567. return header + 1;
  568. }
  569. }
  570. header->Stats = &PoolStats[i];
  571. PoolStats[POOL_MAXTYPE].Count++;
  572. PoolStats[POOL_MAXTYPE].Size += NumberOfBytes;
  573. #endif
  574. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  575. return header + 1;
  576. }
  577. VOID
  578. BowserFreePool (
  579. IN PVOID P
  580. )
  581. {
  582. PPOOL_HEADER header;
  583. KIRQL oldIrql;
  584. PPOOL_STATS stats;
  585. ULONG size;
  586. header = (PPOOL_HEADER)P - 1;
  587. size = header->NumberOfBytes;
  588. stats = header->Stats;
  589. // if ( allocationType > POOL_MAXTYPE ) allocationType = POOL_MAXTYPE;
  590. // DbgPrint( "BOWSER: freed type %d, size %d at %x\n", allocationType, size, header );
  591. ACQUIRE_SPIN_LOCK( &BowserTimeSpinLock, &oldIrql );
  592. CurrentAllocationCount--;
  593. CurrentAllocationSize -= size;
  594. #if 1
  595. stats->Count--;
  596. stats->Size -= size;
  597. #endif
  598. RELEASE_SPIN_LOCK( &BowserTimeSpinLock, oldIrql );
  599. ExFreePool( header );
  600. return;
  601. }
  602. #endif // BOWSERPOOLDBG
  603. #if DBG
  604. ERESOURCE
  605. BrowserTraceLock;
  606. HANDLE
  607. BrowserTraceLogHandle = NULL;
  608. UCHAR LastCharacter = '\n';
  609. #ifndef PRODUCT1
  610. VOID
  611. BowserTrace(
  612. PCHAR FormatString,
  613. ...
  614. )
  615. #define LAST_NAMED_ARGUMENT FormatString
  616. {
  617. CHAR OutputString[1024];
  618. IO_STATUS_BLOCK IoStatus;
  619. BOOLEAN ProcessAttached = FALSE;
  620. BOOLEAN ReleaseResource = FALSE;
  621. va_list ParmPtr; // Pointer to stack parms.
  622. KAPC_STATE ApcState;
  623. NTSTATUS Status;
  624. PAGED_CODE();
  625. if (BrowserTraceLogHandle == NULL) {
  626. // Attach to FSP when using handle
  627. if (IoGetCurrentProcess() != BowserFspProcess) {
  628. KeStackAttachProcess(BowserFspProcess, &ApcState );
  629. ProcessAttached = TRUE;
  630. }
  631. if (!NT_SUCCESS(BowserOpenTraceLogFile(L"\\SystemRoot\\Bowser.Log"))) {
  632. BrowserTraceLogHandle = (HANDLE) -1;
  633. if (ProcessAttached) {
  634. KeUnstackDetachProcess( &ApcState );
  635. }
  636. return;
  637. }
  638. } else if (BrowserTraceLogHandle == (HANDLE) -1) {
  639. if (ProcessAttached) {
  640. KeUnstackDetachProcess( &ApcState );
  641. }
  642. return;
  643. }
  644. try {
  645. LARGE_INTEGER EndOfFile;
  646. ExAcquireResourceExclusive(&BrowserTraceLock, TRUE);
  647. ReleaseResource = TRUE;
  648. // re-verify we should be tracing (under lock).
  649. if (BrowserTraceLogHandle == NULL) {
  650. try_return(Status);
  651. }
  652. EndOfFile.HighPart = 0xffffffff;
  653. EndOfFile.LowPart = FILE_WRITE_TO_END_OF_FILE;
  654. if (LastCharacter == '\n') {
  655. LARGE_INTEGER SystemTime;
  656. TIME_FIELDS TimeFields;
  657. KeQuerySystemTime(&SystemTime);
  658. ExSystemTimeToLocalTime(&SystemTime, &SystemTime);
  659. RtlTimeToTimeFields(&SystemTime, &TimeFields);
  660. //
  661. // The last character written was a newline character. We should
  662. // timestamp this record in the file.
  663. //
  664. sprintf(OutputString, "%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%3.3d: ",
  665. TimeFields.Month,
  666. TimeFields.Day,
  667. TimeFields.Hour,
  668. TimeFields.Minute,
  669. TimeFields.Second,
  670. TimeFields.Milliseconds);
  671. // Attach to FSP when using handle
  672. if (IoGetCurrentProcess() != BowserFspProcess) {
  673. KeStackAttachProcess(BowserFspProcess, &ApcState );
  674. ProcessAttached = TRUE;
  675. }
  676. if (!NT_SUCCESS(Status = ZwWriteFile(BrowserTraceLogHandle, NULL, NULL, NULL, &IoStatus, OutputString, strlen(OutputString), &EndOfFile, NULL))) {
  677. KdPrint(("Error writing time to Browser log file: %lX\n", Status));
  678. try_return(Status);
  679. }
  680. if (!NT_SUCCESS(IoStatus.Status)) {
  681. KdPrint(("Error writing time to Browser log file: %lX\n", IoStatus.Status));
  682. try_return(Status);
  683. }
  684. if (IoStatus.Information != strlen(OutputString)) {
  685. KdPrint(("Error writing time to Browser log file: %lX\n", IoStatus.Status));
  686. try_return(Status);
  687. }
  688. }
  689. va_start(ParmPtr, LAST_NAMED_ARGUMENT);
  690. // Be in caller's process when referencing parameters.
  691. if (ProcessAttached) {
  692. KeUnstackDetachProcess( &ApcState );
  693. ProcessAttached = FALSE;
  694. }
  695. //
  696. // Format the parameters to the string.
  697. //
  698. vsprintf(OutputString, FormatString, ParmPtr);
  699. // Attach to FSP when using handle
  700. if (IoGetCurrentProcess() != BowserFspProcess) {
  701. KeStackAttachProcess(BowserFspProcess, &ApcState );
  702. ProcessAttached = TRUE;
  703. }
  704. if (!NT_SUCCESS(Status = ZwWriteFile(BrowserTraceLogHandle, NULL, NULL, NULL, &IoStatus, OutputString, strlen(OutputString), &EndOfFile, NULL))) {
  705. KdPrint(("Error writing string to Browser log file: %ld\n", Status));
  706. try_return(Status);
  707. }
  708. if (!NT_SUCCESS(IoStatus.Status)) {
  709. KdPrint(("Error writing string to Browser log file: %lX\n", IoStatus.Status));
  710. try_return(Status);
  711. }
  712. if (IoStatus.Information != strlen(OutputString)) {
  713. KdPrint(("Error writing string to Browser log file: %ld\n", IoStatus.Status));
  714. try_return(Status);
  715. }
  716. //
  717. // Remember the last character output to the log.
  718. //
  719. LastCharacter = OutputString[strlen(OutputString)-1];
  720. try_exit:NOTHING;
  721. } finally {
  722. if (ReleaseResource) {
  723. ExReleaseResource(&BrowserTraceLock);
  724. }
  725. if (ProcessAttached) {
  726. KeUnstackDetachProcess( &ApcState );
  727. }
  728. }
  729. }
  730. #endif
  731. VOID
  732. BowserInitializeTraceLog()
  733. {
  734. PAGED_CODE();
  735. ExInitializeResource(&BrowserTraceLock);
  736. }
  737. NTSTATUS
  738. BowserOpenTraceLogFile(
  739. IN PWCHAR TraceFile
  740. )
  741. {
  742. UNICODE_STRING TraceFileName;
  743. OBJECT_ATTRIBUTES ObjA;
  744. NTSTATUS Status;
  745. IO_STATUS_BLOCK IoStatusBlock;
  746. PAGED_CODE();
  747. RtlInitUnicodeString(&TraceFileName, TraceFile);
  748. InitializeObjectAttributes(&ObjA, &TraceFileName, OBJ_CASE_INSENSITIVE, NULL, NULL);
  749. Status = IoCreateFile(&BrowserTraceLogHandle,
  750. FILE_APPEND_DATA|SYNCHRONIZE,
  751. &ObjA,
  752. &IoStatusBlock,
  753. NULL,
  754. FILE_ATTRIBUTE_NORMAL,
  755. FILE_SHARE_READ,
  756. FILE_OPEN_IF,
  757. FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE | FILE_SEQUENTIAL_ONLY,
  758. NULL,
  759. 0,
  760. CreateFileTypeNone,
  761. NULL,
  762. IO_FORCE_ACCESS_CHECK | // Ensure the user has access to the file
  763. IO_NO_PARAMETER_CHECKING | // All of the buffers are kernel buffers
  764. IO_CHECK_CREATE_PARAMETERS // But double check parameter consistancy
  765. );
  766. if (!NT_SUCCESS(Status)) {
  767. KdPrint(("Bowser: Error creating trace file %ws %lX\n", TraceFile, Status));
  768. return Status;
  769. }
  770. return Status;
  771. }
  772. VOID
  773. BowserUninitializeTraceLog()
  774. {
  775. BOOLEAN ProcessAttached = FALSE;
  776. KAPC_STATE ApcState;
  777. PAGED_CODE();
  778. ExDeleteResource(&BrowserTraceLock);
  779. if (BrowserTraceLogHandle != NULL) {
  780. if (IoGetCurrentProcess() != BowserFspProcess) {
  781. KeStackAttachProcess(BowserFspProcess, &ApcState );
  782. ProcessAttached = TRUE;
  783. }
  784. ZwClose(BrowserTraceLogHandle);
  785. if (ProcessAttached) {
  786. KeUnstackDetachProcess( &ApcState );
  787. }
  788. }
  789. BrowserTraceLogHandle = NULL;
  790. }
  791. NTSTATUS
  792. BowserDebugCall(
  793. IN PLMDR_REQUEST_PACKET InputBuffer,
  794. IN ULONG InputBufferLength
  795. )
  796. {
  797. NTSTATUS Status;
  798. BOOLEAN ProcessAttached = FALSE;
  799. KAPC_STATE ApcState;
  800. PAGED_CODE();
  801. if (IoGetCurrentProcess() != BowserFspProcess) {
  802. KeStackAttachProcess(BowserFspProcess, &ApcState );
  803. ProcessAttached = TRUE;
  804. }
  805. try {
  806. if (InputBufferLength < sizeof(LMDR_REQUEST_PACKET)) {
  807. try_return(Status=STATUS_BUFFER_TOO_SMALL);
  808. }
  809. if ( InputBuffer->Version != LMDR_REQUEST_PACKET_VERSION_DOM ) {
  810. try_return(Status=STATUS_INVALID_PARAMETER);
  811. }
  812. if (InputBuffer->Parameters.Debug.OpenLog && InputBuffer->Parameters.Debug.CloseLog) {
  813. try_return(Status=STATUS_INVALID_PARAMETER);
  814. }
  815. if (InputBuffer->Parameters.Debug.OpenLog) {
  816. ENSURE_IN_INPUT_BUFFER_STR( InputBuffer->Parameters.Debug.TraceFileName);
  817. Status = BowserOpenTraceLogFile(InputBuffer->Parameters.Debug.TraceFileName);
  818. } else if (InputBuffer->Parameters.Debug.CloseLog) {
  819. Status = ZwClose(BrowserTraceLogHandle);
  820. if (NT_SUCCESS(Status)) {
  821. BrowserTraceLogHandle = NULL;
  822. }
  823. } else if (InputBuffer->Parameters.Debug.TruncateLog) {
  824. FILE_END_OF_FILE_INFORMATION EndOfFileInformation;
  825. IO_STATUS_BLOCK IoStatus;
  826. if (BrowserTraceLogHandle == NULL) {
  827. try_return(Status=STATUS_INVALID_HANDLE);
  828. }
  829. EndOfFileInformation.EndOfFile.HighPart = 0;
  830. EndOfFileInformation.EndOfFile.LowPart = 0;
  831. Status = NtSetInformationFile(BrowserTraceLogHandle,
  832. &IoStatus,
  833. &EndOfFileInformation,
  834. sizeof(EndOfFileInformation),
  835. FileEndOfFileInformation);
  836. } else {
  837. BowserDebugLogLevel = InputBuffer->Parameters.Debug.DebugTraceBits;
  838. KdPrint(("Setting Browser Debug Trace Bits to %lx\n", BowserDebugLogLevel));
  839. Status = STATUS_SUCCESS;
  840. }
  841. try_return(Status);
  842. try_exit:NOTHING;
  843. } finally {
  844. if (ProcessAttached) {
  845. KeUnstackDetachProcess( &ApcState );
  846. }
  847. }
  848. return Status;
  849. }
  850. #endif