2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT : ReactOS system libraries
4 * MODULE : kernel32.dll
5 * FILE : reactos/dll/win32/kernel32/misc/ldr.c
6 * AUTHOR : Aleksey Bragin <aleksey@reactos.org>
14 typedef struct tagLOADPARMS32
{
22 extern BOOLEAN InWindows
;
23 extern WaitForInputIdleType lpfnGlobalRegisterWaitForInputIdle
;
25 #define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR 1
26 #define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS 2
27 #define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_CONTINUE 3
31 BasepLocateExeLdrEntry(IN PLDR_DATA_TABLE_ENTRY Entry
,
33 OUT BOOLEAN
*StopEnumeration
);
35 /* FUNCTIONS ****************************************************************/
39 BasepGetModuleHandleExParameterValidation(DWORD dwFlags
,
40 LPCWSTR lpwModuleName
,
43 /* Set phModule to 0 if it's not a NULL pointer */
44 if (phModule
) *phModule
= 0;
46 /* Check for invalid flags combination */
47 if (dwFlags
& ~(GET_MODULE_HANDLE_EX_FLAG_PIN
|
48 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
|
49 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
) ||
50 ((dwFlags
& GET_MODULE_HANDLE_EX_FLAG_PIN
) &&
51 (dwFlags
& GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
)) ||
52 (!lpwModuleName
&& (dwFlags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
))
55 BaseSetLastNTError(STATUS_INVALID_PARAMETER_1
);
56 return BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
;
59 /* Check 2nd parameter */
62 BaseSetLastNTError(STATUS_INVALID_PARAMETER_2
);
63 return BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
;
66 /* Return what we have according to the module name */
69 return BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_CONTINUE
;
72 /* No name given, so put ImageBaseAddress there */
73 *phModule
= (HMODULE
)NtCurrentPeb()->ImageBaseAddress
;
75 return BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
;
80 BasepMapModuleHandle(HMODULE hModule
, BOOLEAN AsDataFile
)
82 /* If no handle is provided - use current image base address */
83 if (!hModule
) return NtCurrentPeb()->ImageBaseAddress
;
85 /* Check if it's a normal or a datafile one */
86 if (LDR_IS_DATAFILE(hModule
) && !AsDataFile
)
89 /* It'a a normal DLL, just return its handle */
94 * @name GetDllLoadPath
96 * Internal function to compute the load path to use for a given dll.
98 * @remarks Returned pointer must be freed by caller.
102 GetDllLoadPath(LPCWSTR lpModule
)
104 ULONG Pos
= 0, Length
= 0;
105 PWCHAR EnvironmentBufferW
= NULL
;
106 LPCWSTR lpModuleEnd
= NULL
;
107 UNICODE_STRING ModuleName
;
108 DWORD LastError
= GetLastError(); /* GetEnvironmentVariable changes LastError */
110 // FIXME: This function is used only by SearchPathW, and is deprecated and will be deleted ASAP.
112 if ((lpModule
!= NULL
) && (wcslen(lpModule
) > 2) && (lpModule
[1] == ':'))
114 lpModuleEnd
= lpModule
+ wcslen(lpModule
);
118 ModuleName
= NtCurrentPeb()->ProcessParameters
->ImagePathName
;
119 lpModule
= ModuleName
.Buffer
;
120 lpModuleEnd
= lpModule
+ (ModuleName
.Length
/ sizeof(WCHAR
));
123 if (lpModule
!= NULL
)
125 while (lpModuleEnd
> lpModule
&& *lpModuleEnd
!= L
'/' &&
126 *lpModuleEnd
!= L
'\\' && *lpModuleEnd
!= L
':')
130 Length
= (lpModuleEnd
- lpModule
) + 1;
133 Length
+= GetCurrentDirectoryW(0, NULL
);
134 Length
+= GetDllDirectoryW(0, NULL
);
135 Length
+= GetSystemDirectoryW(NULL
, 0);
136 Length
+= GetWindowsDirectoryW(NULL
, 0);
137 Length
+= GetEnvironmentVariableW(L
"PATH", NULL
, 0);
139 EnvironmentBufferW
= RtlAllocateHeap(RtlGetProcessHeap(), 0,
140 Length
* sizeof(WCHAR
));
141 if (EnvironmentBufferW
== NULL
)
148 RtlCopyMemory(EnvironmentBufferW
, lpModule
,
149 (lpModuleEnd
- lpModule
) * sizeof(WCHAR
));
150 Pos
+= lpModuleEnd
- lpModule
;
151 EnvironmentBufferW
[Pos
++] = L
';';
154 Pos
+= GetCurrentDirectoryW(Length
, EnvironmentBufferW
+ Pos
);
155 EnvironmentBufferW
[Pos
++] = L
';';
156 Pos
+= GetDllDirectoryW(Length
- Pos
, EnvironmentBufferW
+ Pos
);
157 EnvironmentBufferW
[Pos
++] = L
';';
158 Pos
+= GetSystemDirectoryW(EnvironmentBufferW
+ Pos
, Length
- Pos
);
159 EnvironmentBufferW
[Pos
++] = L
';';
160 Pos
+= GetWindowsDirectoryW(EnvironmentBufferW
+ Pos
, Length
- Pos
);
161 EnvironmentBufferW
[Pos
++] = L
';';
162 Pos
+= GetEnvironmentVariableW(L
"PATH", EnvironmentBufferW
+ Pos
, Length
- Pos
);
164 SetLastError(LastError
);
165 return EnvironmentBufferW
;
173 DisableThreadLibraryCalls(
174 IN HMODULE hLibModule
)
178 /* Disable thread library calls */
179 Status
= LdrDisableThreadCalloutsForDll((PVOID
)hLibModule
);
181 /* If it wasn't success - set last error and return failure */
182 if (!NT_SUCCESS(Status
))
184 BaseSetLastNTError(Status
);
198 LoadLibraryA(LPCSTR lpLibFileName
)
204 /* Treat twain_32.dll in a special way (what a surprise...) */
205 if (lpLibFileName
&& !_strcmpi(lpLibFileName
, "twain_32.dll"))
207 /* Allocate space for the buffer */
208 PathBuffer
= RtlAllocateHeap(RtlGetProcessHeap(), 0, MAX_PATH
);
211 /* Get windows dir in this buffer */
212 Len
= GetWindowsDirectoryA(PathBuffer
, MAX_PATH
- 13); /* 13 is sizeof of '\\twain_32.dll' */
213 if (Len
&& Len
< (MAX_PATH
- 13))
215 /* We successfully got windows directory. Concatenate twain_32.dll to it */
216 strncat(PathBuffer
, "\\twain_32.dll", 13);
218 /* And recursively call ourselves with a new string */
219 Result
= LoadLibraryA(PathBuffer
);
221 /* If it was successful - free memory and return result */
224 RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer
);
229 /* Free allocated buffer */
230 RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer
);
234 /* Call the Ex version of the API */
235 return LoadLibraryExA(lpLibFileName
, 0, 0);
243 LoadLibraryExA(LPCSTR lpLibFileName
,
247 PUNICODE_STRING FileNameW
;
249 /* Convert file name to unicode */
250 if (!(FileNameW
= Basep8BitStringToStaticUnicodeString(lpLibFileName
)))
253 /* And call W version of the API */
254 return LoadLibraryExW(FileNameW
->Buffer
, hFile
, dwFlags
);
262 LoadLibraryW(LPCWSTR lpLibFileName
)
264 /* Call Ex version of the API */
265 return LoadLibraryExW (lpLibFileName
, 0, 0);
271 BasepLoadLibraryAsDatafile(PWSTR Path
, LPCWSTR Name
, HMODULE
*hModule
)
273 WCHAR FilenameW
[MAX_PATH
];
274 HANDLE hFile
= INVALID_HANDLE_VALUE
;
277 PVOID lpBaseAddress
= NULL
;
279 //PUNICODE_STRING OriginalName;
280 //UNICODE_STRING dotDLL = RTL_CONSTANT_STRING(L".DLL");
282 /* Zero out handle value */
285 DPRINT("BasepLoadLibraryAsDatafile(%S %S %p)\n", Path
, Name
, hModule
);
287 /*Status = RtlDosApplyFileIsolationRedirection_Ustr(TRUE,
297 /* Try to search for it */
298 if (!SearchPathW(Path
,
301 sizeof(FilenameW
) / sizeof(FilenameW
[0]),
305 /* Return last status value directly */
306 return NtCurrentTeb()->LastStatusValue
;
309 /* Open this file we found */
310 hFile
= CreateFileW(FilenameW
,
312 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
318 /* If opening failed - return last status value */
319 if (hFile
== INVALID_HANDLE_VALUE
) return NtCurrentTeb()->LastStatusValue
;
321 /* Create file mapping */
322 hMapping
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
, 0, 0, NULL
);
324 /* Close the file handle */
327 /* If creating file mapping failed - return last status value */
328 if (!hMapping
) return NtCurrentTeb()->LastStatusValue
;
330 /* Map view of section */
331 Status
= NtMapViewOfSection(hMapping
,
342 /* Close handle to the section */
343 CloseHandle(hMapping
);
345 /* If mapping view of section failed - return last status value */
346 if (!NT_SUCCESS(Status
)) return NtCurrentTeb()->LastStatusValue
;
348 /* Make sure it's a valid PE file */
349 if (!RtlImageNtHeader(lpBaseAddress
))
351 /* Unmap the view and return failure status */
352 UnmapViewOfFile(lpBaseAddress
);
353 return STATUS_INVALID_IMAGE_FORMAT
;
356 /* Set low bit of handle to indicate datafile module */
357 *hModule
= (HMODULE
)((ULONG_PTR
)lpBaseAddress
| 1);
359 /* Load alternate resource module */
360 //LdrLoadAlternateResourceModule(*hModule, FilenameW);
362 return STATUS_SUCCESS
;
370 LoadLibraryExW(LPCWSTR lpLibFileName
,
374 UNICODE_STRING DllName
;
378 ULONG DllCharacteristics
= 0;
379 BOOL FreeString
= FALSE
;
381 /* Check for any flags LdrLoadDll might be interested in */
382 if (dwFlags
& DONT_RESOLVE_DLL_REFERENCES
)
384 /* Tell LDR to treat it as an EXE */
385 DllCharacteristics
= IMAGE_FILE_EXECUTABLE_IMAGE
;
388 /* Build up a unicode dll name from null-terminated string */
389 RtlInitUnicodeString(&DllName
, (LPWSTR
)lpLibFileName
);
391 /* Lazy-initialize BasepExeLdrEntry */
392 if (!BasepExeLdrEntry
)
393 LdrEnumerateLoadedModules(0, BasepLocateExeLdrEntry
, NtCurrentPeb()->ImageBaseAddress
);
395 /* Check if that module is our exe*/
396 if (BasepExeLdrEntry
&& !(dwFlags
& LOAD_LIBRARY_AS_DATAFILE
) &&
397 DllName
.Length
== BasepExeLdrEntry
->FullDllName
.Length
)
399 /* Lengths match and it's not a datafile, so perform name comparison */
400 if (RtlEqualUnicodeString(&DllName
, &BasepExeLdrEntry
->FullDllName
, TRUE
))
403 return BasepExeLdrEntry
->DllBase
;
407 /* Check for trailing spaces and remove them if necessary */
408 if (DllName
.Buffer
[DllName
.Length
/sizeof(WCHAR
) - 1] == L
' ')
410 RtlCreateUnicodeString(&DllName
, (LPWSTR
)lpLibFileName
);
411 while (DllName
.Length
> sizeof(WCHAR
) &&
412 DllName
.Buffer
[DllName
.Length
/sizeof(WCHAR
) - 1] == L
' ')
414 DllName
.Length
-= sizeof(WCHAR
);
416 DllName
.Buffer
[DllName
.Length
/sizeof(WCHAR
)] = UNICODE_NULL
;
420 /* Compute the load path */
421 SearchPath
= BasepGetDllPath((dwFlags
& LOAD_WITH_ALTERED_SEARCH_PATH
) ? (LPWSTR
)lpLibFileName
: NULL
,
426 /* Getting DLL path failed, so set last error, free mem and return */
427 BaseSetLastNTError(STATUS_NO_MEMORY
);
428 if (FreeString
) RtlFreeUnicodeString(&DllName
);
434 if (dwFlags
& LOAD_LIBRARY_AS_DATAFILE
)
436 /* If the image is loaded as a datafile, try to get its handle */
437 Status
= LdrGetDllHandle(SearchPath
, NULL
, &DllName
, (PVOID
*)&hInst
);
438 if (!NT_SUCCESS(Status
))
440 /* It's not loaded yet - so load it up */
441 Status
= BasepLoadLibraryAsDatafile(SearchPath
, DllName
.Buffer
, &hInst
);
442 _SEH2_YIELD(goto done
;)
446 /* Call the API Properly */
447 Status
= LdrLoadDll(SearchPath
,
452 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
454 Status
= _SEH2_GetExceptionCode();
459 /* Free SearchPath buffer */
460 RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath
);
462 /* Free DllName string if it was dynamically allocated */
463 if (FreeString
) RtlFreeUnicodeString(&DllName
);
465 /* Set last error in failure case */
466 if (!NT_SUCCESS(Status
))
468 BaseSetLastNTError(Status
);
472 /* Return loaded module handle */
482 GetProcAddress(HMODULE hModule
, LPCSTR lpProcName
)
484 ANSI_STRING ProcedureName
, *ProcNamePtr
= NULL
;
485 FARPROC fnExp
= NULL
;
490 if (HIWORD(lpProcName
) != 0)
492 /* Look up by name */
493 RtlInitAnsiString(&ProcedureName
, (LPSTR
)lpProcName
);
494 ProcNamePtr
= &ProcedureName
;
498 /* Look up by ordinal */
499 Ordinal
= (ULONG
)lpProcName
;
502 /* Map provided handle */
503 hMapped
= BasepMapModuleHandle(hModule
, FALSE
);
505 /* Get the proc address */
506 Status
= LdrGetProcedureAddress(hMapped
,
511 if (!NT_SUCCESS(Status
))
513 BaseSetLastNTError(Status
);
517 /* Check for a special case when returned pointer is
518 the same as iamge's base address */
519 if (fnExp
== hMapped
)
521 /* Set correct error code */
522 if (HIWORD(lpProcName
) != 0)
523 BaseSetLastNTError(STATUS_ENTRYPOINT_NOT_FOUND
);
525 BaseSetLastNTError(STATUS_ORDINAL_NOT_FOUND
);
530 /* All good, return procedure pointer */
538 BOOL WINAPI
FreeLibrary(HINSTANCE hLibModule
)
541 PIMAGE_NT_HEADERS NtHeaders
;
543 if (LDR_IS_DATAFILE(hLibModule
))
545 // FIXME: This SEH should go inside RtlImageNtHeader instead
548 /* This is a LOAD_LIBRARY_AS_DATAFILE module, check if it's a valid one */
549 NtHeaders
= RtlImageNtHeader((PVOID
)((ULONG_PTR
)hLibModule
& ~1));
551 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
559 Status
= NtUnmapViewOfSection(NtCurrentProcess(), (PVOID
)((ULONG_PTR
)hLibModule
& ~1));
561 /* Unload alternate resource module */
562 LdrUnloadAlternateResourceModule(hLibModule
);
565 Status
= STATUS_INVALID_IMAGE_FORMAT
;
570 Status
= LdrUnloadDll((PVOID
)hLibModule
);
573 /* Check what kind of status we got */
574 if (!NT_SUCCESS(Status
))
577 BaseSetLastNTError(Status
);
593 FreeLibraryAndExitThread(HMODULE hLibModule
,
598 if (LDR_IS_DATAFILE(hLibModule
))
600 /* This is a LOAD_LIBRARY_AS_DATAFILE module */
601 if (RtlImageNtHeader((PVOID
)((ULONG_PTR
)hLibModule
& ~1)))
604 Status
= NtUnmapViewOfSection(NtCurrentProcess(), (PVOID
)((ULONG_PTR
)hLibModule
& ~1));
606 /* Unload alternate resource module */
607 LdrUnloadAlternateResourceModule(hLibModule
);
613 Status
= LdrUnloadDll((PVOID
)hLibModule
);
617 ExitThread(dwExitCode
);
626 GetModuleFileNameA(HINSTANCE hModule
,
630 UNICODE_STRING FilenameW
;
631 ANSI_STRING FilenameA
;
633 DWORD Length
= 0, LengthToCopy
;
635 /* Allocate a unicode buffer */
636 FilenameW
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), 0, nSize
* sizeof(WCHAR
));
637 if (!FilenameW
.Buffer
)
639 BaseSetLastNTError(STATUS_NO_MEMORY
);
643 /* Call unicode API */
644 FilenameW
.Length
= GetModuleFileNameW(hModule
, FilenameW
.Buffer
, nSize
) * sizeof(WCHAR
);
645 FilenameW
.MaximumLength
= FilenameW
.Length
+ sizeof(WCHAR
);
647 if (FilenameW
.Length
)
649 /* Convert to ansi string */
650 Status
= BasepUnicodeStringTo8BitString(&FilenameA
, &FilenameW
, TRUE
);
651 if (!NT_SUCCESS(Status
))
653 /* Set last error, free string and retun failure */
654 BaseSetLastNTError(Status
);
655 RtlFreeUnicodeString(&FilenameW
);
659 /* Calculate size to copy */
660 Length
= min(nSize
, FilenameA
.Length
);
662 /* Include terminating zero */
664 LengthToCopy
= Length
+ 1;
666 LengthToCopy
= nSize
;
668 /* Now copy back to the caller amount he asked */
669 RtlMoveMemory(lpFilename
, FilenameA
.Buffer
, LengthToCopy
);
671 /* Free ansi filename */
672 RtlFreeAnsiString(&FilenameA
);
675 /* Free unicode filename */
676 RtlFreeHeap(RtlGetProcessHeap(), 0, FilenameW
.Buffer
);
678 /* Return length copied */
687 GetModuleFileNameW(HINSTANCE hModule
,
691 PLIST_ENTRY ModuleListHead
, Entry
;
692 PLDR_DATA_TABLE_ENTRY Module
;
697 hModule
= BasepMapModuleHandle(hModule
, FALSE
);
699 /* Upscale nSize from chars to bytes */
700 nSize
*= sizeof(WCHAR
);
704 /* We don't use per-thread cur dir now */
705 //PRTL_PERTHREAD_CURDIR PerThreadCurdir = (PRTL_PERTHREAD_CURDIR)teb->NtTib.SubSystemTib;
707 Peb
= NtCurrentPeb ();
709 /* Acquire a loader lock */
710 LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, NULL
, &Cookie
);
712 /* Traverse the module list */
713 ModuleListHead
= &Peb
->Ldr
->InLoadOrderModuleList
;
714 Entry
= ModuleListHead
->Flink
;
715 while (Entry
!= ModuleListHead
)
717 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
719 /* Check if this is the requested module */
720 if (Module
->DllBase
== (PVOID
)hModule
)
722 /* Calculate size to copy */
723 Length
= min(nSize
, Module
->FullDllName
.MaximumLength
);
726 RtlMoveMemory(lpFilename
, Module
->FullDllName
.Buffer
, Length
);
728 /* Subtract a terminating zero */
729 if (Length
== Module
->FullDllName
.MaximumLength
)
730 Length
-= sizeof(WCHAR
);
732 /* Break out of the loop */
736 /* Advance to the next entry */
737 Entry
= Entry
->Flink
;
740 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
742 BaseSetLastNTError(_SEH2_GetExceptionCode());
746 /* Release the loader lock */
747 LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
749 return Length
/ sizeof(WCHAR
);
754 GetModuleHandleForUnicodeString(PUNICODE_STRING ModuleName
)
760 /* Try to get a handle with a magic value of 1 for DllPath */
761 Status
= LdrGetDllHandle((LPWSTR
)1, NULL
, ModuleName
, &Module
);
763 /* If that succeeded - we're done */
764 if (NT_SUCCESS(Status
)) return Module
;
766 /* If not, then the path should be computed */
767 DllPath
= BasepGetDllPath(NULL
, 0);
769 /* Call LdrGetHandle() again providing the computed DllPath
770 and wrapped into SEH */
773 Status
= LdrGetDllHandle(DllPath
, NULL
, ModuleName
, &Module
);
775 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
777 /* Fail with the SEH error */
778 Status
= _SEH2_GetExceptionCode();
782 /* Free the DllPath */
783 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
);
785 /* In case of error set last win32 error and return NULL */
786 if (!NT_SUCCESS(Status
))
788 DPRINT("Failure acquiring DLL module '%wZ' handle, Status 0x%08X\n", ModuleName
, Status
);
789 SetLastErrorByStatus(Status
);
794 return (HMODULE
)Module
;
799 BasepGetModuleHandleExW(BOOLEAN NoLock
, DWORD dwPublicFlags
, LPCWSTR lpwModuleName
, HMODULE
*phModule
)
802 NTSTATUS Status
= STATUS_SUCCESS
, Status2
;
804 UNICODE_STRING ModuleNameU
;
806 BOOLEAN Redirected
= FALSE
; // FIXME
808 /* Validate parameters */
809 dwValid
= BasepGetModuleHandleExParameterValidation(dwPublicFlags
, lpwModuleName
, phModule
);
810 ASSERT(dwValid
== BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_CONTINUE
);
812 /* Acquire lock if necessary */
815 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
816 if (!NT_SUCCESS(Status
))
819 SetLastErrorByStatus(Status
);
820 if (phModule
) *phModule
= 0;
825 if (!(dwPublicFlags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
))
827 /* Create a unicode string out of module name */
828 RtlInitUnicodeString(&ModuleNameU
, lpwModuleName
);
830 // FIXME: Do some redirected DLL stuff?
838 hModule
= GetModuleHandleForUnicodeString(&ModuleNameU
);
841 /* Last error is already set, so just return failure by setting status */
842 Status
= STATUS_DLL_NOT_FOUND
;
849 /* Perform Pc to file header to get module instance */
850 hModule
= (HMODULE
)RtlPcToFileHeader((PVOID
)lpwModuleName
,
853 /* Check if it succeeded */
856 /* Set "dll not found" status and quit */
857 Status
= STATUS_DLL_NOT_FOUND
;
862 /* Check if changing reference is not forbidden */
863 if (!(dwPublicFlags
& GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
))
865 /* Add reference to this DLL */
866 Status
= LdrAddRefDll((dwPublicFlags
& GET_MODULE_HANDLE_EX_FLAG_PIN
) ? LDR_PIN_MODULE
: 0,
870 /* Set last error in case of failure */
871 if (!NT_SUCCESS(Status
))
872 SetLastErrorByStatus(Status
);
875 /* Unlock loader lock if it was acquired */
878 Status2
= LdrUnlockLoaderLock(0, Cookie
);
879 ASSERT(NT_SUCCESS(Status2
));
882 /* Set the module handle to the caller */
883 if (phModule
) *phModule
= hModule
;
885 /* Return TRUE on success and FALSE otherwise */
886 return NT_SUCCESS(Status
);
894 GetModuleHandleA(LPCSTR lpModuleName
)
896 PUNICODE_STRING ModuleNameW
;
897 PTEB pTeb
= NtCurrentTeb();
899 /* Check if we have no name to convert */
901 return ((HMODULE
)pTeb
->ProcessEnvironmentBlock
->ImageBaseAddress
);
903 /* Convert module name to unicode */
904 ModuleNameW
= Basep8BitStringToStaticUnicodeString(lpModuleName
);
906 /* Call W version if conversion was successful */
908 return GetModuleHandleW(ModuleNameW
->Buffer
);
920 GetModuleHandleW(LPCWSTR lpModuleName
)
925 /* If current module is requested - return it right away */
927 return ((HMODULE
)NtCurrentPeb()->ImageBaseAddress
);
929 /* Use common helper routine */
930 Status
= BasepGetModuleHandleExW(TRUE
,
931 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
,
935 /* If it wasn't successful - return 0 */
936 if (!NT_SUCCESS(Status
)) hModule
= 0;
938 /* Return the handle */
948 GetModuleHandleExW(IN DWORD dwFlags
,
949 IN LPCWSTR lpwModuleName OPTIONAL
,
950 OUT HMODULE
* phModule
)
956 /* Validate parameters */
957 dwValid
= BasepGetModuleHandleExParameterValidation(dwFlags
, lpwModuleName
, phModule
);
959 /* If result is invalid parameter - return failure */
960 if (dwValid
== BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
) return FALSE
;
962 /* If result is 2, there is no need to do anything - return success. */
963 if (dwValid
== BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
) return TRUE
;
965 /* Use common helper routine */
966 Status
= BasepGetModuleHandleExW(FALSE
,
971 /* Return TRUE in case of success */
972 if (NT_SUCCESS(Status
)) Ret
= TRUE
;
982 GetModuleHandleExA(IN DWORD dwFlags
,
983 IN LPCSTR lpModuleName OPTIONAL
,
984 OUT HMODULE
* phModule
)
986 PUNICODE_STRING lpModuleNameW
;
991 /* Validate parameters */
992 dwValid
= BasepGetModuleHandleExParameterValidation(dwFlags
, (LPCWSTR
)lpModuleName
, phModule
);
994 /* If result is invalid parameter - return failure */
995 if (dwValid
== BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
) return FALSE
;
997 /* If result is 2, there is no need to do anything - return success. */
998 if (dwValid
== BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
) return TRUE
;
1000 /* Check if we don't need to convert the name */
1001 if (dwFlags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
)
1003 /* Call the extended version of the API without conversion */
1004 Status
= BasepGetModuleHandleExW(FALSE
,
1006 (LPCWSTR
)lpModuleName
,
1011 /* Convert module name to unicode */
1012 lpModuleNameW
= Basep8BitStringToStaticUnicodeString(lpModuleName
);
1014 /* Return FALSE if conversion failed */
1015 if (!lpModuleNameW
) return FALSE
;
1017 /* Call the extended version of the API */
1018 Status
= BasepGetModuleHandleExW(FALSE
,
1020 lpModuleNameW
->Buffer
,
1024 /* If result was successful - return true */
1025 if (NT_SUCCESS(Status
))
1038 LoadModule(LPCSTR lpModuleName
,
1039 LPVOID lpParameterBlock
)
1041 STARTUPINFOA StartupInfo
;
1042 PROCESS_INFORMATION ProcessInformation
;
1043 LOADPARMS32
*LoadParams
;
1044 char FileName
[MAX_PATH
];
1046 DWORD Length
, Error
;
1048 ANSI_STRING AnsiStr
;
1049 UNICODE_STRING UnicStr
;
1050 RTL_PATH_TYPE PathType
;
1053 LoadParams
= (LOADPARMS32
*)lpParameterBlock
;
1055 /* Check load parameters */
1056 if (LoadParams
->dwReserved
|| LoadParams
->wMagicValue
!= 2)
1058 /* Fail with invalid param error */
1059 BaseSetLastNTError(STATUS_INVALID_PARAMETER
);
1064 Length
= SearchPathA(NULL
, lpModuleName
, ".exe", MAX_PATH
, FileName
, NULL
);
1066 /* Check if path was found */
1067 if (Length
&& Length
< MAX_PATH
)
1069 /* Build StartupInfo */
1070 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
1072 StartupInfo
.cb
= sizeof(STARTUPINFOA
);
1073 StartupInfo
.dwFlags
= STARTF_USESHOWWINDOW
;
1074 StartupInfo
.wShowWindow
= LoadParams
->wCmdShow
;
1076 /* Allocate command line buffer */
1077 CommandLine
= RtlAllocateHeap(RtlGetProcessHeap(),
1079 (ULONG
)LoadParams
->lpCmdLine
[0] + Length
+ 2);
1081 /* Put module name there, then a space, and then copy provided command line,
1082 and null-terminate it */
1083 RtlCopyMemory(CommandLine
, FileName
, Length
);
1084 CommandLine
[Length
] = ' ';
1085 RtlCopyMemory(&CommandLine
[Length
+ 1], &LoadParams
->lpCmdLine
[1], (ULONG
)LoadParams
->lpCmdLine
[0]);
1086 CommandLine
[Length
+ 1 + (ULONG
)LoadParams
->lpCmdLine
[0]] = 0;
1088 /* Create the process */
1089 ProcessStatus
= CreateProcessA(FileName
,
1095 LoadParams
->lpEnvAddress
,
1098 &ProcessInformation
);
1100 /* Free the command line buffer */
1101 RtlFreeHeap(RtlGetProcessHeap(), 0, CommandLine
);
1105 /* Creating process failed, return right error code */
1106 Error
= GetLastError();
1109 case ERROR_BAD_EXE_FORMAT
:
1110 return ERROR_BAD_FORMAT
;
1112 case ERROR_FILE_NOT_FOUND
:
1113 case ERROR_PATH_NOT_FOUND
:
1117 /* Return 0 otherwise */
1121 /* Wait up to 30 seconds for the process to become idle */
1122 if (lpfnGlobalRegisterWaitForInputIdle
)
1124 lpfnGlobalRegisterWaitForInputIdle(ProcessInformation
.hProcess
, 30000);
1128 NtClose(ProcessInformation
.hThread
);
1129 NtClose(ProcessInformation
.hProcess
);
1131 /* Return magic success value (33) */
1135 /* The path was not found, create an ansi string from
1136 the module name and convert it to unicode */
1137 RtlInitAnsiString(&AnsiStr
, lpModuleName
);
1138 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&UnicStr
,&AnsiStr
,TRUE
)))
1139 return ERROR_FILE_NOT_FOUND
;
1141 /* Determine path type */
1142 PathType
= RtlDetermineDosPathNameType_U(UnicStr
.Buffer
);
1144 /* Free the unicode module name */
1145 RtlFreeUnicodeString(&UnicStr
);
1147 /* If it's a relative path, return file not found */
1148 if (PathType
== RtlPathTypeRelative
)
1149 return ERROR_FILE_NOT_FOUND
;
1151 /* If not, try to open it */
1152 Handle
= CreateFile(lpModuleName
,
1154 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1157 FILE_ATTRIBUTE_NORMAL
,
1160 if (Handle
!= INVALID_HANDLE_VALUE
)
1162 /* Opening file succeeded for some reason, close the handle and return file not found anyway */
1163 CloseHandle(Handle
);
1164 return ERROR_FILE_NOT_FOUND
;
1167 /* Return last error which CreateFile set during an attempt to open it */
1168 return GetLastError();