2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: ntoskrnl/rtl/libsupp.c
5 * PURPOSE: RTL Support Routines
6 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
10 /* INCLUDES ******************************************************************/
16 #define TAG_ATMT 'TotA' /* Atom table */
18 extern ULONG NtGlobalFlag
;
20 typedef struct _RTL_RANGE_ENTRY
24 } RTL_RANGE_ENTRY
, *PRTL_RANGE_ENTRY
;
26 PAGED_LOOKASIDE_LIST RtlpRangeListEntryLookasideList
;
27 SIZE_T RtlpAllocDeallocQueryBufferSize
= 128;
29 /* FUNCTIONS *****************************************************************/
35 OUT PVOID
*BaseOfImage
)
37 PLDR_DATA_TABLE_ENTRY LdrEntry
;
40 /* Get the base for this file */
41 if ((ULONG_PTR
)PcValue
> (ULONG_PTR
)MmHighestUserAddress
)
43 /* We are in kernel */
44 *BaseOfImage
= KiPcToFileHeader(PcValue
, &LdrEntry
, FALSE
, &InSystem
);
48 /* We are in user land */
49 *BaseOfImage
= KiRosPcToUserFileHeader(PcValue
, &LdrEntry
);
57 RtlInitializeRangeListPackage(VOID
)
59 /* Setup the lookaside list for allocations (not used yet) */
60 ExInitializePagedLookasideList(&RtlpRangeListEntryLookasideList
,
64 sizeof(RTL_RANGE_ENTRY
),
71 RtlpCheckForActiveDebugger(VOID
)
73 /* This check is meaningless in kernel-mode */
79 RtlpSetInDbgPrint(VOID
)
81 /* Nothing to set in kernel mode */
87 RtlpClearInDbgPrint(VOID
)
89 /* Nothing to clear in kernel mode */
101 RtlpAllocateMemory(ULONG Bytes
,
104 return ExAllocatePoolWithTag(PagedPool
,
110 #define TAG_USTR 'RTSU'
111 #define TAG_ASTR 'RTSA'
112 #define TAG_OSTR 'RTSO'
115 RtlpFreeMemory(PVOID Mem
,
118 if (Tag
== TAG_ASTR
|| Tag
== TAG_OSTR
|| Tag
== TAG_USTR
)
121 ExFreePoolWithTag(Mem
, Tag
);
128 RtlAcquirePebLock(VOID
)
137 RtlReleasePebLock(VOID
)
144 LdrShutdownThread(VOID
)
146 return STATUS_SUCCESS
;
152 RtlGetCurrentPeb(VOID
)
154 return ((PEPROCESS
)(KeGetCurrentThread()->ApcState
.Process
))->Peb
;
159 RtlDeleteHeapLock(IN OUT PHEAP_LOCK Lock
)
161 ExDeleteResourceLite(&Lock
->Resource
);
164 return STATUS_SUCCESS
;
169 RtlEnterHeapLock(IN OUT PHEAP_LOCK Lock
, IN BOOLEAN Exclusive
)
171 KeEnterCriticalRegion();
174 ExAcquireResourceExclusiveLite(&Lock
->Resource
, TRUE
);
176 ExAcquireResourceSharedLite(&Lock
->Resource
, TRUE
);
178 return STATUS_SUCCESS
;
183 RtlInitializeHeapLock(IN OUT PHEAP_LOCK
*Lock
)
185 PHEAP_LOCK HeapLock
= ExAllocatePool(NonPagedPool
, sizeof(HEAP_LOCK
));
186 if (HeapLock
== NULL
)
187 return STATUS_NO_MEMORY
;
189 ExInitializeResourceLite(&HeapLock
->Resource
);
192 return STATUS_SUCCESS
;
197 RtlLeaveHeapLock(IN OUT PHEAP_LOCK Lock
)
199 ExReleaseResourceLite(&Lock
->Resource
);
200 KeLeaveCriticalRegion();
202 return STATUS_SUCCESS
;
209 RtlpAddHeapToProcessList(struct _HEAP
*Heap
)
211 UNREFERENCED_PARAMETER(Heap
);
216 RtlpRemoveHeapFromProcessList(struct _HEAP
*Heap
)
218 UNREFERENCED_PARAMETER(Heap
);
222 RtlInitializeHeapManager(VOID
)
228 CHECK_PAGED_CODE_RTL(char *file
, int line
)
230 if(KeGetCurrentIrql() > APC_LEVEL
)
232 DbgPrint("%s:%i: Pagable code called at IRQL > APC_LEVEL (%u)\n", file
, line
, KeGetCurrentIrql());
240 RtlpSetHeapParameters(IN PRTL_HEAP_PARAMETERS Parameters
)
242 /* Apply defaults for non-set parameters */
243 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= MmHeapSegmentCommit
;
244 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= MmHeapSegmentReserve
;
245 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= MmHeapDeCommitFreeBlockThreshold
;
246 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= MmHeapDeCommitTotalFreeThreshold
;
251 RtlpCheckLogException(IN PEXCEPTION_RECORD ExceptionRecord
,
252 IN PCONTEXT ContextRecord
,
253 IN PVOID ContextData
,
256 /* Check the global flag */
257 if (NtGlobalFlag
& FLG_ENABLE_EXCEPTION_LOGGING
)
259 /* FIXME: Log this exception */
265 RtlpHandleDpcStackException(IN PEXCEPTION_REGISTRATION_RECORD RegistrationFrame
,
266 IN ULONG_PTR RegistrationFrameEnd
,
267 IN OUT PULONG_PTR StackLow
,
268 IN OUT PULONG_PTR StackHigh
)
273 /* Check if we are at DISPATCH or higher */
274 if (KeGetCurrentIrql() >= DISPATCH_LEVEL
)
276 /* Get the PRCB and DPC Stack */
277 Prcb
= KeGetCurrentPrcb();
278 DpcStack
= (ULONG_PTR
)Prcb
->DpcStack
;
280 /* Check if we are in a DPC and the stack matches */
281 if ((Prcb
->DpcRoutineActive
) &&
282 (RegistrationFrameEnd
<= DpcStack
) &&
283 ((ULONG_PTR
)RegistrationFrame
>= DpcStack
- KERNEL_STACK_SIZE
))
285 /* Update the limits to the DPC Stack's */
286 *StackHigh
= DpcStack
;
287 *StackLow
= DpcStack
- KERNEL_STACK_SIZE
;
292 /* Not in DPC stack */
296 #if !defined(_ARM_) && !defined(_AMD64_)
300 RtlpCaptureStackLimits(IN ULONG_PTR Ebp
,
301 IN ULONG_PTR
*StackBegin
,
302 IN ULONG_PTR
*StackEnd
)
304 PKTHREAD Thread
= KeGetCurrentThread();
306 /* Don't even try at ISR level or later */
307 if (KeGetCurrentIrql() > DISPATCH_LEVEL
) return FALSE
;
309 /* Start with defaults */
310 *StackBegin
= Thread
->StackLimit
;
311 *StackEnd
= (ULONG_PTR
)Thread
->StackBase
;
313 /* Check if EBP is inside the stack */
314 if ((*StackBegin
<= Ebp
) && (Ebp
<= *StackEnd
))
316 /* Then make the stack start at EBP */
321 /* Now we're going to assume we're on the DPC stack */
322 *StackEnd
= (ULONG_PTR
)(KeGetPcr()->Prcb
->DpcStack
);
323 *StackBegin
= *StackEnd
- KERNEL_STACK_SIZE
;
325 /* Check if we seem to be on the DPC stack */
326 if ((*StackEnd
) && (*StackBegin
< Ebp
) && (Ebp
<= *StackEnd
))
328 /* We're on the DPC stack */
333 /* We're somewhere else entirely... use EBP for safety */
335 *StackEnd
= (ULONG_PTR
)PAGE_ALIGN(*StackBegin
);
348 RtlWalkFrameChain(OUT PVOID
*Callers
,
352 ULONG_PTR Stack
, NewStack
, StackBegin
, StackEnd
= 0;
354 BOOLEAN Result
, StopSearch
= FALSE
;
356 PETHREAD Thread
= PsGetCurrentThread();
358 PKTRAP_FRAME TrapFrame
;
360 /* Get current EBP */
363 __asm__("mov %%ebp, %0" : "=r" (Stack
) : );
364 #elif defined(_MSC_VER)
367 #elif defined(_M_MIPS)
368 __asm__("move $sp, %0" : "=r" (Stack
) : );
369 #elif defined(_M_PPC)
370 __asm__("mr %0,1" : "=r" (Stack
) : );
371 #elif defined(_M_ARM)
372 __asm__("mov sp, %0" : "=r"(Stack
) : );
374 #error Unknown architecture
377 /* Set it as the stack begin limit as well */
378 StackBegin
= (ULONG_PTR
)Stack
;
380 /* Check if we're called for non-logging mode */
383 /* Get the actual safe limits */
384 Result
= RtlpCaptureStackLimits((ULONG_PTR
)Stack
,
387 if (!Result
) return 0;
390 /* Use a SEH block for maximum protection */
393 /* Check if we want the user-mode stack frame */
396 /* Get the trap frame and TEB */
397 TrapFrame
= KeGetTrapFrame(&Thread
->Tcb
);
398 Teb
= Thread
->Tcb
.Teb
;
400 /* Make sure we can trust the TEB and trap frame */
402 (KeIsAttachedProcess()) ||
403 (KeGetCurrentIrql() >= DISPATCH_LEVEL
))
405 /* Invalid or unsafe attempt to get the stack */
406 _SEH2_YIELD(return 0;)
409 /* Get the stack limits */
410 StackBegin
= (ULONG_PTR
)Teb
->NtTib
.StackLimit
;
411 StackEnd
= (ULONG_PTR
)Teb
->NtTib
.StackBase
;
413 Stack
= TrapFrame
->Ebp
;
414 #elif defined(_M_PPC)
415 Stack
= TrapFrame
->Gpr1
;
417 #error Unknown architecture
421 if (StackEnd
<= StackBegin
) _SEH2_YIELD(return 0);
422 ProbeForRead((PVOID
)StackBegin
,
423 StackEnd
- StackBegin
,
427 /* Loop the frames */
428 for (i
= 0; i
< Count
; i
++)
431 * Leave if we're past the stack,
432 * if we're before the stack,
433 * or if we've reached ourselves.
435 if ((Stack
>= StackEnd
) ||
436 (!i
? (Stack
< StackBegin
) : (Stack
<= StackBegin
)) ||
437 ((StackEnd
- Stack
) < (2 * sizeof(ULONG_PTR
))))
439 /* We're done or hit a bad address */
443 /* Get new stack and EIP */
444 NewStack
= *(PULONG_PTR
)Stack
;
445 Eip
= *(PULONG_PTR
)(Stack
+ sizeof(ULONG_PTR
));
447 /* Check if the new pointer is above the oldone and past the end */
448 if (!((Stack
< NewStack
) && (NewStack
< StackEnd
)))
450 /* Stop searching after this entry */
454 /* Also make sure that the EIP isn't a stack address */
455 if ((StackBegin
< Eip
) && (Eip
< StackEnd
)) break;
457 /* Check if we reached a user-mode address */
458 if (!(Flags
) && !(Eip
& 0x80000000)) break; // FIXME: 3GB breakage
460 /* Save this frame */
461 Callers
[i
] = (PVOID
)Eip
;
463 /* Check if we should continue */
466 /* Return the next index */
471 /* Move to the next stack */
475 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
482 /* Return frames parsed */
492 OUT PULONG_PTR LowLimit
,
493 OUT PULONG_PTR HighLimit
)
495 PKTHREAD CurrentThread
= KeGetCurrentThread();
496 *HighLimit
= (ULONG_PTR
)CurrentThread
->InitialStack
;
497 *LowLimit
= (ULONG_PTR
)CurrentThread
->StackLimit
;
501 /* RTL Atom Tables ************************************************************/
504 RtlpInitAtomTableLock(PRTL_ATOM_TABLE AtomTable
)
506 ExInitializeFastMutex(&AtomTable
->FastMutex
);
508 return STATUS_SUCCESS
;
513 RtlpDestroyAtomTableLock(PRTL_ATOM_TABLE AtomTable
)
519 RtlpLockAtomTable(PRTL_ATOM_TABLE AtomTable
)
521 ExAcquireFastMutex(&AtomTable
->FastMutex
);
526 RtlpUnlockAtomTable(PRTL_ATOM_TABLE AtomTable
)
528 ExReleaseFastMutex(&AtomTable
->FastMutex
);
532 RtlpCreateAtomHandleTable(PRTL_ATOM_TABLE AtomTable
)
534 AtomTable
->ExHandleTable
= ExCreateHandleTable(NULL
);
535 return (AtomTable
->ExHandleTable
!= NULL
);
540 RtlpCloseHandleCallback(
541 IN PHANDLE_TABLE_ENTRY HandleTableEntry
,
543 IN PVOID HandleTable
)
545 /* Destroy and unlock the handle entry */
546 return ExDestroyHandle(HandleTable
, Handle
, HandleTableEntry
);
550 RtlpDestroyAtomHandleTable(PRTL_ATOM_TABLE AtomTable
)
552 if (AtomTable
->ExHandleTable
)
554 ExSweepHandleTable(AtomTable
->ExHandleTable
,
555 RtlpCloseHandleCallback
,
556 AtomTable
->ExHandleTable
);
557 ExDestroyHandleTable(AtomTable
->ExHandleTable
, NULL
);
558 AtomTable
->ExHandleTable
= NULL
;
563 RtlpAllocAtomTable(ULONG Size
)
565 PRTL_ATOM_TABLE Table
= ExAllocatePool(NonPagedPool
,
577 RtlpFreeAtomTable(PRTL_ATOM_TABLE AtomTable
)
579 ExFreePool(AtomTable
);
582 PRTL_ATOM_TABLE_ENTRY
583 RtlpAllocAtomTableEntry(ULONG Size
)
585 PRTL_ATOM_TABLE_ENTRY Entry
;
587 Entry
= ExAllocatePoolWithTag(NonPagedPool
, Size
, TAG_ATMT
);
590 RtlZeroMemory(Entry
, Size
);
597 RtlpFreeAtomTableEntry(PRTL_ATOM_TABLE_ENTRY Entry
)
599 ExFreePoolWithTag(Entry
, TAG_ATMT
);
603 RtlpFreeAtomHandle(PRTL_ATOM_TABLE AtomTable
, PRTL_ATOM_TABLE_ENTRY Entry
)
605 ExDestroyHandle(AtomTable
->ExHandleTable
,
606 (HANDLE
)((ULONG_PTR
)Entry
->HandleIndex
<< 2),
611 RtlpCreateAtomHandle(PRTL_ATOM_TABLE AtomTable
, PRTL_ATOM_TABLE_ENTRY Entry
)
613 HANDLE_TABLE_ENTRY ExEntry
;
617 /* Initialize ex handle table entry */
618 ExEntry
.Object
= Entry
;
619 ExEntry
.GrantedAccess
= 0x1; /* FIXME - valid handle */
621 /* Create ex handle */
622 Handle
= ExCreateHandle(AtomTable
->ExHandleTable
,
624 if (!Handle
) return FALSE
;
626 /* Calculate HandleIndex (by getting rid of the first two bits) */
627 HandleIndex
= (USHORT
)((ULONG_PTR
)Handle
>> 2);
629 /* Index must be less than 0xC000 */
630 if (HandleIndex
>= 0xC000)
632 /* Destroy ex handle */
633 ExDestroyHandle(AtomTable
->ExHandleTable
,
641 /* Initialize atom table entry */
642 Entry
->HandleIndex
= HandleIndex
;
643 Entry
->Atom
= 0xC000 + HandleIndex
;
649 PRTL_ATOM_TABLE_ENTRY
650 RtlpGetAtomEntry(PRTL_ATOM_TABLE AtomTable
, ULONG Index
)
652 PHANDLE_TABLE_ENTRY ExEntry
;
653 PRTL_ATOM_TABLE_ENTRY Entry
= NULL
;
655 /* NOTE: There's no need to explicitly enter a critical region because it's
656 guaranteed that we're in a critical region right now (as we hold
657 the atom table lock) */
659 ExEntry
= ExMapHandleToPointer(AtomTable
->ExHandleTable
,
660 (HANDLE
)((ULONG_PTR
)Index
<< 2));
663 Entry
= ExEntry
->Object
;
665 ExUnlockHandleTableEntry(AtomTable
->ExHandleTable
,
673 * Ldr Resource support code
676 IMAGE_RESOURCE_DIRECTORY
*find_entry_by_name( IMAGE_RESOURCE_DIRECTORY
*dir
,
677 LPCWSTR name
, void *root
,
679 IMAGE_RESOURCE_DIRECTORY
*find_entry_by_id( IMAGE_RESOURCE_DIRECTORY
*dir
,
680 USHORT id
, void *root
, int want_dir
);
681 IMAGE_RESOURCE_DIRECTORY
*find_first_entry( IMAGE_RESOURCE_DIRECTORY
*dir
,
682 void *root
, int want_dir
);
684 /**********************************************************************
687 * Find a resource entry
689 NTSTATUS
find_entry( PVOID BaseAddress
, LDR_RESOURCE_INFO
*info
,
690 ULONG level
, void **ret
, int want_dir
)
694 IMAGE_RESOURCE_DIRECTORY
*resdirptr
;
696 root
= RtlImageDirectoryEntryToData( BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_RESOURCE
, &size
);
697 if (!root
) return STATUS_RESOURCE_DATA_NOT_FOUND
;
700 if (!level
--) goto done
;
701 if (!(*ret
= find_entry_by_name( resdirptr
, (LPCWSTR
)info
->Type
, root
, want_dir
|| level
)))
702 return STATUS_RESOURCE_TYPE_NOT_FOUND
;
703 if (!level
--) return STATUS_SUCCESS
;
706 if (!(*ret
= find_entry_by_name( resdirptr
, (LPCWSTR
)info
->Name
, root
, want_dir
|| level
)))
707 return STATUS_RESOURCE_NAME_NOT_FOUND
;
708 if (!level
--) return STATUS_SUCCESS
;
709 if (level
) return STATUS_INVALID_PARAMETER
; /* level > 3 */
713 if ((*ret
= find_first_entry( resdirptr
, root
, want_dir
))) return STATUS_SUCCESS
;
715 return STATUS_RESOURCE_DATA_NOT_FOUND
;
719 return STATUS_SUCCESS
;
725 _Out_writes_bytes_all_(Length
) VOID UNALIGNED
*Destination
,
726 _In_reads_bytes_(Length
) CONST VOID UNALIGNED
*Source
,
731 RtlCopyMemory(Destination
, Source
, Length
);
733 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
735 _SEH2_YIELD(return _SEH2_GetExceptionCode());
739 return STATUS_SUCCESS
;
744 RtlCallVectoredExceptionHandlers(
745 _In_ PEXCEPTION_RECORD ExceptionRecord
,
746 _In_ PCONTEXT Context
)
748 /* In the kernel we don't have vectored exception handlers */