module.c 43.5 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 * Modules
 *
 * Copyright 1995 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
19 20
 */

21
#include "config.h"
22
#include "wine/port.h"
23

Alexandre Julliard's avatar
Alexandre Julliard committed
24
#include <fcntl.h>
25
#include <stdarg.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
26
#include <stdio.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
27 28
#include <stdlib.h>
#include <string.h>
29
#include <sys/types.h>
30 31 32
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
33 34
#include "ntstatus.h"
#define WIN32_NO_STATUS
Alexandre Julliard's avatar
Alexandre Julliard committed
35
#include "winerror.h"
36 37
#include "windef.h"
#include "winbase.h"
38
#include "winternl.h"
39
#include "kernel_private.h"
40
#include "psapi.h"
41

42
#include "wine/exception.h"
43
#include "wine/debug.h"
44
#include "wine/unicode.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
45

46
WINE_DEFAULT_DEBUG_CHANNEL(module);
47

48 49
#define NE_FFLAGS_LIBMODULE 0x8000

50 51 52 53 54 55 56
static WCHAR *dll_directory;  /* extra path for SetDllDirectoryW */

static CRITICAL_SECTION dlldir_section;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &dlldir_section,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
57
      0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
};
static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };


/****************************************************************************
 *              GetDllDirectoryA   (KERNEL32.@)
 */
DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
{
    DWORD len;

    RtlEnterCriticalSection( &dlldir_section );
    len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
    if (buffer && buf_len > len)
    {
        if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
        else *buffer = 0;
    }
    else
    {
        len++;  /* for terminating null */
        if (buffer) *buffer = 0;
    }
    RtlLeaveCriticalSection( &dlldir_section );
    return len;
}


/****************************************************************************
 *              GetDllDirectoryW   (KERNEL32.@)
 */
DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
{
    DWORD len;

    RtlEnterCriticalSection( &dlldir_section );
    len = dll_directory ? strlenW( dll_directory ) : 0;
    if (buffer && buf_len > len)
    {
        if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
        else *buffer = 0;
    }
    else
    {
        len++;  /* for terminating null */
        if (buffer) *buffer = 0;
    }
    RtlLeaveCriticalSection( &dlldir_section );
    return len;
}


/****************************************************************************
 *              SetDllDirectoryA   (KERNEL32.@)
 */
BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
{
    WCHAR *dirW;
    BOOL ret;

    if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
    ret = SetDllDirectoryW( dirW );
    HeapFree( GetProcessHeap(), 0, dirW );
    return ret;
}


/****************************************************************************
 *              SetDllDirectoryW   (KERNEL32.@)
 */
BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
{
    WCHAR *newdir = NULL;

    if (dir)
    {
        DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
        if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
        {
            SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            return FALSE;
        }
        memcpy( newdir, dir, len );
    }

    RtlEnterCriticalSection( &dlldir_section );
    HeapFree( GetProcessHeap(), 0, dll_directory );
    dll_directory = newdir;
    RtlLeaveCriticalSection( &dlldir_section );
    return TRUE;
}


151
/****************************************************************************
152
 *              DisableThreadLibraryCalls (KERNEL32.@)
153
 *
Jon Griffiths's avatar
Jon Griffiths committed
154 155 156 157 158 159 160 161 162 163 164 165 166
 * Inform the module loader that thread notifications are not required for a dll.
 *
 * PARAMS
 *  hModule [I] Module handle to skip calls for
 *
 * RETURNS
 *  Success: TRUE. Thread attach and detach notifications will not be sent
 *           to hModule.
 *  Failure: FALSE. Use GetLastError() to determine the cause.
 *
 * NOTES
 *  This is typically called from the dll entry point of a dll during process
 *  attachment, for dlls that do not need to process thread notifications.
167
 */
168
BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
169
{
170 171
    NTSTATUS    nts = LdrDisableThreadCalloutsForDll( hModule );
    if (nts == STATUS_SUCCESS) return TRUE;
172

173 174
    SetLastError( RtlNtStatusToDosError( nts ) );
    return FALSE;
175 176
}

Alexandre Julliard's avatar
Alexandre Julliard committed
177

178 179 180 181 182 183
/* Check whether a file is an OS/2 or a very old Windows executable
 * by testing on import of KERNEL.
 *
 * FIXME: is reading the module imports the only way of discerning
 *        old Windows binaries from OS/2 ones ? At least it seems so...
 */
184
static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
185 186
{
    DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
187
    DWORD ret = BINARY_OS216;
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    LPWORD modtab = NULL;
    LPSTR nametab = NULL;
    DWORD len;
    int i;

    /* read modref table */
    if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
      || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
      || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
      || (len != ne->ne_cmod*sizeof(WORD)) )
	goto broken;

    /* read imported names table */
    if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
      || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
      || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
      || (len != ne->ne_enttab - ne->ne_imptab) )
	goto broken;

    for (i=0; i < ne->ne_cmod; i++)
    {
	LPSTR module = &nametab[modtab[i]];
	TRACE("modref: %.*s\n", module[0], &module[1]);
	if (!(strncmp(&module[1], "KERNEL", module[0])))
	{ /* very old Windows file */
	    MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
214
            ret = BINARY_WIN16;
215 216 217 218 219
	    goto good;
	}
    }

broken:
220
    ERR("Hmm, an error occurred. Is this binary file broken?\n");
221 222 223 224 225

good:
    HeapFree( GetProcessHeap(), 0, modtab);
    HeapFree( GetProcessHeap(), 0, nametab);
    SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
226
    return ret;
227 228
}

229 230
/***********************************************************************
 *           MODULE_GetBinaryType
231
 */
232
void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
233 234 235 236 237 238
{
    union
    {
        struct
        {
            unsigned char magic[4];
239 240 241 242
            unsigned char class;
            unsigned char data;
            unsigned char version;
            unsigned char ignored[9];
243
            unsigned short type;
244
            unsigned short machine;
245
        } elf;
246 247
        struct
        {
248 249 250 251
            unsigned int magic;
            unsigned int cputype;
            unsigned int cpusubtype;
            unsigned int filetype;
252
        } macho;
253 254 255 256 257
        IMAGE_DOS_HEADER mz;
    } header;

    DWORD len;

258 259
    memset( info, 0, sizeof(*info) );

260
    /* Seek to the start of the file and read the header information. */
261 262
    if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
    if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
263 264 265

    if (!memcmp( header.elf.magic, "\177ELF", 4 ))
    {
266
        if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
267 268 269 270 271 272 273 274 275
#ifdef WORDS_BIGENDIAN
        if (header.elf.data == 1)
#else
        if (header.elf.data == 2)
#endif
        {
            header.elf.type = RtlUshortByteSwap( header.elf.type );
            header.elf.machine = RtlUshortByteSwap( header.elf.machine );
        }
276 277
        switch(header.elf.type)
        {
278 279
        case 2: info->type = BINARY_UNIX_EXE; break;
        case 3: info->type = BINARY_UNIX_LIB; break;
280
        }
281 282 283 284 285 286 287 288 289
        switch(header.elf.machine)
        {
        case 3:   info->arch = IMAGE_FILE_MACHINE_I386; break;
        case 20:  info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
        case 40:  info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
        case 50:  info->arch = IMAGE_FILE_MACHINE_IA64; break;
        case 62:  info->arch = IMAGE_FILE_MACHINE_AMD64; break;
        case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
        }
290
    }
291
    /* Mach-o File with Endian set to Big Endian or Little Endian */
292 293
    else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
             header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
294
    {
295
        if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
296
        if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
297 298 299 300
        {
            header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
            header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
        }
301 302
        switch(header.macho.filetype)
        {
303 304
        case 2: info->type = BINARY_UNIX_EXE; break;
        case 8: info->type = BINARY_UNIX_LIB; break;
305
        }
306 307 308 309 310 311 312 313
        switch(header.macho.cputype)
        {
        case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
        case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
        case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
        case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
        case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
        }
314
    }
315
    /* Not ELF, try DOS */
316
    else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
317
    {
318 319 320
        union
        {
            IMAGE_OS2_HEADER os2;
321
            IMAGE_NT_HEADERS32 nt;
322 323
        } ext_header;

324 325 326 327 328 329 330
        /* We do have a DOS image so we will now try to seek into
         * the file by the amount indicated by the field
         * "Offset to extended header" and read in the
         * "magic" field information at that location.
         * This will tell us if there is more header information
         * to read or not.
         */
331
        info->type = BINARY_DOS;
332
        info->arch = IMAGE_FILE_MACHINE_I386;
333 334
        if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
        if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
335 336 337 338

        /* Reading the magic field succeeded so
         * we will try to determine what type it is.
         */
339
        if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
340
        {
341
            if (len >= sizeof(ext_header.nt.FileHeader))
342
            {
343 344 345
                static const char fakedll_signature[] = "Wine placeholder DLL";
                char buffer[sizeof(fakedll_signature)];

346
                info->type = BINARY_PE;
347
                info->arch = ext_header.nt.FileHeader.Machine;
348 349
                if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
                    info->flags |= BINARY_FLAG_DLL;
350 351
                if (len < sizeof(ext_header.nt))  /* clear remaining part of header if missing */
                    memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
352 353 354
                switch (ext_header.nt.OptionalHeader.Magic)
                {
                case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
355 356
                    info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
                    info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
357
                                                     ext_header.nt.OptionalHeader.SizeOfImage);
358
                    break;
359
                case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
360 361
                    info->flags |= BINARY_FLAG_64BIT;
                    break;
362
                }
363 364 365 366 367 368 369 370 371

                if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
                    SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
                    ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
                    len == sizeof(fakedll_signature) &&
                    !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
                {
                    info->flags |= BINARY_FLAG_FAKEDLL;
                }
372 373
            }
        }
374
        else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
375 376 377 378 379 380
        {
            /* This is a Windows executable (NE) header.  This can
             * mean either a 16-bit OS/2 or a 16-bit Windows or even a
             * DOS program (running under a DOS extender).  To decide
             * which, we'll have to read the NE header.
             */
381
            if (len >= sizeof(ext_header.os2))
382
            {
383
                if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
384
                switch ( ext_header.os2.ne_exetyp )
385
                {
386 387 388 389 390
                case 1:  info->type = BINARY_OS216; break; /* OS/2 */
                case 2:  info->type = BINARY_WIN16; break; /* Windows */
                case 3:  info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
                case 4:  info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
                case 5:  info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
391
                /* other types, e.g. 0 is: "unknown" */
392
                default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
393 394 395 396 397 398 399
                }
            }
        }
    }
}

/***********************************************************************
400
 *             GetBinaryTypeW                     [KERNEL32.@]
401
 *
Jon Griffiths's avatar
Jon Griffiths committed
402 403 404 405 406 407 408 409 410 411 412
 * Determine whether a file is executable, and if so, what kind.
 *
 * PARAMS
 *  lpApplicationName [I] Path of the file to check
 *  lpBinaryType      [O] Destination for the binary type
 *
 * RETURNS
 *  TRUE, if the file is an executable, in which case lpBinaryType is set.
 *  FALSE, if the file is not an executable or if the function fails.
 *
 * NOTES
413
 *  The type of executable is a property that determines which subsystem an
Jon Griffiths's avatar
Jon Griffiths committed
414 415 416
 *  executable file runs under. lpBinaryType can be set to one of the following
 *  values:
 *   SCS_32BIT_BINARY: A Win32 based application
417
 *   SCS_64BIT_BINARY: A Win64 based application
Jon Griffiths's avatar
Jon Griffiths committed
418 419 420 421 422 423 424 425 426
 *   SCS_DOS_BINARY: An MS-Dos based application
 *   SCS_WOW_BINARY: A Win16 based application
 *   SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
 *   SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
 *   SCS_OS216_BINARY: A 16bit OS/2 based application
 *
 *  To find the binary type, this function reads in the files header information.
 *  If extended header information is not present it will assume that the file
 *  is a DOS executable. If extended header information is present it will
427
 *  determine if the file is a 16, 32 or 64 bit Windows executable by checking the
Jon Griffiths's avatar
Jon Griffiths committed
428 429 430 431
 *  flags in the header.
 *
 *  ".com" and ".pif" files are only recognized by their file name extension,
 *  as per native Windows.
Alexandre Julliard's avatar
Alexandre Julliard committed
432
 */
433
BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
434 435
{
    BOOL ret = FALSE;
436
    HANDLE hfile;
437
    struct binary_info binary_info;
Alexandre Julliard's avatar
Alexandre Julliard committed
438

439
    TRACE("%s\n", debugstr_w(lpApplicationName) );
Alexandre Julliard's avatar
Alexandre Julliard committed
440

441 442 443 444 445 446 447
    /* Sanity check.
     */
    if ( lpApplicationName == NULL || lpBinaryType == NULL )
        return FALSE;

    /* Open the file indicated by lpApplicationName for reading.
     */
448
    hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
449
                         NULL, OPEN_EXISTING, 0, 0 );
450
    if ( hfile == INVALID_HANDLE_VALUE )
451 452 453 454
        return FALSE;

    /* Check binary type
     */
455 456
    MODULE_get_binary_info( hfile, &binary_info );
    switch (binary_info.type)
457 458
    {
    case BINARY_UNKNOWN:
459 460 461 462 463
    {
        static const WCHAR comW[] = { '.','C','O','M',0 };
        static const WCHAR pifW[] = { '.','P','I','F',0 };
        const WCHAR *ptr;

464
        /* try to determine from file name */
465
        ptr = strrchrW( lpApplicationName, '.' );
466
        if (!ptr) break;
467
        if (!strcmpiW( ptr, comW ))
468 469 470 471
        {
            *lpBinaryType = SCS_DOS_BINARY;
            ret = TRUE;
        }
472
        else if (!strcmpiW( ptr, pifW ))
473 474 475 476 477
        {
            *lpBinaryType = SCS_PIF_BINARY;
            ret = TRUE;
        }
        break;
478
    }
479
    case BINARY_PE:
480
        *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        ret = TRUE;
        break;
    case BINARY_WIN16:
        *lpBinaryType = SCS_WOW_BINARY;
        ret = TRUE;
        break;
    case BINARY_OS216:
        *lpBinaryType = SCS_OS216_BINARY;
        ret = TRUE;
        break;
    case BINARY_DOS:
        *lpBinaryType = SCS_DOS_BINARY;
        ret = TRUE;
        break;
    case BINARY_UNIX_EXE:
    case BINARY_UNIX_LIB:
        ret = FALSE;
        break;
    }
500 501 502

    CloseHandle( hfile );
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
503 504
}

505
/***********************************************************************
506 507
 *             GetBinaryTypeA                     [KERNEL32.@]
 *             GetBinaryType                      [KERNEL32.@]
508 509
 *
 * See GetBinaryTypeW.
510
 */
511
BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
512
{
513 514
    ANSI_STRING app_nameA;
    NTSTATUS status;
515

516
    TRACE("%s\n", debugstr_a(lpApplicationName));
517 518 519 520 521 522

    /* Sanity check.
     */
    if ( lpApplicationName == NULL || lpBinaryType == NULL )
        return FALSE;

523 524 525 526 527
    RtlInitAnsiString(&app_nameA, lpApplicationName);
    status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
                                          &app_nameA, FALSE);
    if (!status)
        return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
528

529 530
    SetLastError(RtlNtStatusToDosError(status));
    return FALSE;
531
}
Alexandre Julliard's avatar
Alexandre Julliard committed
532

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
/***********************************************************************
 *              GetModuleHandleExA         (KERNEL32.@)
 */
BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
{
    WCHAR *nameW;

    if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
        return GetModuleHandleExW( flags, (LPCWSTR)name, module );

    if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
    return GetModuleHandleExW( flags, nameW, module );
}

/***********************************************************************
 *              GetModuleHandleExW         (KERNEL32.@)
 */
BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
{
    NTSTATUS status = STATUS_SUCCESS;
    HMODULE ret;
554
    ULONG_PTR magic;
555
    BOOL lock;
556

557 558 559 560 561 562
    if (!module)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return FALSE;
    }

563
    /* if we are messing with the refcount, grab the loader lock */
564 565
    lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
    if (lock)
566
        LdrLockLoaderLock( 0, NULL, &magic );
567 568 569 570 571 572 573 574 575 576 577 578 579 580

    if (!name)
    {
        ret = NtCurrentTeb()->Peb->ImageBaseAddress;
    }
    else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
    {
        void *dummy;
        if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
    }
    else
    {
        UNICODE_STRING wstr;
        RtlInitUnicodeString( &wstr, name );
581
        status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
582 583
    }

584
    if (status == STATUS_SUCCESS)
585
    {
586
        if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
587
            LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
588 589
        else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
            LdrAddRefDll( 0, ret );
590
    }
591
    else SetLastError( RtlNtStatusToDosError( status ) );
592

593
    if (lock)
594
        LdrUnlockLoaderLock( 0, magic );
595

596 597 598
    if (status == STATUS_SUCCESS) *module = ret;
    else *module = NULL;

599
    return (status == STATUS_SUCCESS);
600
}
Alexandre Julliard's avatar
Alexandre Julliard committed
601

Alexandre Julliard's avatar
Alexandre Julliard committed
602
/***********************************************************************
603
 *              GetModuleHandleA         (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
604 605 606 607 608 609 610 611 612
 *
 * Get the handle of a dll loaded into the process address space.
 *
 * PARAMS
 *  module [I] Name of the dll
 *
 * RETURNS
 *  Success: A handle to the loaded dll.
 *  Failure: A NULL handle. Use GetLastError() to determine the cause.
Alexandre Julliard's avatar
Alexandre Julliard committed
613
 */
614
HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
Alexandre Julliard's avatar
Alexandre Julliard committed
615
{
616
    HMODULE ret;
617

618
    GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
619
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
620 621
}

622
/***********************************************************************
623
 *		GetModuleHandleW (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
624 625
 *
 * Unicode version of GetModuleHandleA.
626
 */
627
HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
Alexandre Julliard's avatar
Alexandre Julliard committed
628
{
629
    HMODULE ret;
630

631
    GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
632
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
633 634
}

Alexandre Julliard's avatar
Alexandre Julliard committed
635

Alexandre Julliard's avatar
Alexandre Julliard committed
636
/***********************************************************************
637
 *              GetModuleFileNameA      (KERNEL32.@)
638
 *
Jon Griffiths's avatar
Jon Griffiths committed
639 640 641 642 643 644 645
 * Get the file name of a loaded module from its handle.
 *
 * RETURNS
 *  Success: The length of the file name, excluding the terminating NUL.
 *  Failure: 0. Use GetLastError() to determine the cause.
 *
 * NOTES
646
 *  This function always returns the long path of hModule
Andreas Mohr's avatar
Andreas Mohr committed
647
 *  The function doesn't write a terminating '\0' if the buffer is too 
648
 *  small.
Alexandre Julliard's avatar
Alexandre Julliard committed
649
 */
650
DWORD WINAPI GetModuleFileNameA(
Jon Griffiths's avatar
Jon Griffiths committed
651 652 653
	HMODULE hModule,	/* [in] Module handle (32 bit) */
	LPSTR lpFileName,	/* [out] Destination for file name */
        DWORD size )		/* [in] Size of lpFileName in characters */
654
{
655
    LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
656
    DWORD len;
Alexandre Julliard's avatar
Alexandre Julliard committed
657

658
    if (!filenameW)
659
    {
660 661
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return 0;
662
    }
663 664 665
    if ((len = GetModuleFileNameW( hModule, filenameW, size )))
    {
    	len = FILE_name_WtoA( filenameW, len, lpFileName, size );
666 667 668 669
        if (len < size)
            lpFileName[len] = '\0';
        else
            SetLastError( ERROR_INSUFFICIENT_BUFFER );
670
    }
671
    HeapFree( GetProcessHeap(), 0, filenameW );
672
    return len;
673 674
}

Alexandre Julliard's avatar
Alexandre Julliard committed
675
/***********************************************************************
676
 *              GetModuleFileNameW      (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
677 678
 *
 * Unicode version of GetModuleFileNameA.
Alexandre Julliard's avatar
Alexandre Julliard committed
679
 */
680
DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
Alexandre Julliard's avatar
Alexandre Julliard committed
681
{
682 683
    ULONG len = 0;
    ULONG_PTR magic;
684 685 686
    LDR_MODULE *pldr;
    NTSTATUS nts;
    WIN16_SUBSYSTEM_TIB *win16_tib;
687

688
    if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
689
    {
690 691 692
        len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
        memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
        if (len < size) lpFileName[len] = '\0';
693
        goto done;
694 695
    }

696
    LdrLockLoaderLock( 0, NULL, &magic );
697

698 699
    if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
    nts = LdrFindEntryForAddress( hModule, &pldr );
700 701 702 703
    if (nts == STATUS_SUCCESS)
    {
        len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
        memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
704
        if (len < size)
705
        {
706
            lpFileName[len] = '\0';
707 708
            SetLastError( 0 );
        }
709 710
        else
            SetLastError( ERROR_INSUFFICIENT_BUFFER );
711
    }
712
    else SetLastError( RtlNtStatusToDosError( nts ) );
713

714 715
    LdrUnlockLoaderLock( 0, magic );
done:
716 717
    TRACE( "%s\n", debugstr_wn(lpFileName, len) );
    return len;
Alexandre Julliard's avatar
Alexandre Julliard committed
718 719
}

720 721 722 723 724 725

/***********************************************************************
 *           get_dll_system_path
 */
static const WCHAR *get_dll_system_path(void)
{
726
    static WCHAR *cached_path;
727

728
    if (!cached_path)
729
    {
730
        WCHAR *p, *path;
731 732
        int len = 3;

733
        len += 2 * GetSystemDirectoryW( NULL, 0 );
734
        len += GetWindowsDirectoryW( NULL, 0 );
735
        p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
736 737 738 739
        *p++ = '.';
        *p++ = ';';
        GetSystemDirectoryW( p, path + len - p);
        p += strlenW(p);
740 741 742 743 744 745 746
        /* if system directory ends in "32" add 16-bit version too */
        if (p[-2] == '3' && p[-1] == '2')
        {
            *p++ = ';';
            GetSystemDirectoryW( p, path + len - p);
            p += strlenW(p) - 2;
        }
747 748
        *p++ = ';';
        GetWindowsDirectoryW( p, path + len - p);
749
        cached_path = path;
750
    }
751
    return cached_path;
752 753
}

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
/******************************************************************
 *		get_module_path_end
 *
 * Returns the end of the directory component of the module path.
 */
static inline const WCHAR *get_module_path_end(const WCHAR *module)
{
    const WCHAR *p;
    const WCHAR *mod_end = module;
    if (!module) return mod_end;

    if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
    if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
    if (mod_end == module + 2 && module[1] == ':') mod_end++;
    if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;

    return mod_end;
}
772 773

/******************************************************************
774
 *		MODULE_get_dll_load_path
775 776 777 778
 *
 * Compute the load path to use for a given dll.
 * Returned pointer must be freed by caller.
 */
779
WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
780 781 782 783 784 785 786 787 788 789 790 791
{
    static const WCHAR pathW[] = {'P','A','T','H',0};

    const WCHAR *system_path = get_dll_system_path();
    const WCHAR *mod_end = NULL;
    UNICODE_STRING name, value;
    WCHAR *p, *ret;
    int len = 0, path_len = 0;

    /* adjust length for module name */

    if (module)
792 793 794 795
        mod_end = get_module_path_end( module );
    /* if module is NULL or doesn't contain a path, fall back to directory
     * process was loaded from */
    if (module == mod_end)
796
    {
797 798
        module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
        mod_end = get_module_path_end( module );
799
    }
800 801
    len += (mod_end - module) + 1;

802 803 804 805 806 807 808 809 810 811 812
    len += strlenW( system_path ) + 2;

    /* get the PATH variable */

    RtlInitUnicodeString( &name, pathW );
    value.Length = 0;
    value.MaximumLength = 0;
    value.Buffer = NULL;
    if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
        path_len = value.Length;

813 814 815
    RtlEnterCriticalSection( &dlldir_section );
    if (dll_directory) len += strlenW(dll_directory) + 1;
    if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
816
    {
817 818 819 820 821 822 823 824 825 826 827 828
        if (module)
        {
            memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
            p += (mod_end - module);
            *p++ = ';';
        }
        if (dll_directory)
        {
            strcpyW( p, dll_directory );
            p += strlenW(p);
            *p++ = ';';
        }
829
    }
830 831 832
    RtlLeaveCriticalSection( &dlldir_section );
    if (!ret) return NULL;

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    strcpyW( p, system_path );
    p += strlenW(p);
    *p++ = ';';
    value.Buffer = p;
    value.MaximumLength = path_len;

    while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
    {
        WCHAR *new_ptr;

        /* grow the buffer and retry */
        path_len = value.Length;
        if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
        {
            HeapFree( GetProcessHeap(), 0, ret );
            return NULL;
        }
        value.Buffer = new_ptr + (value.Buffer - ret);
        value.MaximumLength = path_len;
        ret = new_ptr;
    }
    value.Buffer[value.Length / sizeof(WCHAR)] = 0;
    return ret;
}


859 860
/******************************************************************
 *		load_library_as_datafile
861
 */
862
static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
863
{
864 865 866
    static const WCHAR dotDLL[] = {'.','d','l','l',0};

    WCHAR filenameW[MAX_PATH];
867 868
    HANDLE hFile = INVALID_HANDLE_VALUE;
    HANDLE mapping;
869
    HMODULE module;
870

871
    *hmod = 0;
872

873
    if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
874
                     filenameW, NULL ))
875
    {
876 877
        hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
                             NULL, OPEN_EXISTING, 0, 0 );
878 879
    }
    if (hFile == INVALID_HANDLE_VALUE) return FALSE;
880 881

    mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
882
    CloseHandle( hFile );
883 884 885 886 887
    if (!mapping) return FALSE;

    module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
    CloseHandle( mapping );
    if (!module) return FALSE;
888

889 890 891 892 893 894 895 896
    /* make sure it's a valid PE file */
    if (!RtlImageNtHeader(module))
    {
        UnmapViewOfFile( module );
        return FALSE;
    }
    *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
    return TRUE;
897 898
}

899 900 901 902 903 904 905 906 907 908 909

/******************************************************************
 *		load_library
 *
 * Helper for LoadLibraryExA/W.
 */
static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
{
    NTSTATUS nts;
    HMODULE hModule;
    WCHAR *load_path;
910 911 912 913
    static const DWORD unsupported_flags = 
        LOAD_IGNORE_CODE_AUTHZ_LEVEL |
        LOAD_LIBRARY_AS_IMAGE_RESOURCE |
        LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
914 915 916 917 918 919
        LOAD_LIBRARY_REQUIRE_SIGNED_TARGET |
        LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
        LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
        LOAD_LIBRARY_SEARCH_USER_DIRS |
        LOAD_LIBRARY_SEARCH_SYSTEM32 |
        LOAD_LIBRARY_SEARCH_DEFAULT_DIRS;
920 921

    if( flags & unsupported_flags)
922
        FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
923

924 925
    load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );

926 927
    if (flags & LOAD_LIBRARY_AS_DATAFILE)
    {
928
        ULONG_PTR magic;
929 930

        LdrLockLoaderLock( 0, NULL, &magic );
931
        if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
932 933 934 935 936 937 938
        {
            LdrAddRefDll( 0, hModule );
            LdrUnlockLoaderLock( 0, magic );
            goto done;
        }
        LdrUnlockLoaderLock( 0, magic );

939 940 941
        /* The method in load_library_as_datafile allows searching for the
         * 'native' libraries only
         */
942
        if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
943 944 945 946 947 948 949 950
        flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
        /* Fallback to normal behaviour */
    }

    nts = LdrLoadDll( load_path, flags, libname, &hModule );
    if (nts != STATUS_SUCCESS)
    {
        hModule = 0;
951 952 953 954
        if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
            SetLastError( ERROR_DLL_NOT_FOUND );
        else
            SetLastError( RtlNtStatusToDosError( nts ) );
955
    }
956 957
done:
    HeapFree( GetProcessHeap(), 0, load_path );
958 959 960 961
    return hModule;
}


962 963
/******************************************************************
 *		LoadLibraryExA          (KERNEL32.@)
964
 *
Jon Griffiths's avatar
Jon Griffiths committed
965 966 967 968 969 970 971 972 973 974 975 976
 * Load a dll file into the process address space.
 *
 * PARAMS
 *  libname [I] Name of the file to load
 *  hfile   [I] Reserved, must be 0.
 *  flags   [I] Flags for loading the dll
 *
 * RETURNS
 *  Success: A handle to the loaded dll.
 *  Failure: A NULL handle. Use GetLastError() to determine the cause.
 *
 * NOTES
977 978 979
 * The HFILE parameter is not used and marked reserved in the SDK. I can
 * only guess that it should force a file to be mapped, but I rather
 * ignore the parameter because it would be extremely difficult to
980
 * integrate this with different types of module representations.
981
 */
982
HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
Alexandre Julliard's avatar
Alexandre Julliard committed
983
{
984
    WCHAR *libnameW;
985

986 987
    if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
    return LoadLibraryExW( libnameW, hfile, flags );
988
}
989

990 991
/***********************************************************************
 *           LoadLibraryExW       (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
992 993
 *
 * Unicode version of LoadLibraryExA.
994
 */
995
HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
996 997
{
    UNICODE_STRING      wstr;
998
    HMODULE             res;
999

1000 1001 1002 1003 1004 1005
    if (!libnameW)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }
    RtlInitUnicodeString( &wstr, libnameW );
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
        return load_library( &wstr, flags );

    /* Library name has trailing spaces */
    RtlCreateUnicodeString( &wstr, libnameW );
    while (wstr.Length > sizeof(WCHAR) &&
           wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
    {
        wstr.Length -= sizeof(WCHAR);
    }
    wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
    res = load_library( &wstr, flags );
    RtlFreeUnicodeString( &wstr );
    return res;
Alexandre Julliard's avatar
Alexandre Julliard committed
1020 1021 1022
}

/***********************************************************************
1023
 *           LoadLibraryA         (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
 *
 * Load a dll file into the process address space.
 *
 * PARAMS
 *  libname [I] Name of the file to load
 *
 * RETURNS
 *  Success: A handle to the loaded dll.
 *  Failure: A NULL handle. Use GetLastError() to determine the cause.
 *
 * NOTES
 * See LoadLibraryExA().
Alexandre Julliard's avatar
Alexandre Julliard committed
1036
 */
1037
HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1038 1039
{
    return LoadLibraryExA(libname, 0, 0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1040 1041 1042
}

/***********************************************************************
1043
 *           LoadLibraryW         (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1044 1045
 *
 * Unicode version of LoadLibraryA.
Alexandre Julliard's avatar
Alexandre Julliard committed
1046
 */
1047
HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
Alexandre Julliard's avatar
Alexandre Julliard committed
1048
{
1049
    return LoadLibraryExW(libnameW, 0, 0);
Alexandre Julliard's avatar
Alexandre Julliard committed
1050 1051
}

1052
/***********************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
1053
 *           FreeLibrary   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1054 1055 1056 1057 1058 1059 1060 1061 1062
 *
 * Free a dll loaded into the process address space.
 *
 * PARAMS
 *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
 *
 * RETURNS
 *  Success: TRUE. The dll is removed if it is not still in use.
 *  Failure: FALSE. Use GetLastError() to determine the cause.
1063
 */
1064
BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1065
{
1066 1067
    BOOL                retv = FALSE;
    NTSTATUS            nts;
1068

1069 1070 1071 1072 1073 1074
    if (!hLibModule)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

1075 1076 1077 1078
    if ((ULONG_PTR)hLibModule & 1)
    {
        /* this is a LOAD_LIBRARY_AS_DATAFILE module */
        char *ptr = (char *)hLibModule - 1;
1079
        return UnmapViewOfFile( ptr );
1080
    }
1081

1082 1083
    if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
    else SetLastError( RtlNtStatusToDosError( nts ) );
1084

1085 1086
    return retv;
}
1087

Alexandre Julliard's avatar
Alexandre Julliard committed
1088
/***********************************************************************
1089
 *           GetProcAddress   		(KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
 *
 * Find the address of an exported symbol in a loaded dll.
 *
 * PARAMS
 *  hModule  [I] Handle to the dll returned by LoadLibraryA().
 *  function [I] Name of the symbol, or an integer ordinal number < 16384
 *
 * RETURNS
 *  Success: A pointer to the symbol in the process address space.
 *  Failure: NULL. Use GetLastError() to determine the cause.
Alexandre Julliard's avatar
Alexandre Julliard committed
1100
 */
1101
FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
Alexandre Julliard's avatar
Alexandre Julliard committed
1102
{
1103 1104 1105
    NTSTATUS    nts;
    FARPROC     fp;

1106 1107
    if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;

1108
    if ((ULONG_PTR)function >> 16)
1109 1110 1111 1112 1113 1114 1115
    {
        ANSI_STRING     str;

        RtlInitAnsiString( &str, function );
        nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
    }
    else
1116
        nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1117 1118 1119 1120 1121 1122
    if (nts != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError( nts ) );
        fp = NULL;
    }
    return fp;
Alexandre Julliard's avatar
Alexandre Julliard committed
1123 1124
}

1125 1126 1127 1128 1129 1130 1131
/***********************************************************************
 *           DelayLoadFailureHook  (KERNEL32.@)
 */
FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
{
    ULONG_PTR args[2];

1132 1133 1134 1135
    if ((ULONG_PTR)function >> 16)
        ERR( "failed to delay load %s.%s\n", name, function );
    else
        ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1136 1137 1138 1139 1140
    args[0] = (ULONG_PTR)name;
    args[1] = (ULONG_PTR)function;
    RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
    return NULL;
}
1141

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
typedef struct {
    HANDLE process;
    PLIST_ENTRY head, current;
    LDR_MODULE ldr_module;
} MODULE_ITERATOR;

static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
{
    PROCESS_BASIC_INFORMATION pbi;
    PPEB_LDR_DATA ldr_data;
    NTSTATUS status;

    /* Get address of PEB */
    status = NtQueryInformationProcess(process, ProcessBasicInformation,
                                       &pbi, sizeof(pbi), NULL);
    if (status != STATUS_SUCCESS)
    {
        SetLastError(RtlNtStatusToDosError(status));
        return FALSE;
    }

    /* Read address of LdrData from PEB */
    if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
                           &ldr_data, sizeof(ldr_data), NULL))
        return FALSE;

    /* Read address of first module from LdrData */
    if (!ReadProcessMemory(process,
                           &ldr_data->InLoadOrderModuleList.Flink,
                           &iter->current, sizeof(iter->current), NULL))
        return FALSE;

    iter->head = &ldr_data->InLoadOrderModuleList;
    iter->process = process;

    return TRUE;
}

static int module_iterator_next(MODULE_ITERATOR *iter)
{
    if (iter->current == iter->head)
        return 0;

    if (!ReadProcessMemory(iter->process,
                           CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
                           &iter->ldr_module, sizeof(iter->ldr_module), NULL))
         return -1;

    iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
    return 1;
}

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
{
    MODULE_ITERATOR iter;
    INT ret;

    if (!init_module_iterator(&iter, process))
        return FALSE;

    while ((ret = module_iterator_next(&iter)) > 0)
        /* When hModule is NULL we return the process image - which will be
         * the first module since our iterator uses InLoadOrderModuleList */
        if (!module || module == iter.ldr_module.BaseAddress)
        {
            *ldr_module = iter.ldr_module;
            return TRUE;
        }

    if (ret == 0)
        SetLastError(ERROR_INVALID_HANDLE);

    return FALSE;
}

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
/***********************************************************************
 *           K32EnumProcessModules (KERNEL32.@)
 *
 * NOTES
 *  Returned list is in load order.
 */
BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
                                  DWORD cb, DWORD *needed)
{
    MODULE_ITERATOR iter;
    INT ret;

    if (!init_module_iterator(&iter, process))
        return FALSE;

1232
    if ((cb && !lphModule) || !needed)
1233 1234 1235 1236 1237
    {
        SetLastError(ERROR_NOACCESS);
        return FALSE;
    }

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    *needed = 0;

    while ((ret = module_iterator_next(&iter)) > 0)
    {
        if (cb >= sizeof(HMODULE))
        {
            *lphModule++ = iter.ldr_module.BaseAddress;
            cb -= sizeof(HMODULE);
        }
        *needed += sizeof(HMODULE);
    }

    return ret == 0;
}

1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
/***********************************************************************
 *           K32EnumProcessModulesEx (KERNEL32.@)
 *
 * NOTES
 *  Returned list is in load order.
 */
BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
                                    DWORD cb, DWORD *needed, DWORD filter)
{
    FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
          process, lphModule, cb, needed, filter);
    return K32EnumProcessModules(process, lphModule, cb, needed);
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
/***********************************************************************
 *           K32GetModuleBaseNameW (KERNEL32.@)
 */
DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
                                   LPWSTR base_name, DWORD size)
{
    LDR_MODULE ldr_module;

    if (!get_ldr_module(process, module, &ldr_module))
        return 0;

    size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
    if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
                           base_name, size * sizeof(WCHAR), NULL))
        return 0;

    base_name[size] = 0;
    return size;
}

/***********************************************************************
 *           K32GetModuleBaseNameA (KERNEL32.@)
 */
DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
                                   LPSTR base_name, DWORD size)
{
    WCHAR *base_name_w;
    DWORD len, ret = 0;

    if(!base_name || !size) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
    if(!base_name_w)
        return 0;

    len = K32GetModuleBaseNameW(process, module, base_name_w, size);
    TRACE("%d, %s\n", len, debugstr_w(base_name_w));
    if (len)
    {
        ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
                                  base_name, size, NULL, NULL);
        if (ret < size) base_name[ret] = 0;
    }
    HeapFree(GetProcessHeap(), 0, base_name_w);
    return ret;
}
1316

1317 1318 1319 1320 1321 1322 1323
/***********************************************************************
 *           K32GetModuleFileNameExW (KERNEL32.@)
 */
DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
                                     LPWSTR file_name, DWORD size)
{
    LDR_MODULE ldr_module;
1324 1325 1326
    DWORD len;

    if (!size) return 0;
1327 1328 1329 1330

    if(!get_ldr_module(process, module, &ldr_module))
        return 0;

1331
    len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1332
    if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1333
                           file_name, min( len, size ) * sizeof(WCHAR), NULL))
1334 1335
        return 0;

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    if (len < size)
    {
        file_name[len] = 0;
        return len;
    }
    else
    {
        file_name[size - 1] = 0;
        return size;
    }
1346 1347 1348 1349 1350 1351 1352 1353 1354
}

/***********************************************************************
 *           K32GetModuleFileNameExA (KERNEL32.@)
 */
DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
                                     LPSTR file_name, DWORD size)
{
    WCHAR *ptr;
1355
    DWORD len;
1356 1357 1358

    TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);

1359 1360 1361 1362 1363
    if (!file_name || !size)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }
1364 1365 1366

    if ( process == GetCurrentProcess() )
    {
1367
        len = GetModuleFileNameA( module, file_name, size );
1368 1369 1370 1371 1372 1373
        if (size) file_name[size - 1] = '\0';
        return len;
    }

    if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;

1374 1375
    len = K32GetModuleFileNameExW(process, module, ptr, size);
    if (!len)
1376 1377 1378 1379 1380 1381
    {
        file_name[0] = '\0';
    }
    else
    {
        if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1382
        {
1383
            file_name[size - 1] = 0;
1384 1385 1386
            len = size;
        }
        else if (len < size) len = strlen( file_name );
1387 1388 1389
    }

    HeapFree(GetProcessHeap(), 0, ptr);
1390
    return len;
1391 1392
}

1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
/***********************************************************************
 *           K32GetModuleInformation (KERNEL32.@)
 */
BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
                                    MODULEINFO *modinfo, DWORD cb)
{
    LDR_MODULE ldr_module;

    if (cb < sizeof(MODULEINFO))
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

    if (!get_ldr_module(process, module, &ldr_module))
        return FALSE;

    modinfo->lpBaseOfDll = ldr_module.BaseAddress;
    modinfo->SizeOfImage = ldr_module.SizeOfImage;
    modinfo->EntryPoint  = ldr_module.EntryPoint;
    return TRUE;
}

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
#ifdef __i386__

/***********************************************************************
 *           __wine_dll_register_16 (KERNEL32.@)
 *
 * No longer used.
 */
void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
{
    ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
}


/***********************************************************************
 *           __wine_dll_unregister_16 (KERNEL32.@)
 *
 * No longer used.
 */
void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
{
}

#endif