ReactOS  0.4.12-dev-90-g2e2e63e
loader.c File Reference
#include <k32.h>
#include <debug.h>
Include dependency graph for loader.c:

Go to the source code of this file.

Macros

#define NDEBUG
 

Functions

NTSTATUS WINAPI BasepInitializeTermsrvFpns (VOID)
 
DWORD WINAPI BasepGetModuleHandleExParameterValidation (DWORD dwFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
 
PVOID WINAPI BasepMapModuleHandle (HMODULE hModule, BOOLEAN AsDataFile)
 
BOOL WINAPI DisableThreadLibraryCalls (IN HMODULE hLibModule)
 
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryA (LPCSTR lpLibFileName)
 
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA (LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
 
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryW (LPCWSTR lpLibFileName)
 
static NTSTATUS BasepLoadLibraryAsDatafile (PWSTR Path, LPCWSTR Name, HMODULE *hModule)
 
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW (LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
 
FARPROC WINAPI GetProcAddress (HMODULE hModule, LPCSTR lpProcName)
 
BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary (HINSTANCE hLibModule)
 
VOID WINAPI FreeLibraryAndExitThread (HMODULE hLibModule, DWORD dwExitCode)
 
DWORD WINAPI GetModuleFileNameA (HINSTANCE hModule, LPSTR lpFilename, DWORD nSize)
 
DWORD WINAPI GetModuleFileNameW (HINSTANCE hModule, LPWSTR lpFilename, DWORD nSize)
 
HMODULE WINAPI GetModuleHandleForUnicodeString (PUNICODE_STRING ModuleName)
 
BOOLEAN WINAPI BasepGetModuleHandleExW (BOOLEAN NoLock, DWORD dwPublicFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
 
HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA (LPCSTR lpModuleName)
 
HMODULE WINAPI GetModuleHandleW (LPCWSTR lpModuleName)
 
BOOL WINAPI GetModuleHandleExW (IN DWORD dwFlags, IN LPCWSTR lpwModuleName OPTIONAL, OUT HMODULE *phModule)
 
BOOL WINAPI GetModuleHandleExA (IN DWORD dwFlags, IN LPCSTR lpModuleName OPTIONAL, OUT HMODULE *phModule)
 
DWORD WINAPI LoadModule (LPCSTR lpModuleName, LPVOID lpParameterBlock)
 
FARPROC WINAPI DelayLoadFailureHook (LPCSTR pszDllName, LPCSTR pszProcName)
 
BOOL WINAPI UTRegister (HMODULE hModule, LPSTR lpsz16BITDLL, LPSTR lpszInitName, LPSTR lpszProcName, FARPROC *ppfn32Thunk, FARPROC pfnUT32CallBack, LPVOID lpBuff)
 
VOID WINAPI UTUnRegister (HMODULE hModule)
 
BOOL WINAPI BaseQueryModuleData (IN LPSTR ModuleName, IN LPSTR Unknown, IN PVOID Unknown2, IN PVOID Unknown3, IN PVOID Unknown4)
 
NTSTATUS WINAPI BaseProcessInitPostImport (VOID)
 

Macro Definition Documentation

◆ NDEBUG

#define NDEBUG

Definition at line 11 of file loader.c.

Function Documentation

◆ BasepGetModuleHandleExParameterValidation()

DWORD WINAPI BasepGetModuleHandleExParameterValidation ( DWORD  dwFlags,
LPCWSTR  lpwModuleName,
HMODULE phModule 
)

Definition at line 26 of file loader.c.

Referenced by BasepGetModuleHandleExW(), GetModuleHandleExA(), and GetModuleHandleExW().

29 {
30  /* Set phModule to 0 if it's not a NULL pointer */
31  if (phModule) *phModule = 0;
32 
33  /* Check for invalid flags combination */
34  if (dwFlags & ~(GET_MODULE_HANDLE_EX_FLAG_PIN |
35  GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
36  GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS) ||
37  ((dwFlags & GET_MODULE_HANDLE_EX_FLAG_PIN) &&
38  (dwFlags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT)) ||
39  (!lpwModuleName && (dwFlags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
40  )
41  {
44  }
45 
46  /* Check 2nd parameter */
47  if (!phModule)
48  {
51  }
52 
53  /* Return what we have according to the module name */
54  if (lpwModuleName)
55  {
57  }
58 
59  /* No name given, so put ImageBaseAddress there */
60  *phModule = (HMODULE)NtCurrentPeb()->ImageBaseAddress;
61 
63 }
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
Definition: kernel32.h:105
#define STATUS_INVALID_PARAMETER_2
Definition: ntstatus.h:462
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
_In_ PCCERT_CONTEXT _In_ DWORD dwFlags
Definition: wincrypt.h:1175
#define STATUS_INVALID_PARAMETER_1
Definition: ntstatus.h:461
#define NtCurrentPeb()
Definition: FLS.c:19
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
Definition: kernel32.h:106
HANDLE HMODULE
Definition: typedefs.h:75
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_CONTINUE
Definition: kernel32.h:107

◆ BasepGetModuleHandleExW()

BOOLEAN WINAPI BasepGetModuleHandleExW ( BOOLEAN  NoLock,
DWORD  dwPublicFlags,
LPCWSTR  lpwModuleName,
HMODULE phModule 
)

Definition at line 723 of file loader.c.

Referenced by GetModuleHandleExA(), GetModuleHandleExW(), and GetModuleHandleW().

724 {
726  NTSTATUS Status = STATUS_SUCCESS, Status2;
727  HANDLE hModule = NULL;
728  UNICODE_STRING ModuleNameU;
729  DWORD dwValid;
730  BOOLEAN Redirected = FALSE; // FIXME
731 
732  /* Validate parameters */
733  dwValid = BasepGetModuleHandleExParameterValidation(dwPublicFlags, lpwModuleName, phModule);
735 
736  /* Acquire lock if necessary */
737  if (!NoLock)
738  {
739  Status = LdrLockLoaderLock(0, NULL, &Cookie);
740  if (!NT_SUCCESS(Status))
741  {
742  /* Fail */
743  BaseSetLastNTError(Status);
744  if (phModule) *phModule = NULL;
745  return NT_SUCCESS(Status);
746  }
747  }
748 
749  if (!(dwPublicFlags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
750  {
751  /* Create a unicode string out of module name */
752  RtlInitUnicodeString(&ModuleNameU, lpwModuleName);
753 
754  // FIXME: Do some redirected DLL stuff?
755  if (Redirected)
756  {
758  }
759 
760  if (!hModule)
761  {
762  hModule = GetModuleHandleForUnicodeString(&ModuleNameU);
763  if (!hModule)
764  {
765  /* Last error is already set, so just return failure by setting status */
766  Status = STATUS_DLL_NOT_FOUND;
767  goto quickie;
768  }
769  }
770  }
771  else
772  {
773  /* Perform Pc to file header to get module instance */
774  hModule = (HMODULE)RtlPcToFileHeader((PVOID)lpwModuleName,
775  (PVOID*)&hModule);
776 
777  /* Check if it succeeded */
778  if (!hModule)
779  {
780  /* Set "dll not found" status and quit */
781  Status = STATUS_DLL_NOT_FOUND;
782  goto quickie;
783  }
784  }
785 
786  /* Check if changing reference is not forbidden */
787  if (!(dwPublicFlags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
788  {
789  /* Add reference to this DLL */
790  Status = LdrAddRefDll((dwPublicFlags & GET_MODULE_HANDLE_EX_FLAG_PIN) ? LDR_ADDREF_DLL_PIN : 0,
791  hModule);
792  }
793 
794 quickie:
795  /* Set last error in case of failure */
796  if (!NT_SUCCESS(Status))
797  BaseSetLastNTError(Status);
798 
799  /* Unlock loader lock if it was acquired */
800  if (!NoLock)
801  {
802  Status2 = LdrUnlockLoaderLock(0, Cookie);
803  ASSERT(NT_SUCCESS(Status2));
804  }
805 
806  /* Set the module handle to the caller */
807  if (phModule) *phModule = hModule;
808 
809  /* Return TRUE on success and FALSE otherwise */
810  return NT_SUCCESS(Status);
811 }
NTSTATUS NTAPI LdrUnlockLoaderLock(IN ULONG Flags, IN ULONG Cookie OPTIONAL)
Definition: ldrapi.c:101
NTSTATUS NTAPI LdrAddRefDll(IN ULONG Flags, IN PVOID BaseAddress)
Definition: ldrapi.c:1237
LONG NTSTATUS
Definition: precomp.h:26
NTSTATUS NTAPI LdrLockLoaderLock(IN ULONG Flags, OUT PULONG Disposition OPTIONAL, OUT PULONG_PTR Cookie OPTIONAL)
Definition: ldrapi.c:173
PVOID NTAPI RtlPcToFileHeader(IN PVOID PcValue, PVOID *BaseOfImage)
Definition: libsupp.c:616
uint32_t ULONG_PTR
Definition: typedefs.h:63
HMODULE WINAPI GetModuleHandleForUnicodeString(PUNICODE_STRING ModuleName)
Definition: loader.c:674
unsigned char BOOLEAN
smooth NULL
Definition: ftsmooth.c:416
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
_In_opt_ PVOID _Out_ PLARGE_INTEGER Cookie
Definition: cmfuncs.h:13
unsigned long DWORD
Definition: ntddk_ex.h:95
ASSERT((InvokeOnSuccess||InvokeOnError||InvokeOnCancel) ?(CompletionRoutine !=NULL) :TRUE)
Status
Definition: gdiplustypes.h:24
DWORD WINAPI BasepGetModuleHandleExParameterValidation(DWORD dwFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:26
#define STATUS_DLL_NOT_FOUND
Definition: ntstatus.h:531
HANDLE HMODULE
Definition: typedefs.h:75
#define LDR_ADDREF_DLL_PIN
Definition: ldrtypes.h:69
NTSYSAPI VOID NTAPI RtlInitUnicodeString(PUNICODE_STRING DestinationString, PCWSTR SourceString)
#define UNIMPLEMENTED
Definition: debug.h:114
return STATUS_SUCCESS
Definition: btrfs.c:2725
HMODULE hModule
Definition: animate.c:44
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_CONTINUE
Definition: kernel32.h:107

◆ BasepInitializeTermsrvFpns()

NTSTATUS WINAPI BasepInitializeTermsrvFpns ( VOID  )

Definition at line 18 of file loader.c.

Referenced by BaseProcessInitPostImport().

19 {
22 }
#define STATUS_NOT_IMPLEMENTED
Definition: ntstatus.h:225
#define UNIMPLEMENTED
Definition: debug.h:114

◆ BasepLoadLibraryAsDatafile()

static NTSTATUS BasepLoadLibraryAsDatafile ( PWSTR  Path,
LPCWSTR  Name,
HMODULE hModule 
)
static

Definition at line 186 of file loader.c.

Referenced by LoadLibraryExW().

187 {
188  WCHAR FilenameW[MAX_PATH];
190  HANDLE hMapping;
192  PVOID lpBaseAddress = NULL;
193  SIZE_T ViewSize = 0;
194  //PUNICODE_STRING OriginalName;
195  //UNICODE_STRING dotDLL = RTL_CONSTANT_STRING(L".DLL");
196 
197  /* Zero out handle value */
198  *hModule = 0;
199 
200  DPRINT("BasepLoadLibraryAsDatafile(%S %S %p)\n", Path, Name, hModule);
201 
202  /*Status = RtlDosApplyFileIsolationRedirection_Ustr(TRUE,
203  Name,
204  &dotDLL,
205  RedirName,
206  RedirName2,
207  &OriginalName2,
208  NULL,
209  NULL,
210  NULL);*/
211 
212  /* Try to search for it */
213  if (!SearchPathW(Path,
214  Name,
215  L".DLL",
216  sizeof(FilenameW) / sizeof(FilenameW[0]),
217  FilenameW,
218  NULL))
219  {
220  /* Return last status value directly */
221  return NtCurrentTeb()->LastStatusValue;
222  }
223 
224  /* Open this file we found */
225  hFile = CreateFileW(FilenameW,
226  GENERIC_READ,
228  NULL,
230  0,
231  0);
232 
233  /* If opening failed - return last status value */
234  if (hFile == INVALID_HANDLE_VALUE) return NtCurrentTeb()->LastStatusValue;
235 
236  /* Create file mapping */
237  hMapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
238 
239  /* Close the file handle */
240  CloseHandle(hFile);
241 
242  /* If creating file mapping failed - return last status value */
243  if (!hMapping) return NtCurrentTeb()->LastStatusValue;
244 
245  /* Map view of section */
246  Status = NtMapViewOfSection(hMapping,
248  &lpBaseAddress,
249  0,
250  0,
251  0,
252  &ViewSize,
253  ViewShare,
254  0,
255  PAGE_READONLY);
256 
257  /* Close handle to the section */
258  CloseHandle(hMapping);
259 
260  /* If mapping view of section failed - return last status value */
261  if (!NT_SUCCESS(Status)) return NtCurrentTeb()->LastStatusValue;
262 
263  /* Make sure it's a valid PE file */
264  if (!RtlImageNtHeader(lpBaseAddress))
265  {
266  /* Unmap the view and return failure status */
267  UnmapViewOfFile(lpBaseAddress);
269  }
270 
271  /* Set low bit of handle to indicate datafile module */
272  *hModule = (HMODULE)((ULONG_PTR)lpBaseAddress | 1);
273 
274  /* Load alternate resource module */
275  //LdrLoadAlternateResourceModule(*hModule, FilenameW);
276 
277  return STATUS_SUCCESS;
278 }
#define CloseHandle
Definition: compat.h:398
__wchar_t WCHAR
Definition: xmlstorage.h:180
LONG NTSTATUS
Definition: precomp.h:26
#define INVALID_HANDLE_VALUE
Definition: compat.h:391
#define FILE_SHARE_READ
Definition: compat.h:125
uint32_t ULONG_PTR
Definition: typedefs.h:63
NTSTATUS NTAPI NtMapViewOfSection(IN HANDLE SectionHandle, IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress, IN ULONG_PTR ZeroBits, IN SIZE_T CommitSize, IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, IN OUT PSIZE_T ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Protect)
Definition: section.c:3553
smooth NULL
Definition: ftsmooth.c:416
void DPRINT(...)
Definition: polytest.cpp:61
#define OPEN_EXISTING
Definition: compat.h:426
#define NtCurrentProcess()
Definition: nt_native.h:1657
#define STATUS_INVALID_IMAGE_FORMAT
Definition: ntstatus.h:345
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
#define CreateFileMappingW(a, b, c, d, e, f)
Definition: compat.h:401
#define MAX_PATH
Definition: compat.h:26
#define FILE_SHARE_DELETE
Definition: nt_native.h:682
static const WCHAR L[]
Definition: oid.c:1087
#define GENERIC_READ
Definition: compat.h:124
_In_ HANDLE hFile
Definition: mswsock.h:90
DWORD WINAPI SearchPathW(IN LPCWSTR lpPath OPTIONAL, IN LPCWSTR lpFileName, IN LPCWSTR lpExtension OPTIONAL, IN DWORD nBufferLength, OUT LPWSTR lpBuffer, OUT LPWSTR *lpFilePart OPTIONAL)
Definition: path.c:1297
Status
Definition: gdiplustypes.h:24
ULONG_PTR SIZE_T
Definition: typedefs.h:78
PRTL_UNICODE_STRING_BUFFER Path
FORCEINLINE struct _TEB * NtCurrentTeb(VOID)
Definition: psfuncs.h:420
#define PAGE_READONLY
Definition: compat.h:127
#define RtlImageNtHeader
Definition: compat.h:457
#define CreateFileW
Definition: compat.h:400
HANDLE HMODULE
Definition: typedefs.h:75
_In_ HANDLE _Outptr_result_bytebuffer_ ViewSize PVOID _In_ ULONG_PTR _In_ SIZE_T _Inout_opt_ PLARGE_INTEGER _Inout_ PSIZE_T ViewSize
Definition: mmfuncs.h:404
return STATUS_SUCCESS
Definition: btrfs.c:2725
#define UnmapViewOfFile
Definition: compat.h:403

◆ BasepMapModuleHandle()

PVOID WINAPI BasepMapModuleHandle ( HMODULE  hModule,
BOOLEAN  AsDataFile 
)

Definition at line 67 of file loader.c.

Referenced by GetModuleFileNameW(), and GetProcAddress().

68 {
69  /* If no handle is provided - use current image base address */
70  if (!hModule) return NtCurrentPeb()->ImageBaseAddress;
71 
72  /* Check if it's a normal or a datafile one */
73  if (LDR_IS_DATAFILE(hModule) && !AsDataFile)
74  return NULL;
75 
76  /* It's a normal DLL, just return its handle */
77  return hModule;
78 }
#define LDR_IS_DATAFILE(handle)
Definition: ldrtypes.h:101
smooth NULL
Definition: ftsmooth.c:416
#define NtCurrentPeb()
Definition: FLS.c:19
HMODULE hModule
Definition: animate.c:44

◆ BaseProcessInitPostImport()

NTSTATUS WINAPI BaseProcessInitPostImport ( VOID  )

Definition at line 1141 of file loader.c.

1142 {
1143  DPRINT("Post-init called\n");
1144 
1145  /* Check if this is a terminal server */
1146  if (SharedUserData->SuiteMask & VER_SUITE_TERMINAL)
1147  {
1148  /* Initialize TS pointers */
1149  return BasepInitializeTermsrvFpns();
1150  }
1151 
1152  /* FIXME: Initialize TS pointers */
1153  return STATUS_SUCCESS;
1154 }
#define VER_SUITE_TERMINAL
NTSTATUS WINAPI BasepInitializeTermsrvFpns(VOID)
Definition: loader.c:18
void DPRINT(...)
Definition: polytest.cpp:61
#define SharedUserData
return STATUS_SUCCESS
Definition: btrfs.c:2725

◆ BaseQueryModuleData()

BOOL WINAPI BaseQueryModuleData ( IN LPSTR  ModuleName,
IN LPSTR  Unknown,
IN PVOID  Unknown2,
IN PVOID  Unknown3,
IN PVOID  Unknown4 
)

Definition at line 1121 of file loader.c.

1126 {
1127  DPRINT1("BaseQueryModuleData called: %s %s %p %p %p\n",
1128  ModuleName,
1129  Unknown,
1130  Unknown2,
1131  Unknown3,
1132  Unknown4);
1133  return FALSE;
1134 }
ACPI_BUFFER *RetBuffer ACPI_BUFFER *RetBuffer char ACPI_WALK_RESOURCE_CALLBACK void *Context ACPI_BUFFER *RetBuffer UINT16 ACPI_RESOURCE **ResourcePtr ACPI_GENERIC_ADDRESS *Reg UINT32 *ReturnValue UINT8 UINT8 *Slp_TypB ACPI_PHYSICAL_ADDRESS PhysicalAddress64 UINT32 UINT32 *TimeElapsed UINT32 ACPI_STATUS const char UINT32 const char UINT32 const char const char * ModuleName
Definition: acpixf.h:1269
IN PUNICODE_STRING IN POBJECT_ATTRIBUTES IN DWORD Unknown3
Definition: conport.c:35
PRTL_UNICODE_STRING_BUFFER PULONG PULONG Unknown4
#define DPRINT1
Definition: precomp.h:8

◆ DelayLoadFailureHook()

FARPROC WINAPI DelayLoadFailureHook ( LPCSTR  pszDllName,
LPCSTR  pszProcName 
)

Definition at line 1090 of file loader.c.

1091 {
1092  STUB;
1093  return NULL;
1094 }
smooth NULL
Definition: ftsmooth.c:416
#define STUB
Definition: kernel32.h:27

◆ DisableThreadLibraryCalls()

BOOL WINAPI DisableThreadLibraryCalls ( IN HMODULE  hLibModule)

Definition at line 85 of file loader.c.

Referenced by _CorDllMain(), DllMain(), if(), LpkDllInitialize(), STRMBASE_DllMain(), WIC_DllMain(), and wined3d_dll_init().

87 {
89 
90  /* Disable thread library calls */
92 
93  /* If it wasn't success - set last error and return failure */
94  if (!NT_SUCCESS(Status))
95  {
96  BaseSetLastNTError(Status);
97  return FALSE;
98  }
99 
100  /* Return success */
101  return TRUE;
102 }
HINSTANCE hLibModule
Definition: sfc.c:23
#define TRUE
Definition: types.h:120
LONG NTSTATUS
Definition: precomp.h:26
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
Status
Definition: gdiplustypes.h:24
NTSTATUS NTAPI LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress)
Definition: ldrapi.c:1187

◆ FreeLibrary()

BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary ( HINSTANCE  hLibModule)

Definition at line 458 of file loader.c.

Referenced by child_process(), dll_entry_point(), map_image_section(), test_filenames(), test_image_mapping(), test_import_resolution(), test_Loader(), test_ResolveDelayLoadedAPI(), test_section_access(), and wine_dlclose().

459 {
461  PIMAGE_NT_HEADERS NtHeaders;
462 
463  if (LDR_IS_DATAFILE(hLibModule))
464  {
465  // FIXME: This SEH should go inside RtlImageNtHeader instead
466  // See https://jira.reactos.org/browse/CORE-14857
467  _SEH2_TRY
468  {
469  /* This is a LOAD_LIBRARY_AS_DATAFILE module, check if it's a valid one */
470  NtHeaders = RtlImageNtHeader((PVOID)((ULONG_PTR)hLibModule & ~1));
471  }
473  {
474  NtHeaders = NULL;
475  } _SEH2_END
476 
477  if (NtHeaders)
478  {
479  /* Unmap view */
480  Status = NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)((ULONG_PTR)hLibModule & ~1));
481 
482  /* Unload alternate resource module */
484  }
485  else
487  }
488  else
489  {
490  /* Just unload it */
491  Status = LdrUnloadDll((PVOID)hLibModule);
492  }
493 
494  /* Check what kind of status we got */
495  if (!NT_SUCCESS(Status))
496  {
497  /* Set last error */
498  BaseSetLastNTError(Status);
499 
500  /* Return failure */
501  return FALSE;
502  }
503 
504  /* Return success */
505  return TRUE;
506 }
NTSTATUS NTAPI NtUnmapViewOfSection(IN HANDLE ProcessHandle, IN PVOID BaseAddress)
Definition: section.c:3781
#define TRUE
Definition: types.h:120
#define LDR_IS_DATAFILE(handle)
Definition: ldrtypes.h:101
LONG NTSTATUS
Definition: precomp.h:26
_SEH2_TRY
Definition: create.c:4250
uint32_t ULONG_PTR
Definition: typedefs.h:63
#define EXCEPTION_EXECUTE_HANDLER
Definition: excpt.h:85
smooth NULL
Definition: ftsmooth.c:416
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define NtCurrentProcess()
Definition: nt_native.h:1657
BOOLEAN NTAPI LdrUnloadAlternateResourceModule(IN PVOID BaseAddress)
Definition: ldrapi.c:1630
#define STATUS_INVALID_IMAGE_FORMAT
Definition: ntstatus.h:345
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
Status
Definition: gdiplustypes.h:24
NTSTATUS NTAPI LdrUnloadDll(IN PVOID BaseAddress)
Definition: ldrapi.c:1322
_SEH2_END
Definition: create.c:4424
#define RtlImageNtHeader
Definition: compat.h:457
#define _SEH2_EXCEPT(...)
Definition: pseh2_64.h:6

◆ FreeLibraryAndExitThread()

VOID WINAPI FreeLibraryAndExitThread ( HMODULE  hLibModule,
DWORD  dwExitCode 
)

Definition at line 514 of file loader.c.

Referenced by collect_connections_proc(), connection_collector(), ExitThreadApc(), GPNotificationThreadProc(), LookupThreadProc(), CSysTray::SysTrayThreadProc(), wined3d_cs_run(), and WsAsyncThread().

516 {
517 
518  if (LDR_IS_DATAFILE(hLibModule))
519  {
520  /* This is a LOAD_LIBRARY_AS_DATAFILE module */
521  if (RtlImageNtHeader((PVOID)((ULONG_PTR)hLibModule & ~1)))
522  {
523  /* Unmap view */
524  NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)((ULONG_PTR)hLibModule & ~1));
525 
526  /* Unload alternate resource module */
528  }
529  }
530  else
531  {
532  /* Just unload it */
533  LdrUnloadDll((PVOID)hLibModule);
534  }
535 
536  /* Exit thread */
537  ExitThread(dwExitCode);
538 }
NTSTATUS NTAPI NtUnmapViewOfSection(IN HANDLE ProcessHandle, IN PVOID BaseAddress)
Definition: section.c:3781
#define LDR_IS_DATAFILE(handle)
Definition: ldrtypes.h:101
uint32_t ULONG_PTR
Definition: typedefs.h:63
VOID WINAPI ExitThread(IN DWORD uExitCode)
Definition: thread.c:327
#define NtCurrentProcess()
Definition: nt_native.h:1657
BOOLEAN NTAPI LdrUnloadAlternateResourceModule(IN PVOID BaseAddress)
Definition: ldrapi.c:1630
NTSTATUS NTAPI LdrUnloadDll(IN PVOID BaseAddress)
Definition: ldrapi.c:1322
#define RtlImageNtHeader
Definition: compat.h:457

◆ GetModuleFileNameA()

DWORD WINAPI GetModuleFileNameA ( HINSTANCE  hModule,
LPSTR  lpFilename,
DWORD  nSize 
)

Definition at line 546 of file loader.c.

Referenced by __getmainargs(), _assert(), _module_name_from_addr(), AssertFail(), create_proc(), doChild(), FreeLibrary(), get_app_key(), GetWindowModuleFileNameA(), init_test(), InstallService(), MLLoadLibraryA(), rdp_send_logon_info(), register_current_module_typelib(), register_service(), register_service_exA(), run_child_process(), run_js_script(), setup_dsound_options(), START_TEST(), STRMBASE_DllGetClassObject(), test(), test_32bit_win(), test_ExitCode(), test_extra_block(), test_filenames(), test_GetMappedFileName(), test_GetModuleBaseName(), test_GetModuleFileNameEx(), test_GetSetConsoleInputExeName(), test_GetWindowModuleFileName(), test_IME(), test_info_size(), test_inheritance(), test_internet_features_registry(), test_load_save(), test_LoadLibraryEx_search_flags(), test_loadlibraryshim(), test_LocalizedNames(), test_QueryFullProcessImageNameA(), test_VerQueryValueA(), testGetModuleFileName(), testGetModuleFileName_Wrong(), TestGetModuleFileNameA(), and wined3d_dll_init().

549 {
550  UNICODE_STRING FilenameW;
551  ANSI_STRING FilenameA;
553  DWORD Length = 0, LengthToCopy;
554 
555  /* Allocate a unicode buffer */
556  FilenameW.Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, nSize * sizeof(WCHAR));
557  if (!FilenameW.Buffer)
558  {
560  return 0;
561  }
562 
563  /* Call unicode API */
564  FilenameW.Length = (USHORT)GetModuleFileNameW(hModule, FilenameW.Buffer, nSize) * sizeof(WCHAR);
565  FilenameW.MaximumLength = FilenameW.Length + sizeof(WCHAR);
566 
567  if (FilenameW.Length)
568  {
569  /* Convert to ansi string */
570  Status = BasepUnicodeStringTo8BitString(&FilenameA, &FilenameW, TRUE);
571  if (!NT_SUCCESS(Status))
572  {
573  /* Set last error, free string and return failure */
574  BaseSetLastNTError(Status);
575  RtlFreeUnicodeString(&FilenameW);
576  return 0;
577  }
578 
579  /* Calculate size to copy */
580  Length = min(nSize, FilenameA.Length);
581 
582  /* Include terminating zero */
583  if (nSize > Length)
584  LengthToCopy = Length + 1;
585  else
586  LengthToCopy = nSize;
587 
588  /* Now copy back to the caller amount he asked */
589  RtlMoveMemory(lpFilename, FilenameA.Buffer, LengthToCopy);
590 
591  /* Free ansi filename */
592  RtlFreeAnsiString(&FilenameA);
593  }
594 
595  /* Free unicode filename */
596  RtlFreeHeap(RtlGetProcessHeap(), 0, FilenameW.Buffer);
597 
598  /* Return length copied */
599  return Length;
600 }
DWORD WINAPI GetModuleFileNameW(HINSTANCE hModule, LPWSTR lpFilename, DWORD nSize)
Definition: loader.c:607
#define TRUE
Definition: types.h:120
USHORT MaximumLength
Definition: env_spec_w32.h:370
PRTL_CONVERT_STRINGA BasepUnicodeStringTo8BitString
Definition: utils.c:27
__wchar_t WCHAR
Definition: xmlstorage.h:180
*nSize LPSTR _Inout_ LPDWORD nSize
Definition: winbase.h:2024
LONG NTSTATUS
Definition: precomp.h:26
BOOLEAN NTAPI RtlFreeHeap(IN PVOID HeapHandle, IN ULONG Flags, IN PVOID HeapBase)
Definition: heap.c:603
#define WCHAR
Definition: msvc.h:43
#define RtlMoveMemory(Destination, Source, Length)
Definition: typedefs.h:263
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
PVOID NTAPI RtlAllocateHeap(IN PVOID HeapHandle, IN ULONG Flags, IN SIZE_T Size)
Definition: heap.c:585
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
NTSYSAPI VOID NTAPI RtlFreeAnsiString(PANSI_STRING AnsiString)
unsigned long DWORD
Definition: ntddk_ex.h:95
NTSYSAPI VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING UnicodeString)
_In_ ULONG _In_ ULONG _In_ ULONG Length
Definition: ntddpcm.h:101
Status
Definition: gdiplustypes.h:24
unsigned short USHORT
Definition: pedump.c:61
#define STATUS_NO_MEMORY
Definition: ntstatus.h:246
#define min(a, b)
Definition: monoChain.cc:55

◆ GetModuleFileNameW()

DWORD WINAPI GetModuleFileNameW ( HINSTANCE  hModule,
LPWSTR  lpFilename,
DWORD  nSize 
)

Definition at line 607 of file loader.c.

Referenced by __report_error(), __wgetmainargs(), _CorExeMain(), _CreateActCtxFromFile(), _CreateV5ActCtx(), _DoDLLInjection(), _RunRemoteTest(), AMovieDllRegisterServer2(), AtlLoadTypeLib(), ATL::AtlLoadTypeLib(), AtlUpdateRegistryFromResourceD(), CommandLineToArgvW(), ATL::CAtlModule::CommonInitRegistrar(), create_registrar(), CURSORICON_LoadImageW(), BtrfsVolPropSheet::DeviceDlgProc(), DllRegisterServer(), ExtractAssociatedIconW(), FILEDLG95_MRU_load_filename(), FILEDLG95_MRU_save_filename(), get_mmioFromProfile(), CConfiguration::GetConfigurationFromFile(), CNtObjectFolderExtractIcon::GetIconLocation(), CRegistryFolderExtractIcon::GetIconLocation(), CNetConUiObject::GetIconLocation(), GetModuleFileNameA(), BtrfsIconOverlay::GetOverlayInfo(), GetWindowModuleFileNameW(), Host_get_FullName(), Host_get_Path(), if(), init_paths(), InitLogs(), InstallEventSource(), IntSetWindowsHook(), BtrfsContextMenu::InvokeCommand(), load_process_feature(), load_typelib(), SEALED_::LoadTypeLibrary(), LPK_ApplyMirroring(), MLBuildResURLW(), MLLoadLibraryW(), NdrDllRegisterProxy(), BtrfsPropSheet::open_as_admin(), BtrfsBalance::PauseBalance(), ReallyFixupVTable(), register_clsid(), register_service(), register_service_exW(), RegisterComponent(), RegisterInShimCache(), BtrfsVolPropSheet::ResetStats(), ResProtocolInfo_ParseUrl(), RetrieveCurrentModuleNTDirectory(), RunApphelpCacheControlTests(), search_res_tlb(), set_firewall(), SetWinEventHook(), BtrfsVolPropSheet::ShowScrub(), ShowUsage(), START_TEST(), BtrfsBalance::StartBalance(), StartChild(), BtrfsBalance::StopBalance(), CSysTray::SysTrayThreadProc(), taskdialog_get_exe_name(), test_32bit_win(), Test_ApphelpCheckRunApp(), test_commandline2argv(), test_FakeDLL(), Test_GetMatchingExe(), Test_ImageSection(), test_Load(), test_NetFwAuthorizedApplication(), test_QueryFullProcessImageNameW(), test_WTSEnumerateProcessesW(), TestDllStartup(), testGetModuleFileName(), testGetModuleFileName_Wrong(), TestGetModuleFileNameW(), TestPrivMoveFileIdentityW(), TestRedirection(), TestStaticDestruct(), User32CallEventProcFromKernel(), validate_SDBQUERYRESULT_size(), and write_predefined_strings().

610 {
612  PLDR_DATA_TABLE_ENTRY Module;
613  ULONG Length = 0;
615  PPEB Peb;
616 
617  hModule = BasepMapModuleHandle(hModule, FALSE);
618 
619  /* Upscale nSize from chars to bytes */
620  nSize *= sizeof(WCHAR);
621 
622  _SEH2_TRY
623  {
624  /* We don't use per-thread cur dir now */
625  //PRTL_PERTHREAD_CURDIR PerThreadCurdir = (PRTL_PERTHREAD_CURDIR)teb->NtTib.SubSystemTib;
626 
627  Peb = NtCurrentPeb ();
628 
629  /* Acquire a loader lock */
631 
632  /* Traverse the module list */
633  ModuleListHead = &Peb->Ldr->InLoadOrderModuleList;
634  Entry = ModuleListHead->Flink;
635  while (Entry != ModuleListHead)
636  {
637  Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
638 
639  /* Check if this is the requested module */
640  if (Module->DllBase == (PVOID)hModule)
641  {
642  /* Calculate size to copy */
643  Length = min(nSize, Module->FullDllName.MaximumLength);
644 
645  /* Copy contents */
646  RtlMoveMemory(lpFilename, Module->FullDllName.Buffer, Length);
647 
648  /* Subtract a terminating zero */
649  if (Length == Module->FullDllName.MaximumLength)
650  Length -= sizeof(WCHAR);
651 
652  /* Break out of the loop */
653  break;
654  }
655 
656  /* Advance to the next entry */
657  Entry = Entry->Flink;
658  }
659  }
661  {
663  Length = 0;
664  } _SEH2_END
665 
666  /* Release the loader lock */
668 
669  return Length / sizeof(WCHAR);
670 }
#define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
Definition: ldrtypes.h:74
PPEB Peb
Definition: dllmain.c:27
struct _Entry Entry
Definition: kefuncs.h:640
NTSTATUS NTAPI LdrUnlockLoaderLock(IN ULONG Flags, IN ULONG Cookie OPTIONAL)
Definition: ldrapi.c:101
USHORT MaximumLength
Definition: env_spec_w32.h:370
LIST_ENTRY InLoadOrderModuleList
Definition: ldrtypes.h:118
*nSize LPSTR _Inout_ LPDWORD nSize
Definition: winbase.h:2024
NTSTATUS NTAPI LdrLockLoaderLock(IN ULONG Flags, OUT PULONG Disposition OPTIONAL, OUT PULONG_PTR Cookie OPTIONAL)
Definition: ldrapi.c:173
#define WCHAR
Definition: msvc.h:43
#define RtlMoveMemory(Destination, Source, Length)
Definition: typedefs.h:263
_SEH2_TRY
Definition: create.c:4250
uint32_t ULONG_PTR
Definition: typedefs.h:63
PVOID DllBase
Definition: btrfs_drv.h:1805
#define EXCEPTION_EXECUTE_HANDLER
Definition: excpt.h:85
smooth NULL
Definition: ftsmooth.c:416
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
PFLT_MESSAGE_WAITER_QUEUE CONTAINING_RECORD(Csq, DEVICE_EXTENSION, IrpQueue)) -> WaiterQ.mLock) _IRQL_raises_(DISPATCH_LEVEL) VOID NTAPI FltpAcquireMessageWaiterLock(_In_ PIO_CSQ Csq, _Out_ PKIRQL Irql)
Definition: Messaging.c:560
struct _LIST_ENTRY * Flink
Definition: typedefs.h:119
_In_opt_ PVOID _Out_ PLARGE_INTEGER Cookie
Definition: cmfuncs.h:13
_In_ ULONG _In_ ULONG _In_ ULONG Length
Definition: ntddpcm.h:101
Definition: btrfs_drv.h:1801
Definition: typedefs.h:117
_SEH2_END
Definition: create.c:4424
#define NtCurrentPeb()
Definition: FLS.c:19
PPEB_LDR_DATA Ldr
Definition: btrfs_drv.h:1837
UNICODE_STRING FullDllName
Definition: btrfs_drv.h:1807
#define min(a, b)
Definition: monoChain.cc:55
unsigned int ULONG
Definition: retypes.h:1
#define _SEH2_EXCEPT(...)
Definition: pseh2_64.h:6
#define _SEH2_GetExceptionCode()
Definition: pseh2_64.h:12
LIST_ENTRY * ModuleListHead
Definition: kdpacket.c:23
PVOID WINAPI BasepMapModuleHandle(HMODULE hModule, BOOLEAN AsDataFile)
Definition: loader.c:67

◆ GetModuleHandleA()

HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA ( LPCSTR  lpModuleName)

Definition at line 819 of file loader.c.

Referenced by __mingw_get_msvcrt_handle(), _configure_devices(), add_128x15_bitmap(), build_toolbar(), check_address(), check_dialog_style(), check_z_order_debug(), child_process(), cleanup(), compat_catpath(), create_animate(), create_async_message_window(), create_custom_parent_window(), create_dde_server(), create_dde_window(), create_edit_control(), create_listview_control(), create_main_test_wnd(), create_monthcal_control(), create_pager_control(), create_parent(), create_parent_window(), create_progress(), create_rebar_control(), create_testfontfile(), create_trackbar(), create_trackbar2(), create_treeview_control(), create_updown_control(), createMainWnd(), createParentWindow(), CreateRemoteThread(), CreateTestWindow(), destroy_dde_window(), detect_locale(), DliHook(), dll_entry_point(), DllMain(), DllUnregisterServer(), do_child(), do_parent(), doChild(), drop_window_therad(), dsm_RegisterWindowClasses(), dump_system_info(), EDIT_WM_ContextMenu(), empty_dlg_proc2(), EnumResourceLanguagesA(), EnumResourceNamesA(), EnumResourceTypesA(), ExceptionFilter(), ExtractIconExW(), get_host_winver(), get_mono_path(), get_res_data(), GetDriverVersion(), GetEnvStatus(), hook_WaitForInputIdle(), include_pac_utils(), init(), Init(), init_aes_environment(), init_base_environment(), init_func_ptrs(), init_funcs(), init_function_pointers(), init_function_ptrs(), init_functionpointers(), init_functions(), init_pointers(), init_procs(), init_test(), init_tests(), init_threadpool(), InitFunctionPointers(), InitFunctionPtrs(), is_lang_english(), is_module_loaded(), is_process_limited(), load_it_up(), load_resource(), load_v6_module(), LoadResource(), loadShell32(), mdi_RegisterWindowClasses(), MSVCRT_locale_to_LCID(), MyUserYield(), MyWndProc(), NPSAuthenticationDialogA(), path_to_pidl(), print_version(), rebuild_toolbar(), register_child_wnd_class(), register_class(), register_classes(), register_dummy_class(), register_menu_check_class(), register_parent_class(), register_parent_wnd_class(), register_style_check_class(), register_testwindow_class(), register_window_class(), register_window_classes(), register_wmime_keydown_class(), RegisterClassHelper(), registerParentWindowClass(), RegisterWindowClasses(), running_under_wine(), scrollbar_test_init(), setup_pointers(), sheet_callback(), ShowUsage(), START_TEST(), subclass_button(), subclass_combobox(), subclass_edit(), subclass_static(), test_accelerators(), test_AccessCheck(), test_acmDriverAdd(), test_add_bitmap(), test_add_string(), test_aligned(), test_arrange(), test_attach_input(), test_ax_win(), test_builtinproc(), test_buttons(), test_capture_4(), test_change_focus(), test_CheckMenuRadioItem(), test_child_window_from_point(), test_clipboard_viewers(), test_comctl32_class(), test_converttoemfplus(), test_cookie_attrs(), test_CoWaitForMultipleHandles(), test_crash_couninitialize(), test_create(), test_create_view_template(), test_CreateActCtx(), test_createeffect(), test_createtoolbarex(), test_CreateUpDownControl(), test_CreateWindow(), test_csparentdc(), test_custom_default_button(), test_customdraw(), test_data_cache(), test_dc_layout(), test_default_handler_run(), test_DeleteDC(), test_dialog_messages(), test_dialog_parent(), test_DialogBoxParam(), test_dialogmode(), test_directory_filename(), test_disableowner(), test_drawimage(), test_EM_SETTEXTEX(), test_EN_LINK(), test_EndDialog(), test_EnumProcessModules(), test_eventMask(), test_events(), test_ExitCode(), test_ExtractIcon(), test_FakeDLL(), test_filenames(), test_fullscreen(), test_GdiConvertToDevmodeW(), test_gdiis(), test_GdipInitializePalette(), test_GetConsoleFontInfo(), test_GetConsoleFontSize(), test_GetConsoleScreenBufferInfoEx(), Test_GetDCEx_Cached(), Test_GetDCEx_CS_CLASSDC(), Test_GetDCEx_CS_Mixed(), Test_GetDCEx_CS_OWNDC(), Test_GetDCEx_CS_SwitchedStyle(), test_GetFileVersionInfoEx(), Test_GetKeyState(), test_GetLargestConsoleWindowSize(), test_GetLastActivePopup(), test_GetListBoxInfo(), test_GetMappedFileName(), test_GetModuleBaseName(), test_GetModuleFileNameEx(), test_GetModuleInformation(), test_GetPhysicallyInstalledSystemMemory(), test_GetProcessImageFileName(), test_GetScrollBarInfo(), test_GetSetConsoleInputExeName(), test_getstring(), test_gettext(), test_GetUpdateRect(), test_GetWindowModuleFileName(), test_heap(), test_HeapQueryInformation(), test_hotkey(), test_I_RpcExceptionFilter(), test_I_UpdateStore(), test_IgnoreFreeLibrary(), test_IME(), test_ImmGetCompositionString(), test_ImmMessages(), test_import_resolution(), test_ImportDescriptors(), test_Input_blackbox(), test_Input_mouse(), test_Input_whitebox(), test_InSendMessage(), test_instances(), test_invisible_create(), test_iocp_callback(), test_IsWindowUnicode(), test_launch_app_registry(), test_layout(), test_ldap_parse_sort_control(), test_LdrAddRefDll(), test_listbox_dlgdir(), test_Loader(), test_LoadImage(), test_LoadStringA(), test_LoadStringW(), test_longtextA(), test_maximum_allowed(), test_md5_ctx(), test_mdi(), test_MDI_child_stack(), test_MDI_create(), test_mdi_messages(), test_menu_hilitemenuitem(), test_menu_input(), test_menu_messages(), test_message_from_hmodule(), test_messages(), test_mouse_ll_hook(), test_mru(), test_msidecomposedesc(), test_NdrDllGetClassObject(), test_NdrDllRegisterProxy(), test_NdrGetUserMarshalInfo(), test_nopage(), test_noresize(), test_NtAreMappedFilesTheSame(), test_null_filename(), test_obsolete_flags(), test_ok(), test_ole_initialization(), test_pager(), test_param_check(), test_pe_checksum(), test_PlaySound(), test_popup_zorder(), test_propertytovariant(), test_proxy_used_in_wrong_thread(), test_PSM_ADDPAGE(), test_PSM_INSERTPAGE(), test_queryvirtualmemory(), test_quit_message(), test_redraw(), test_redrawnow(), test_registrar(), test_resizable2(), test_resize(), test_set_clipboard_DRAWCLIPBOARD(), test_set_hook(), test_set_window_style(), test_SetConsoleFont(), Test_SetCursorPos(), test_setinfo(), test_sha_ctx(), test_SHChangeNotify(), test_SHCreateWorkerWindowA(), test_shell_window(), test_SHSetWindowBits(), test_Sign_Media(), test_SIPLoad(), test_sizes(), test_smresult(), test_sscanf_s(), test_stgcreatestorageex(), test_stillimage_aggregation(), test_subitem_rect(), test_swscanf_s(), test_thick_child_size(), test_thread_start_address(), test_timer(), test_title(), test_tooltip(), test_treeview_classinfo(), test_TTM_ADDTOOL(), test_ttm_gettoolinfo(), test_TTN_SHOW(), test_update_region(), test_updown_buddy(), test_updown_create(), test_UuidCreateSequential(), test_varianttoproperty(), test_verifyRevocation(), test_version_flag_versus_aw(), test_WaitForInputIdle(), test_winevents(), test_winproc_handles(), test_wiznavigation(), test_WM_NOTIFY(), test_wndproc(), test_write_watch(), testGetModuleFileName(), testK32GetModuleInformation(), testNestedLoadLibraryA(), wined3d_adapter_init(), WINMM_CheckForMMSystem(), and write_typelib().

820 {
821  PUNICODE_STRING ModuleNameW;
822  PTEB pTeb = NtCurrentTeb();
823 
824  /* Check if we have no name to convert */
825  if (!lpModuleName)
827 
828  /* Convert module name to unicode */
829  ModuleNameW = Basep8BitStringToStaticUnicodeString(lpModuleName);
830 
831  /* Call W version if conversion was successful */
832  if (ModuleNameW)
833  return GetModuleHandleW(ModuleNameW->Buffer);
834 
835  /* Return failure */
836  return 0;
837 }
PUNICODE_STRING WINAPI Basep8BitStringToStaticUnicodeString(IN LPCSTR String)
Definition: utils.c:188
PPEB ProcessEnvironmentBlock
Definition: ntddk_ex.h:341
PVOID ImageBaseAddress
Definition: ntddk_ex.h:249
Definition: compat.h:484
FORCEINLINE struct _TEB * NtCurrentTeb(VOID)
Definition: psfuncs.h:420
HMODULE WINAPI GetModuleHandleW(LPCWSTR lpModuleName)
Definition: loader.c:845

◆ GetModuleHandleExA()

BOOL WINAPI GetModuleHandleExA ( IN DWORD  dwFlags,
IN LPCSTR lpModuleName  OPTIONAL,
OUT HMODULE phModule 
)

Definition at line 903 of file loader.c.

Referenced by testGetModuleHandleEx().

906 {
907  PUNICODE_STRING lpModuleNameW;
908  DWORD dwValid;
909  BOOL Ret;
910 
911  /* Validate parameters */
912  dwValid = BasepGetModuleHandleExParameterValidation(dwFlags, (LPCWSTR)lpModuleName, phModule);
913 
914  /* If result is invalid parameter - return failure */
916 
917  /* If result is 2, there is no need to do anything - return success. */
919 
920  /* Check if we don't need to convert the name */
921  if (dwFlags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
922  {
923  /* Call the extended version of the API without conversion */
925  dwFlags,
926  (LPCWSTR)lpModuleName,
927  phModule);
928  }
929  else
930  {
931  /* Convert module name to unicode */
932  lpModuleNameW = Basep8BitStringToStaticUnicodeString(lpModuleName);
933 
934  /* Return FALSE if conversion failed */
935  if (!lpModuleNameW) return FALSE;
936 
937  /* Call the extended version of the API */
939  dwFlags,
940  lpModuleNameW->Buffer,
941  phModule);
942  }
943 
944  /* Return result */
945  return Ret;
946 }
PUNICODE_STRING WINAPI Basep8BitStringToStaticUnicodeString(IN LPCSTR String)
Definition: utils.c:188
#define TRUE
Definition: types.h:120
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
Definition: kernel32.h:105
BOOLEAN WINAPI BasepGetModuleHandleExW(BOOLEAN NoLock, DWORD dwPublicFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:723
const WCHAR * LPCWSTR
Definition: xmlstorage.h:185
unsigned int BOOL
Definition: ntddk_ex.h:94
unsigned long DWORD
Definition: ntddk_ex.h:95
_In_ PCCERT_CONTEXT _In_ DWORD dwFlags
Definition: wincrypt.h:1175
DWORD WINAPI BasepGetModuleHandleExParameterValidation(DWORD dwFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:26
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
Definition: kernel32.h:106

◆ GetModuleHandleExW()

BOOL WINAPI GetModuleHandleExW ( IN DWORD  dwFlags,
IN LPCWSTR lpwModuleName  OPTIONAL,
OUT HMODULE phModule 
)

Definition at line 873 of file loader.c.

Referenced by cache_connection(), ATL::CAtlBaseModule::CAtlBaseModule(), ATL::CAtlComModule::CAtlComModule(), DllMain(), GPNotificationThreadProc(), http_release_netconn(), LookupThreadProc(), testGetModuleHandleEx(), and wined3d_cs_create().

876 {
877  DWORD dwValid;
878  BOOL Ret;
879 
880  /* Validate parameters */
881  dwValid = BasepGetModuleHandleExParameterValidation(dwFlags, lpwModuleName, phModule);
882 
883  /* If result is invalid parameter - return failure */
885 
886  /* If result is 2, there is no need to do anything - return success. */
888 
889  /* Use common helper routine */
891  dwFlags,
892  lpwModuleName,
893  phModule);
894 
895  return Ret;
896 }
#define TRUE
Definition: types.h:120
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_ERROR
Definition: kernel32.h:105
BOOLEAN WINAPI BasepGetModuleHandleExW(BOOLEAN NoLock, DWORD dwPublicFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:723
unsigned int BOOL
Definition: ntddk_ex.h:94
unsigned long DWORD
Definition: ntddk_ex.h:95
_In_ PCCERT_CONTEXT _In_ DWORD dwFlags
Definition: wincrypt.h:1175
DWORD WINAPI BasepGetModuleHandleExParameterValidation(DWORD dwFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:26
#define BASEP_GET_MODULE_HANDLE_EX_PARAMETER_VALIDATION_SUCCESS
Definition: kernel32.h:106

◆ GetModuleHandleForUnicodeString()

HMODULE WINAPI GetModuleHandleForUnicodeString ( PUNICODE_STRING  ModuleName)

Definition at line 674 of file loader.c.

Referenced by BasepGetModuleHandleExW().

675 {
677  PVOID Module;
678  LPWSTR DllPath;
679 
680  /* Try to get a handle with a magic value of 1 for DllPath */
681  Status = LdrGetDllHandle((LPWSTR)1, NULL, ModuleName, &Module);
682 
683  /* If that succeeded - we're done */
684  if (NT_SUCCESS(Status)) return Module;
685 
686  /* If not, then the path should be computed */
687  DllPath = BaseComputeProcessDllPath(NULL, 0);
688  if (!DllPath)
689  {
690  Status = STATUS_NO_MEMORY;
691  }
692  else
693  {
694  _SEH2_TRY
695  {
696  Status = LdrGetDllHandle(DllPath, NULL, ModuleName, &Module);
697  }
699  {
700  /* Fail with the SEH error */
701  Status = _SEH2_GetExceptionCode();
702  }
703  _SEH2_END;
704  }
705 
706  /* Free the DllPath */
707  RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath);
708 
709  /* In case of error set last win32 error and return NULL */
710  if (!NT_SUCCESS(Status))
711  {
712  DPRINT("Failure acquiring DLL module '%wZ' handle, Status 0x%08X\n", ModuleName, Status);
713  BaseSetLastNTError(Status);
714  Module = 0;
715  }
716 
717  /* Return module */
718  return (HMODULE)Module;
719 }
NTSTATUS NTAPI LdrGetDllHandle(IN PWSTR DllPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *DllHandle)
Definition: ldrapi.c:805
LONG NTSTATUS
Definition: precomp.h:26
BOOLEAN NTAPI RtlFreeHeap(IN PVOID HeapHandle, IN ULONG Flags, IN PVOID HeapBase)
Definition: heap.c:603
_SEH2_TRY
Definition: create.c:4250
#define EXCEPTION_EXECUTE_HANDLER
Definition: excpt.h:85
smooth NULL
Definition: ftsmooth.c:416
void DPRINT(...)
Definition: polytest.cpp:61
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
Status
Definition: gdiplustypes.h:24
LPWSTR WINAPI BaseComputeProcessDllPath(IN LPWSTR FullPath, IN PVOID Environment)
Definition: path.c:420
_SEH2_END
Definition: create.c:4424
static const char const char * DllPath
Definition: image.c:34
#define STATUS_NO_MEMORY
Definition: ntstatus.h:246
#define _SEH2_EXCEPT(...)
Definition: pseh2_64.h:6
#define _SEH2_GetExceptionCode()
Definition: pseh2_64.h:12
WCHAR * LPWSTR
Definition: xmlstorage.h:184

◆ GetModuleHandleW()

HMODULE WINAPI GetModuleHandleW ( LPCWSTR  lpModuleName)

Definition at line 845 of file loader.c.

Referenced by _CorExeMain(), CBandSiteMenu::_CreateMenuPart(), CBandSiteMenu::_CreateNewISFBand(), _DoDLLInjection(), CBandSiteBase::_OnContextMenu(), _SHCreateDesktop(), _SHDesktopMessageLoop(), _ShellDDEInit(), CBandSiteMenu::_ShowToolbarError(), AddTextButton(), AllocAndLoadString(), ApplicationPage_OnSwitchTo(), ApplicationPageOnNotify(), ask_confirm(), AtlAxWinInit(), cleanup(), CMenuBand_CreateInstance(), Confirm(), CDeviceManager::Create(), create_clipbrd_window(), create_listview_controlW(), create_parent_window(), create_syslink(), create_test_windows(), device_tests(), dialog_about(), dialog_viewproperties(), DoEntry(), DoLoadStrings(), DrawThemeText(), EnumJoysticks(), EnumResourceLanguagesW(), EnumResourceNamesW(), EnumResourceTypesW(), EnumWindowsProc(), execute_test(), exit(), extract_resource(), fetch_shlwapi_ordinal(), FILEDLG95_MRU_load_filename(), FILEDLG95_MRU_save_filename(), FindResourceExA(), FindResourceExW(), get_print_file_filter(), BtrfsContextMenu::get_uac_icon(), GetComCtl32Version(), GetLocalsplFuncs(), GetModuleHandleA(), GetProc(), GetResource(), GetSeconds(), GetSpoolssFunc(), GetSystemCPU(), CConfiguration::GetSystemInformation(), ie_dialog_about(), ImmGetContextThreadFunc(), init(), init_preview(), InitializeAPI(), InitThreads(), IntInitializeImmEntryTable(), IsWininetLoaded(), IsWinsockLoaded(), joystick_tests(), keyboard_tests(), load_message(), LsapInitSids(), LsarpLookupPrivilegeDisplayName(), main(), MCIWndCreateW(), MessageBoxWithResStringW(), mouse_tests(), msg_spy_init(), newfile_proc(), OLEClipbrd_UnInitialize(), OnCommand(), OnCreate(), output_message(), output_value(), paraformat_proc(), preview_exit(), preview_proc(), CISFBand::QueryContextMenu(), register_iewindow_class(), register_parent_wnd_class(), RegisterClassExWOWW(), RegisterWindowClasses(), RichEditOleCallback_GetContextMenu(), run_test(), SampInitializeSAM(), START_TEST(), taskkill_message(), taskkill_message_printfW(), test_actctx_classes(), test_builtinproc(), test_default_ime_disabled_cb(), test_default_ime_window_cancel_cb(), test_default_ime_window_cb(), test_default_ime_with_message_only_window_cb(), test_directory_filename(), test_find_resource(), test_GetInterfaceName(), test_icons(), test_ime_processkey(), test_ImmDefaultHwnd(), test_Input_unicode(), test_LoadImage(), test_longtextW(), test_message_conversion(), test_null_filename(), test_rtti(), Test_SetCursorPos(), test_track(), test_write_watch(), TestManualInstantiation(), TestSoftModalMsgBox(), toggle_num_pages(), TrayIcon_ShellAddTrayIcon(), UnloadAppInitDlls(), update_preview_statusbar(), UpdatePerUserImmEnabling(), usage(), User32CallEventProcFromKernel(), User32CallHookProcFromKernel(), UserpFormatMessages(), WhoamiLoadRcString(), WineFile_OnRun(), WinMain(), wWinMain(), and XCOPY_LoadMessage().

846 {
849 
850  /* If current module is requested - return it right away */
851  if (!lpModuleName)
852  return ((HMODULE)NtCurrentPeb()->ImageBaseAddress);
853 
854  /* Use common helper routine */
855  Success = BasepGetModuleHandleExW(TRUE,
856  GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
857  lpModuleName,
858  &hModule);
859 
860  /* If it wasn't successful - return NULL */
861  if (!Success) hModule = NULL;
862 
863  /* Return the handle */
864  return hModule;
865 }
#define TRUE
Definition: types.h:120
BOOLEAN WINAPI BasepGetModuleHandleExW(BOOLEAN NoLock, DWORD dwPublicFlags, LPCWSTR lpwModuleName, HMODULE *phModule)
Definition: loader.c:723
unsigned char BOOLEAN
smooth NULL
Definition: ftsmooth.c:416
#define NtCurrentPeb()
Definition: FLS.c:19
HMODULE hModule
Definition: animate.c:44

◆ GetProcAddress()

FARPROC WINAPI GetProcAddress ( HMODULE  hModule,
LPCSTR  lpProcName 
)

Definition at line 399 of file loader.c.

Referenced by START_TEST(), test_FakeDLL(), test_import_resolution(), test_ResolveDelayLoadedAPI(), and wine_dlsym().

400 {
401  ANSI_STRING ProcedureName, *ProcNamePtr = NULL;
402  FARPROC fnExp = NULL;
404  PVOID hMapped;
405  ULONG Ordinal = 0;
406 
407  if ((ULONG_PTR)lpProcName > MAXUSHORT)
408  {
409  /* Look up by name */
410  RtlInitAnsiString(&ProcedureName, (LPSTR)lpProcName);
411  ProcNamePtr = &ProcedureName;
412  }
413  else
414  {
415  /* Look up by ordinal */
416  Ordinal = PtrToUlong(lpProcName);
417  }
418 
419  /* Map provided handle */
420  hMapped = BasepMapModuleHandle(hModule, FALSE);
421 
422  /* Get the proc address */
423  Status = LdrGetProcedureAddress(hMapped,
424  ProcNamePtr,
425  Ordinal,
426  (PVOID*)&fnExp);
427 
428  if (!NT_SUCCESS(Status))
429  {
430  BaseSetLastNTError(Status);
431  return NULL;
432  }
433 
434  /* Check for a special case when returned pointer is
435  the same as image's base address */
436  if (fnExp == hMapped)
437  {
438  /* Set correct error code */
439  if (HIWORD(lpProcName) != 0)
441  else
443 
444  return NULL;
445  }
446 
447  /* All good, return procedure pointer */
448  return fnExp;
449 }
LONG NTSTATUS
Definition: precomp.h:26
char * LPSTR
Definition: xmlstorage.h:182
NTSYSAPI VOID NTAPI RtlInitAnsiString(PANSI_STRING DestinationString, PCSZ SourceString)
uint32_t ULONG_PTR
Definition: typedefs.h:63
NTSTATUS NTAPI LdrGetProcedureAddress(IN PVOID BaseAddress, IN PANSI_STRING Name, IN ULONG Ordinal, OUT PVOID *ProcedureAddress)
Definition: ldrapi.c:823
smooth NULL
Definition: ftsmooth.c:416
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define PtrToUlong(p)
Definition: basetsd.h:83
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
Status
Definition: gdiplustypes.h:24
#define STATUS_ORDINAL_NOT_FOUND
Definition: ntstatus.h:534
#define MAXUSHORT
Definition: typedefs.h:81
#define STATUS_ENTRYPOINT_NOT_FOUND
Definition: ntstatus.h:535
#define HIWORD(l)
Definition: typedefs.h:246
unsigned int ULONG
Definition: retypes.h:1
int(* FARPROC)()
Definition: compat.h:28
PVOID WINAPI BasepMapModuleHandle(HMODULE hModule, BOOLEAN AsDataFile)
Definition: loader.c:67

◆ LoadLibraryA()

HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryA ( LPCSTR  lpLibFileName)

Definition at line 111 of file loader.c.

Referenced by __delayLoadHelper2(), _loaddll(), _mesa_dlopen(), child_process(), create_printer_dc(), CreateProxyFromTypeInfo(), CreateStubFromTypeInfo(), CRYPT_CreateKeyProv(), DefineDosDeviceW(), Direct3DCreate9(), DliFailHook(), DliHook(), dll_entry_point(), DllUnregisterServer(), DP_LoadSP(), EnableDialogTheme(), ExceptionFilter(), Extract(), extract_cabinet_file(), ExtractFilesA(), FGetComponentPath(), get_corversion(), GetFileNamePreview(), GetUIVersion(), init(), Init(), init_function_pointers(), init_function_ptrs(), init_functionpointers(), init_functions(), init_gdip(), init_pointers(), init_test_functions(), init_tests(), InitFuncPtrs(), InitFunctionPtr(), InitFunctionPtrs(), load_functions(), load_v6_module(), LoadCABINETDll(), LoadCOM(), loadIPHlpApi(), ATL::CImage::COMMON::LoadLib(), LoadLibraryList(), LoadShimDLL(), MACRO_RegisterRoutine(), main(), MCICDA_drvOpen(), MLLoadLibraryA(), msi_dialog_scrolltext_control(), parse_url_from_outside(), prepare_test(), profile_items_callback(), propvar_changetype(), rand_s(), RegisterDeviceNotificationW(), seterror(), SHDOCVW_LoadShell32(), START_TEST(), test_AdvInstallFile(), test_DeviceCapabilities(), test_filenames(), test_GetModuleInformation(), test_IgnoreFreeLibrary(), test_image_mapping(), test_import_resolution(), test_Input_unicode(), test_LdrAddRefDll(), test_Loader(), test_LoadIconWithScaleDown(), test_onefile(), test_res_protocol(), test_ResolveDelayLoadedAPI(), test_section_access(), test_SetDefaultDllDirectories(), test_shell_imagelist(), test_typelib(), test_WICCreateBitmapFromSectionEx(), testGetModuleHandleEx(), testLoadLibraryA(), testLoadLibraryA_Wrong(), testNestedLoadLibraryA(), ThirdPartyVDDBop(), twain_add_onedriver(), TWAIN_OpenDS(), UIINSERTOBJECTDLG_AddControl(), UnregisterDeviceNotification(), use_common(), vmr_create(), WhichPlatform(), wine_dlopen(), WinMain(), WsNpInitialize(), and WspiapiLoad().

112 {
113  LPSTR PathBuffer;
114  UINT Len;
116 
117  /* Treat twain_32.dll in a special way (what a surprise...) */
118  if (lpLibFileName && !_strcmpi(lpLibFileName, "twain_32.dll"))
119  {
120  /* Allocate space for the buffer */
121  PathBuffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, MAX_PATH);
122  if (PathBuffer)
123  {
124  /* Get windows dir in this buffer */
125  Len = GetWindowsDirectoryA(PathBuffer, MAX_PATH - 13); /* 13 is sizeof of '\\twain_32.dll' */
126  if (Len && Len < (MAX_PATH - 13))
127  {
128  /* We successfully got windows directory. Concatenate twain_32.dll to it */
129  strncat(PathBuffer, "\\twain_32.dll", 13);
130 
131  /* And recursively call ourselves with a new string */
132  Result = LoadLibraryA(PathBuffer);
133 
134  /* If it was successful - free memory and return result */
135  if (Result)
136  {
137  RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer);
138  return Result;
139  }
140  }
141 
142  /* Free allocated buffer */
143  RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer);
144  }
145  }
146 
147  /* Call the Ex version of the API */
148  return LoadLibraryExA(lpLibFileName, 0, 0);
149 }
char * strncat(char *DstString, const char *SrcString, ACPI_SIZE Count)
Definition: utclib.c:605
BOOLEAN NTAPI RtlFreeHeap(IN PVOID HeapHandle, IN ULONG Flags, IN PVOID HeapBase)
Definition: heap.c:603
char * LPSTR
Definition: xmlstorage.h:182
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR lpLibFileName)
Definition: loader.c:111
_At_(*)(_In_ PWSK_CLIENT Client, _In_opt_ PUNICODE_STRING NodeName, _In_opt_ PUNICODE_STRING ServiceName, _In_opt_ ULONG NameSpace, _In_opt_ GUID *Provider, _In_opt_ PADDRINFOEXW Hints, _Outptr_ PADDRINFOEXW *Result, _In_opt_ PEPROCESS OwningProcess, _In_opt_ PETHREAD OwningThread, _Inout_ PIRP Irp Result)(Mem)) NTSTATUS(WSKAPI *PFN_WSK_GET_ADDRESS_INFO
Definition: wsk.h:426
PVOID NTAPI RtlAllocateHeap(IN PVOID HeapHandle, IN ULONG Flags, IN SIZE_T Size)
Definition: heap.c:585
#define MAX_PATH
Definition: compat.h:26
unsigned int UINT
Definition: ndis.h:50
#define Len
Definition: deflate.h:82
UINT WINAPI GetWindowsDirectoryA(OUT LPSTR lpBuffer, IN UINT uSize)
Definition: path.c:2336
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
Definition: loader.c:157
_Check_return_ _CRTIMP int __cdecl _strcmpi(_In_z_ const char *_Str1, _In_z_ const char *_Str2)

◆ LoadLibraryExA()

HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA ( LPCSTR  lpLibFileName,
HANDLE  hFile,
DWORD  dwFlags 
)

Definition at line 157 of file loader.c.

Referenced by extract_test_proc(), LoadLibraryA(), LoadModuleWithSymbolsFullPath(), map_image_section(), SHPinDllOfCLSID(), START_TEST(), test_import_resolution(), test_Loader(), test_LoadLibraryEx_search_flags(), test_pe_checksum(), test_SetDefaultDllDirectories(), and testLoadLibraryEx().

160 {
161  PUNICODE_STRING FileNameW;
162 
163  /* Convert file name to unicode */
164  if (!(FileNameW = Basep8BitStringToStaticUnicodeString(lpLibFileName)))
165  return NULL;
166 
167  /* And call W version of the API */
168  return LoadLibraryExW(FileNameW->Buffer, hFile, dwFlags);
169 }
PUNICODE_STRING WINAPI Basep8BitStringToStaticUnicodeString(IN LPCSTR String)
Definition: utils.c:188
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
Definition: loader.c:286
smooth NULL
Definition: ftsmooth.c:416
_In_ PCCERT_CONTEXT _In_ DWORD dwFlags
Definition: wincrypt.h:1175

◆ LoadLibraryExW()

HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW ( LPCWSTR  lpLibFileName,
HANDLE  hFile,
DWORD  dwFlags 
)

Definition at line 286 of file loader.c.

Referenced by add_zone_to_listview(), CoLoadLibrary(), COMPOBJ_DllList_Add(), CClassNode::ConvertResourceDescriptorToString(), CURSORICON_CopyImage(), DIALOG_SYMBOL_DlgProc(), do_register_dll(), DoExtractIcon(), DoLoadIcons(), EngLoadModule(), get_shdoclc(), GetFileVersionInfoExW(), GetFileVersionInfoSizeExW(), GetMessageStringFromDll(), GetServiceDllFunction(), ITERATE_RegisterTypeLibraries(), load_xul(), LoadLibraryExA(), LoadLibraryW(), LoadProc(), MSSTYLES_OpenThemeFile(), register_ocxs_callback(), RegisterOCX(), RegLoadMUIStringW(), ATL::CRegObject::resource_register(), resource_register(), ResProtocol_Start(), ResProtocolInfo_ParseUrl(), RunDlgProc(), SHCoCreateInstance(), TestDllRedirection(), TLB_PEFile_Open(), User32CallEventProcFromKernel(), and User32CallHookProcFromKernel().

289 {
290  UNICODE_STRING DllName;
294  ULONG DllCharacteristics = 0;
295  BOOL FreeString = FALSE;
296 
297  /* Check for any flags LdrLoadDll might be interested in */
299  {
300  /* Tell LDR to treat it as an EXE */
301  DllCharacteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
302  }
303 
304  /* Build up a unicode dll name from null-terminated string */
305  RtlInitUnicodeString(&DllName, (LPWSTR)lpLibFileName);
306 
307  /* Lazy-initialize BasepExeLdrEntry */
308  if (!BasepExeLdrEntry)
310 
311  /* Check if that module is our exe*/
314  {
315  /* Lengths match and it's not a datafile, so perform name comparison */
317  {
318  /* That's us! */
319  return BasepExeLdrEntry->DllBase;
320  }
321  }
322 
323  /* Check for trailing spaces and remove them if necessary */
324  if (DllName.Buffer[DllName.Length/sizeof(WCHAR) - 1] == L' ')
325  {
326  RtlCreateUnicodeString(&DllName, (LPWSTR)lpLibFileName);
327  while (DllName.Length > sizeof(WCHAR) &&
328  DllName.Buffer[DllName.Length/sizeof(WCHAR) - 1] == L' ')
329  {
330  DllName.Length -= sizeof(WCHAR);
331  }
332  DllName.Buffer[DllName.Length/sizeof(WCHAR)] = UNICODE_NULL;
333  FreeString = TRUE;
334  }
335 
336  /* Compute the load path */
338  DllName.Buffer : NULL,
339  NULL);
340  if (!SearchPath)
341  {
342  /* Getting DLL path failed, so set last error, free mem and return */
344  if (FreeString) RtlFreeUnicodeString(&DllName);
345  return NULL;
346  }
347 
348  _SEH2_TRY
349  {
350  if (dwFlags & LOAD_LIBRARY_AS_DATAFILE)
351  {
352  /* If the image is loaded as a datafile, try to get its handle */
353  Status = LdrGetDllHandleEx(0, SearchPath, NULL, &DllName, (PVOID*)&hInst);
354  if (!NT_SUCCESS(Status))
355  {
356  /* It's not loaded yet - so load it up */
357  Status = BasepLoadLibraryAsDatafile(SearchPath, DllName.Buffer, &hInst);
358  }
359  _SEH2_YIELD(goto done;)
360  }
361 
362  /* Call the API Properly */
363  Status = LdrLoadDll(SearchPath,
364  &DllCharacteristics,
365  &DllName,
366  (PVOID*)&hInst);
367  }
369  {
370  Status = _SEH2_GetExceptionCode();
371  } _SEH2_END;
372 
373 
374 done:
375  /* Free SearchPath buffer */
376  RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath);
377 
378  /* Free DllName string if it was dynamically allocated */
379  if (FreeString) RtlFreeUnicodeString(&DllName);
380 
381  /* Set last error in failure case */
382  if (!NT_SUCCESS(Status))
383  {
384  DPRINT1("LoadLibraryExW(%ls) failing with status %lx\n", lpLibFileName, Status);
385  BaseSetLastNTError(Status);
386  return NULL;
387  }
388 
389  /* Return loaded module handle */
390  return hInst;
391 }
NTSTATUS NTAPI LdrGetDllHandleEx(IN ULONG Flags, IN PWSTR DllPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *DllHandle OPTIONAL)
Definition: ldrapi.c:522
#define TRUE
Definition: types.h:120
__wchar_t WCHAR
Definition: xmlstorage.h:180
uint16_t * PWSTR
Definition: typedefs.h:54
LONG NTSTATUS
Definition: precomp.h:26
BOOLEAN NTAPI RtlFreeHeap(IN PVOID HeapHandle, IN ULONG Flags, IN PVOID HeapBase)
Definition: heap.c:603
#define LOAD_WITH_ALTERED_SEARCH_PATH
Definition: winbase.h:339
#define WCHAR
Definition: msvc.h:43
#define SearchPath
Definition: winbase.h:3714
_SEH2_TRY
Definition: create.c:4250
PVOID DllBase
Definition: btrfs_drv.h:1805
#define UNICODE_NULL
#define EXCEPTION_EXECUTE_HANDLER
Definition: excpt.h:85
smooth NULL
Definition: ftsmooth.c:416
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
PLDR_DATA_TABLE_ENTRY BasepExeLdrEntry
Definition: proc.c:25
unsigned int BOOL
Definition: ntddk_ex.h:94
#define _SEH2_YIELD(STMT_)
Definition: pseh2_64.h:8
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
#define IMAGE_FILE_EXECUTABLE_IMAGE
Definition: pedump.c:160
NTSYSAPI VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING UnicodeString)
#define DONT_RESOLVE_DLL_REFERENCES
Definition: winbase.h:337
NTSYSAPI BOOLEAN NTAPI RtlCreateUnicodeString(PUNICODE_STRING DestinationString, PCWSTR SourceString)
static const WCHAR L[]
Definition: oid.c:1087
_In_ PCCERT_CONTEXT _In_ DWORD dwFlags
Definition: wincrypt.h:1175
NTSTATUS NTAPI DECLSPEC_HOTPATCH LdrLoadDll(IN PWSTR SearchPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *BaseAddress)
Definition: ldrapi.c:310
static NTSTATUS BasepLoadLibraryAsDatafile(PWSTR Path, LPCWSTR Name, HMODULE *hModule)
Definition: loader.c:186
NTSTATUS NTAPI LdrEnumerateLoadedModules(IN BOOLEAN ReservedFlag, IN PLDR_ENUM_CALLBACK EnumProc, IN PVOID Context)
Definition: ldrapi.c:1120
VOID NTAPI BasepLocateExeLdrEntry(IN PLDR_DATA_TABLE_ENTRY Entry, IN PVOID Context, OUT BOOLEAN *StopEnumeration)
Definition: utils.c:156
Status
Definition: gdiplustypes.h:24
#define LOAD_LIBRARY_AS_DATAFILE
Definition: winbase.h:338
LPWSTR WINAPI BaseComputeProcessDllPath(IN LPWSTR FullPath, IN PVOID Environment)
Definition: path.c:420
_SEH2_END
Definition: create.c:4424
HINSTANCE hInst
Definition: dxdiag.c:13
#define NtCurrentPeb()
Definition: FLS.c:19
#define STATUS_NO_MEMORY
Definition: ntstatus.h:246
UNICODE_STRING FullDllName
Definition: btrfs_drv.h:1807
#define DPRINT1
Definition: precomp.h:8
unsigned int ULONG
Definition: retypes.h:1
NTSYSAPI VOID NTAPI RtlInitUnicodeString(PUNICODE_STRING DestinationString, PCWSTR SourceString)
#define _SEH2_EXCEPT(...)
Definition: pseh2_64.h:6
#define _SEH2_GetExceptionCode()
Definition: pseh2_64.h:12
WCHAR * LPWSTR
Definition: xmlstorage.h:184
NTSYSAPI BOOLEAN NTAPI RtlEqualUnicodeString(PUNICODE_STRING String1, PUNICODE_STRING String2, BOOLEAN CaseInSensitive)

◆ LoadLibraryW()

HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryW ( LPCWSTR  lpLibFileName)

Definition at line 177 of file loader.c.

178 {
179  /* Call Ex version of the API */
180  return LoadLibraryExW(lpLibFileName, 0, 0);
181 }
HINSTANCE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
Definition: loader.c:286

◆ LoadModule()

DWORD WINAPI LoadModule ( LPCSTR  lpModuleName,
LPVOID  lpParameterBlock 
)

Definition at line 954 of file loader.c.

956 {
957  STARTUPINFOA StartupInfo;
958  PROCESS_INFORMATION ProcessInformation;
959  LOADPARMS32 *LoadParams;
960  char FileName[MAX_PATH];
961  LPSTR CommandLine;
962  DWORD Length, Error;
963  BOOL ProcessStatus;
964  ANSI_STRING AnsiStr;
965  UNICODE_STRING UnicStr;
967  HANDLE Handle;
968 
969  LoadParams = (LOADPARMS32*)lpParameterBlock;
970 
971  /* Check load parameters */
972  if (LoadParams->dwReserved || LoadParams->wMagicValue != 2)
973  {
974  /* Fail with invalid param error */
976  return 0;
977  }
978 
979  /* Search path */
980  Length = SearchPathA(NULL, lpModuleName, ".exe", MAX_PATH, FileName, NULL);
981 
982  /* Check if path was found */
983  if (Length && Length < MAX_PATH)
984  {
985  /* Build StartupInfo */
986  RtlZeroMemory(&StartupInfo, sizeof(StartupInfo));
987 
988  StartupInfo.cb = sizeof(STARTUPINFOA);
989  StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
990  StartupInfo.wShowWindow = LoadParams->wCmdShow;
991 
992  /* Allocate command line buffer */
993  CommandLine = RtlAllocateHeap(RtlGetProcessHeap(),
995  (ULONG)LoadParams->lpCmdLine[0] + Length + 2);
996 
997  /* Put module name there, then a space, and then copy provided command line,
998  and null-terminate it */
999  RtlCopyMemory(CommandLine, FileName, Length);
1000  CommandLine[Length] = ' ';
1001  RtlCopyMemory(&CommandLine[Length + 1], &LoadParams->lpCmdLine[1], (ULONG)LoadParams->lpCmdLine[0]);
1002  CommandLine[Length + 1 + (ULONG)LoadParams->lpCmdLine[0]] = 0;
1003 
1004  /* Create the process */
1005  ProcessStatus = CreateProcessA(FileName,
1006  CommandLine,
1007  NULL,
1008  NULL,
1009  FALSE,
1010  0,
1011  LoadParams->lpEnvAddress,
1012  NULL,
1013  &StartupInfo,
1014  &ProcessInformation);
1015 
1016  /* Free the command line buffer */
1017  RtlFreeHeap(RtlGetProcessHeap(), 0, CommandLine);
1018 
1019  if (!ProcessStatus)
1020  {
1021  /* Creating process failed, return right error code */
1022  Error = GetLastError();
1023  switch(Error)
1024  {
1025  case ERROR_BAD_EXE_FORMAT:
1026  return ERROR_BAD_FORMAT;
1027 
1028  case ERROR_FILE_NOT_FOUND:
1029  case ERROR_PATH_NOT_FOUND:
1030  return Error;
1031  }
1032 
1033  /* Return 0 otherwise */
1034  return 0;
1035  }
1036 
1037  /* Wait up to 30 seconds for the process to become idle */
1039  {
1040  UserWaitForInputIdleRoutine(ProcessInformation.hProcess, 30000);
1041  }
1042 
1043  /* Close handles */
1044  NtClose(ProcessInformation.hThread);
1045  NtClose(ProcessInformation.hProcess);
1046 
1047  /* Return magic success value (33) */
1048  return 33;
1049  }
1050 
1051  /* The path was not found, create an ansi string from
1052  the module name and convert it to unicode */
1053  RtlInitAnsiString(&AnsiStr, lpModuleName);
1054  if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&UnicStr,&AnsiStr,TRUE)))
1055  return ERROR_FILE_NOT_FOUND;
1056 
1057  /* Determine path type */
1058  PathType = RtlDetermineDosPathNameType_U(UnicStr.Buffer);
1059 
1060  /* Free the unicode module name */
1061  RtlFreeUnicodeString(&UnicStr);
1062 
1063  /* If it's a relative path, return file not found */
1064  if (PathType == RtlPathTypeRelative)
1065  return ERROR_FILE_NOT_FOUND;
1066 
1067  /* If not, try to open it */
1068  Handle = CreateFile(lpModuleName,
1069  GENERIC_READ,
1071  NULL,
1072  OPEN_EXISTING,
1074  NULL);
1075 
1076  if (Handle != INVALID_HANDLE_VALUE)
1077  {
1078  /* Opening file succeeded for some reason, close the handle and return file not found anyway */
1079  CloseHandle(Handle);
1080  return ERROR_FILE_NOT_FOUND;
1081  }
1082 
1083  /* Return last error which CreateFile set during an attempt to open it */
1084  return GetLastError();
1085 }
struct _STARTUPINFOA STARTUPINFOA
#define ERROR_BAD_FORMAT
Definition: winerror.h:114
enum _RTL_PATH_TYPE RTL_PATH_TYPE
#define TRUE
Definition: types.h:120
NTSYSAPI VOID NTAPI RtlCopyMemory(VOID UNALIGNED *Destination, CONST VOID UNALIGNED *Source, ULONG Length)
#define CloseHandle
Definition: compat.h:398
LPSTR lpCmdLine
Definition: kernel32.h:72
#define STATUS_INVALID_PARAMETER
Definition: udferr_usr.h:135
LPSTR lpEnvAddress
Definition: kernel32.h:71
BOOLEAN NTAPI RtlFreeHeap(IN PVOID HeapHandle, IN ULONG Flags, IN PVOID HeapBase)
Definition: heap.c:603
#define INVALID_HANDLE_VALUE
Definition: compat.h:391
DWORD WINAPI GetLastError(VOID)
Definition: except.c:1059
DWORD dwFlags
Definition: winbase.h:807
#define FILE_SHARE_WRITE
Definition: nt_native.h:681
char * LPSTR
Definition: xmlstorage.h:182
WORD wMagicValue
Definition: kernel32.h:73
#define FILE_SHARE_READ
Definition: compat.h:125
NTSYSAPI VOID NTAPI RtlInitAnsiString(PANSI_STRING DestinationString, PCSZ SourceString)
static IN ULONG IN PWSTR OUT PCWSTR OUT PBOOLEAN OUT PATH_TYPE_AND_UNKNOWN * PathType
DWORD WINAPI SearchPathA(IN LPCSTR lpPath OPTIONAL, IN LPCSTR lpFileName, IN LPCSTR lpExtension OPTIONAL, IN DWORD nBufferLength, OUT LPSTR lpBuffer, OUT LPSTR *lpFilePart OPTIONAL)
Definition: path.c:1122
#define ERROR_BAD_EXE_FORMAT
Definition: winerror.h:251
smooth NULL
Definition: ftsmooth.c:416
WaitForInputIdleType UserWaitForInputIdleRoutine
Definition: proc.c:20
static const OBJECT_ATTRIBUTES const LARGE_INTEGER ULONG
Definition: loader.c:57
DWORD BaseSetLastNTError(IN NTSTATUS Status)
Definition: reactos.cpp:166
#define STARTF_USESHOWWINDOW
Definition: winbase.h:472
#define ERROR_FILE_NOT_FOUND
Definition: disk.h:79
#define OPEN_EXISTING
Definition: compat.h:426
PVOID NTAPI RtlAllocateHeap(IN PVOID HeapHandle, IN ULONG Flags, IN SIZE_T Size)
Definition: heap.c:585
_In_ HANDLE Handle
Definition: extypes.h:390
unsigned int BOOL
Definition: ntddk_ex.h:94
DWORD cb
Definition: winbase.h:796
#define NT_SUCCESS(StatCode)
Definition: apphelp.c:24
BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
Definition: proc.c:4772
#define MAX_PATH
Definition: compat.h:26
unsigned long DWORD
Definition: ntddk_ex.h:95
NTSYSAPI VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING UnicodeString)
BOOL Error
Definition: chkdsk.c:66
_In_ ULONG _In_ ULONG _In_ ULONG Length
Definition: ntddpcm.h:101
NTSTATUS NTAPI NtClose(IN HANDLE Handle)
Definition: obhandle.c:3393
#define FILE_ATTRIBUTE_NORMAL
Definition: compat.h:126
#define GENERIC_READ
Definition: compat.h:124
WORD wCmdShow
Definition: kernel32.h:74
IN OUT PVCB OUT PDIRENT OUT PBCB IN BOOLEAN CreateFile
Definition: fatprocs.h:904
NTSYSAPI NTSTATUS NTAPI RtlAnsiStringToUnicodeString(PUNICODE_STRING DestinationString, PANSI_STRING SourceString, BOOLEAN AllocateDestinationString)
WORD wShowWindow
Definition: winbase.h:808
#define HEAP_ZERO_MEMORY
Definition: compat.h:123
unsigned int ULONG
Definition: retypes.h:1
#define RtlZeroMemory(Destination, Length)
Definition: typedefs.h:261
#define ERROR_PATH_NOT_FOUND
Definition: winerror.h:106
DWORD dwReserved
Definition: kernel32.h:75
NTSYSAPI RTL_PATH_TYPE NTAPI RtlDetermineDosPathNameType_U(_In_ PCWSTR Path)

◆ UTRegister()

BOOL WINAPI UTRegister ( HMODULE  hModule,
LPSTR  lpsz16BITDLL,
LPSTR  lpszInitName,
LPSTR  lpszProcName,
FARPROC ppfn32Thunk,
FARPROC  pfnUT32CallBack,
LPVOID  lpBuff 
)

Definition at line 1099 of file loader.c.

1103 {
1104  STUB;
1105  return 0;
1106 }
#define STUB
Definition: kernel32.h:27

◆ UTUnRegister()

VOID WINAPI UTUnRegister ( HMODULE  hModule)

Definition at line 1111 of file loader.c.

1112 {
1113  STUB;
1114 }
#define STUB
Definition: kernel32.h:27