loader.c 114 KB
Newer Older
1
/*
2 3
 * Loader functions
 *
4
 * Copyright 1995, 2003 Alexandre Julliard
5
 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21
 */

Alexandre Julliard's avatar
Alexandre Julliard committed
22 23 24
#include "config.h"
#include "wine/port.h"

25
#include <assert.h>
26
#include <stdarg.h>
27 28 29
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif
30

31 32
#include "ntstatus.h"
#define WIN32_NO_STATUS
33
#define NONAMELESSUNION
34
#include "windef.h"
35
#include "winnt.h"
36
#include "winternl.h"
37
#include "delayloadhandler.h"
38

39
#include "wine/exception.h"
40
#include "wine/library.h"
41
#include "wine/unicode.h"
42
#include "wine/debug.h"
43 44
#include "wine/server.h"
#include "ntdll_misc.h"
45
#include "ddk/wdm.h"
46

47 48
WINE_DEFAULT_DEBUG_CHANNEL(module);
WINE_DECLARE_DEBUG_CHANNEL(relay);
49
WINE_DECLARE_DEBUG_CHANNEL(snoop);
50
WINE_DECLARE_DEBUG_CHANNEL(loaddll);
51
WINE_DECLARE_DEBUG_CHANNEL(imports);
52
WINE_DECLARE_DEBUG_CHANNEL(pid);
53

54 55 56 57 58 59
#ifdef _WIN64
#define DEFAULT_SECURITY_COOKIE_64  (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
#endif
#define DEFAULT_SECURITY_COOKIE_32  0xbb40e64e
#define DEFAULT_SECURITY_COOKIE_16  (DEFAULT_SECURITY_COOKIE_32 >> 16)

60 61 62 63
/* we don't want to include winuser.h */
#define RT_MANIFEST                         ((ULONG_PTR)24)
#define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)

64 65
typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);

66
static BOOL process_detaching = FALSE;  /* set on process detach to avoid deadlocks with thread detach */
67
static int free_lib_count;   /* recursion depth of LdrUnloadDll calls */
68

69 70 71 72 73
static const char * const reason_names[] =
{
    "PROCESS_DETACH",
    "PROCESS_ATTACH",
    "THREAD_ATTACH",
74 75 76
    "THREAD_DETACH",
    NULL, NULL, NULL, NULL,
    "WINE_PREATTACH"
77 78
};

79 80 81
static const WCHAR dllW[] = {'.','d','l','l',0};

/* internal representation of 32bit modules. per process. */
82
typedef struct _wine_modref
83 84 85 86
{
    LDR_MODULE            ldr;
    int                   nDeps;
    struct _wine_modref **deps;
87
} WINE_MODREF;
88

89 90 91 92 93
/* info about the current builtin dll load */
/* used to keep track of things across the register_dll constructor call */
struct builtin_load_info
{
    const WCHAR *load_path;
94
    const WCHAR *filename;
95 96 97 98
    NTSTATUS     status;
    WINE_MODREF *wm;
};

99 100
static struct builtin_load_info default_load_info;
static struct builtin_load_info *builtin_load_info = &default_load_info;
101

102 103 104 105 106 107
struct start_params
{
    void                   *kernel_start;
    LPTHREAD_START_ROUTINE  entry;
};

108
static HANDLE main_exe_file;
109
static UINT tls_module_count;      /* number of modules with TLS directory */
110
static IMAGE_TLS_DIRECTORY *tls_dirs;  /* array of TLS directories */
111
LIST_ENTRY tls_links = { &tls_links, &tls_links };
112

113 114
static RTL_CRITICAL_SECTION loader_section;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
115 116 117
{
    0, 0, &loader_section,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
118
      0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
119
};
120
static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
121

122
static WINE_MODREF *cached_modref;
123
static WINE_MODREF *current_modref;
124
static WINE_MODREF *last_failed_modref;
125

126
static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
127
static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
128 129
static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
                                    DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
Eric Pouech's avatar
Eric Pouech committed
130
static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
131
                                  DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
132 133

/* convert PE image VirtualAddress to Real Address */
134
static inline void *get_rva( HMODULE module, DWORD va )
135 136 137
{
    return (void *)((char *)module + va);
}
138

139
/* check whether the file name contains a path */
140
static inline BOOL contains_path( LPCWSTR name )
141 142 143 144 145
{
    return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
}

/* convert from straight ASCII to Unicode without depending on the current codepage */
146
static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
147 148 149 150
{
    while (len--) *dst++ = (unsigned char)*src++;
}

151 152 153 154 155

/*************************************************************************
 *		call_dll_entry_point
 *
 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
156 157 158
 * their entry point, so we need a small asm wrapper. Testing indicates
 * that only modifying esi leads to a crash, so use this one to backup
 * ebp while running the dll entry proc.
159 160 161 162 163
 */
#ifdef __i386__
extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
__ASM_GLOBAL_FUNC(call_dll_entry_point,
                  "pushl %ebp\n\t"
164 165
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
166
                  "movl %esp,%ebp\n\t"
167
                  __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
168
                  "pushl %ebx\n\t"
169
                  __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
170 171 172 173 174 175
                  "pushl %esi\n\t"
                  __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
                  "pushl %edi\n\t"
                  __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
                  "movl %ebp,%esi\n\t"
                  __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
176 177 178 179 180
                  "pushl 20(%ebp)\n\t"
                  "pushl 16(%ebp)\n\t"
                  "pushl 12(%ebp)\n\t"
                  "movl 8(%ebp),%eax\n\t"
                  "call *%eax\n\t"
181 182 183 184 185 186 187
                  "movl %esi,%ebp\n\t"
                  __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
                  "leal -12(%ebp),%esp\n\t"
                  "popl %edi\n\t"
                  __ASM_CFI(".cfi_same_value %edi\n\t")
                  "popl %esi\n\t"
                  __ASM_CFI(".cfi_same_value %esi\n\t")
188
                  "popl %ebx\n\t"
189
                  __ASM_CFI(".cfi_same_value %ebx\n\t")
190
                  "popl %ebp\n\t"
191 192
                  __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
                  __ASM_CFI(".cfi_same_value %ebp\n\t")
193
                  "ret" )
194 195 196 197 198 199 200 201 202
#else /* __i386__ */
static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
                                         UINT reason, void *reserved )
{
    return proc( module, reason, reserved );
}
#endif /* __i386__ */


203
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
204 205 206 207 208
/*************************************************************************
 *		stub_entry_point
 *
 * Entry point for stub functions.
 */
209
static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
210 211 212 213 214 215
{
    EXCEPTION_RECORD rec;

    rec.ExceptionCode           = EXCEPTION_WINE_STUB;
    rec.ExceptionFlags          = EH_NONCONTINUABLE;
    rec.ExceptionRecord         = NULL;
216
    rec.ExceptionAddress        = ret_addr;
217
    rec.NumberParameters        = 2;
218 219
    rec.ExceptionInformation[0] = (ULONG_PTR)dll;
    rec.ExceptionInformation[1] = (ULONG_PTR)name;
220 221 222 223
    for (;;) RtlRaiseException( &rec );
}


224
#include "pshpack1.h"
225
#ifdef __i386__
226 227 228 229 230 231
struct stub
{
    BYTE        pushl1;     /* pushl $name */
    const char *name;
    BYTE        pushl2;     /* pushl $dll */
    const char *dll;
232
    BYTE        call;       /* call stub_entry_point */
233 234
    DWORD       entry;
};
235 236 237 238 239 240 241 242 243 244 245 246 247
#elif defined(__arm__)
struct stub
{
    BYTE ldr_r0[4];        /* ldr r0, $dll */
    BYTE mov_pc_pc1[4];    /* mov pc,pc */
    const char *dll;
    BYTE ldr_r1[4];        /* ldr r1, $name */
    BYTE mov_pc_pc2[4];    /* mov pc,pc */
    const char *name;
    BYTE mov_r2_lr[4];     /* mov r2, lr */
    BYTE ldr_pc_pc[4];     /* ldr pc, [pc, #-4] */
    const void* entry;
};
248 249 250 251 252 253 254 255 256 257 258 259 260
#else
struct stub
{
    BYTE movq_rdi[2];      /* movq $dll,%rdi */
    const char *dll;
    BYTE movq_rsi[2];      /* movq $name,%rsi */
    const char *name;
    BYTE movq_rsp_rdx[4];  /* movq (%rsp),%rdx */
    BYTE movq_rax[2];      /* movq $entry, %rax */
    const void* entry;
    BYTE jmpq_rax[2];      /* jmp %rax */
};
#endif
261
#include "poppack.h"
262 263 264 265 266 267

/*************************************************************************
 *		allocate_stub
 *
 * Allocate a stub entry point.
 */
268
static ULONG_PTR allocate_stub( const char *dll, const char *name )
269 270 271 272 273 274
{
#define MAX_SIZE 65536
    static struct stub *stubs;
    static unsigned int nb_stubs;
    struct stub *stub;

275
    if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
276 277 278

    if (!stubs)
    {
279
        SIZE_T size = MAX_SIZE;
280
        if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
281
                                     MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
282
            return 0xdeadbeef;
283 284
    }
    stub = &stubs[nb_stubs++];
285
#ifdef __i386__
286 287 288 289
    stub->pushl1    = 0x68;  /* pushl $name */
    stub->name      = name;
    stub->pushl2    = 0x68;  /* pushl $dll */
    stub->dll       = dll;
290
    stub->call      = 0xe8;  /* call stub_entry_point */
291
    stub->entry     = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
#elif defined(__arm__)
    stub->ldr_r0[0]     = 0x00;   /* ldr r0, $dll */
    stub->ldr_r0[1]     = 0x00;
    stub->ldr_r0[2]     = 0x9f;
    stub->ldr_r0[3]     = 0xe5;
    stub->mov_pc_pc1[0] = 0x0f;   /* mov pc,pc */
    stub->mov_pc_pc1[1] = 0xf0;
    stub->mov_pc_pc1[2] = 0xa0;
    stub->mov_pc_pc1[3] = 0xe1;
    stub->dll           = dll;
    stub->ldr_r1[0]     = 0x00;   /* ldr r1, $name */
    stub->ldr_r1[1]     = 0x10;
    stub->ldr_r1[2]     = 0x9f;
    stub->ldr_r1[3]     = 0xe5;
    stub->mov_pc_pc2[0] = 0x0f;   /* mov pc,pc */
    stub->mov_pc_pc2[1] = 0xf0;
    stub->mov_pc_pc2[2] = 0xa0;
    stub->mov_pc_pc2[3] = 0xe1;
    stub->name          = name;
    stub->mov_r2_lr[0]  = 0x0e;   /* mov r2, lr */
    stub->mov_r2_lr[1]  = 0x20;
    stub->mov_r2_lr[2]  = 0xa0;
    stub->mov_r2_lr[3]  = 0xe1;
    stub->ldr_pc_pc[0]  = 0x04;   /* ldr pc, [pc, #-4] */
    stub->ldr_pc_pc[1]  = 0xf0;
    stub->ldr_pc_pc[2]  = 0x1f;
    stub->ldr_pc_pc[3]  = 0xe5;
    stub->entry         = stub_entry_point;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
#else
    stub->movq_rdi[0]     = 0x48;  /* movq $dll,%rdi */
    stub->movq_rdi[1]     = 0xbf;
    stub->dll             = dll;
    stub->movq_rsi[0]     = 0x48;  /* movq $name,%rsi */
    stub->movq_rsi[1]     = 0xbe;
    stub->name            = name;
    stub->movq_rsp_rdx[0] = 0x48;  /* movq (%rsp),%rdx */
    stub->movq_rsp_rdx[1] = 0x8b;
    stub->movq_rsp_rdx[2] = 0x14;
    stub->movq_rsp_rdx[3] = 0x24;
    stub->movq_rax[0]     = 0x48;  /* movq $entry, %rax */
    stub->movq_rax[1]     = 0xb8;
    stub->entry           = stub_entry_point;
    stub->jmpq_rax[0]     = 0xff;  /* jmp %rax */
    stub->jmpq_rax[1]     = 0xe0;
#endif
337
    return (ULONG_PTR)stub;
338 339 340
}

#else  /* __i386__ */
341
static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
342 343 344
#endif  /* __i386__ */


345
/*************************************************************************
346 347 348 349
 *		get_modref
 *
 * Looks for the referenced HMODULE in the current process
 * The loader_section must be locked while calling this function.
350
 */
351
static WINE_MODREF *get_modref( HMODULE hmod )
352
{
353 354
    PLIST_ENTRY mark, entry;
    PLDR_MODULE mod;
355

356
    if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
357

358 359
    mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
360
    {
361 362 363
        mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
        if (mod->BaseAddress == hmod)
            return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
364
    }
365
    return NULL;
366 367 368
}


369
/**********************************************************************
370
 *	    find_basename_module
371
 *
372
 * Find a module from its base name.
373 374
 * The loader_section must be locked while calling this function
 */
375
static WINE_MODREF *find_basename_module( LPCWSTR name )
376 377 378
{
    PLIST_ENTRY mark, entry;

379 380
    if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
        return cached_modref;
381

382 383
    mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
384
    {
385 386 387 388 389 390
        LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
        if (!strcmpiW( name, mod->BaseDllName.Buffer ))
        {
            cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
            return cached_modref;
        }
391
    }
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    return NULL;
}


/**********************************************************************
 *	    find_fullname_module
 *
 * Find a module from its full path name.
 * The loader_section must be locked while calling this function
 */
static WINE_MODREF *find_fullname_module( LPCWSTR name )
{
    PLIST_ENTRY mark, entry;

    if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
        return cached_modref;
408 409 410 411

    mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
    {
412 413 414 415 416 417
        LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
        if (!strcmpiW( name, mod->FullDllName.Buffer ))
        {
            cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
            return cached_modref;
        }
418
    }
419
    return NULL;
420 421 422
}


423 424 425 426 427 428
/*************************************************************************
 *		find_forwarded_export
 *
 * Find the final function pointer for a forwarded function.
 * The loader_section must be locked while calling this function.
 */
429
static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
430
{
Eric Pouech's avatar
Eric Pouech committed
431
    const IMAGE_EXPORT_DIRECTORY *exports;
432 433
    DWORD exp_size;
    WINE_MODREF *wm;
434
    WCHAR mod_name[32];
435
    const char *end = strrchr(forward, '.');
436 437 438
    FARPROC proc = NULL;

    if (!end) return NULL;
439
    if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
440
    ascii_to_unicode( mod_name, forward, end - forward );
441 442 443 444 445 446
    mod_name[end - forward] = 0;
    if (!strchrW( mod_name, '.' ))
    {
        if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
        memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
    }
447

448
    if (!(wm = find_basename_module( mod_name )))
449
    {
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
        if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
            !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
        {
            if (process_attach( wm, NULL ) != STATUS_SUCCESS)
            {
                LdrUnloadDll( wm->ldr.BaseAddress );
                wm = NULL;
            }
        }

        if (!wm)
        {
            ERR( "module not found for forward '%s' used by %s\n",
                 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
            return NULL;
        }
467 468 469
    }
    if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
                                                 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
470 471 472 473 474 475 476
    {
        const char *name = end + 1;
        if (*name == '#')  /* ordinal */
            proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
        else
            proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
    }
477 478 479

    if (!proc)
    {
480 481 482 483
        ERR("function not found for forward '%s' used by %s."
            " If you are using builtin %s, try using the native one instead.\n",
            forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
            debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
484 485 486 487 488 489 490 491 492 493 494 495
    }
    return proc;
}


/*************************************************************************
 *		find_ordinal_export
 *
 * Find an exported function by ordinal.
 * The exports base must have been subtracted from the ordinal already.
 * The loader_section must be locked while calling this function.
 */
Eric Pouech's avatar
Eric Pouech committed
496
static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
497
                                    DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
498 499
{
    FARPROC proc;
Eric Pouech's avatar
Eric Pouech committed
500
    const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
501 502 503

    if (ordinal >= exports->NumberOfFunctions)
    {
504
        TRACE("	ordinal %d out of range!\n", ordinal + exports->Base );
505 506 507 508 509 510 511
        return NULL;
    }
    if (!functions[ordinal]) return NULL;

    proc = get_rva( module, functions[ordinal] );

    /* if the address falls into the export dir, it's a forward */
Eric Pouech's avatar
Eric Pouech committed
512 513
    if (((const char *)proc >= (const char *)exports) && 
        ((const char *)proc < (const char *)exports + exp_size))
514
        return find_forwarded_export( module, (const char *)proc, load_path );
515

516
    if (TRACE_ON(snoop))
517
    {
518 519
        const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
        proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
520
    }
521
    if (TRACE_ON(relay))
522
    {
523
        const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
524
        proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
525 526 527 528 529 530 531 532 533 534 535
    }
    return proc;
}


/*************************************************************************
 *		find_named_export
 *
 * Find an exported function by name.
 * The loader_section must be locked while calling this function.
 */
Eric Pouech's avatar
Eric Pouech committed
536
static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
537
                                  DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
538
{
Eric Pouech's avatar
Eric Pouech committed
539 540
    const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
    const DWORD *names = get_rva( module, exports->AddressOfNames );
541 542 543 544 545 546 547
    int min = 0, max = exports->NumberOfNames - 1;

    /* first check the hint */
    if (hint >= 0 && hint <= max)
    {
        char *ename = get_rva( module, names[hint] );
        if (!strcmp( ename, name ))
548
            return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
549 550 551 552 553 554 555 556
    }

    /* then do a binary search */
    while (min <= max)
    {
        int res, pos = (min + max) / 2;
        char *ename = get_rva( module, names[pos] );
        if (!(res = strcmp( ename, name )))
557
            return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
558 559 560
        if (res > 0) max = pos - 1;
        else min = pos + 1;
    }
561
    return NULL;
562 563 564 565 566 567 568 569 570 571

}


/*************************************************************************
 *		import_dll
 *
 * Import the dll specified by the given import descriptor.
 * The loader_section must be locked while calling this function.
 */
572
static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
573 574 575 576
{
    NTSTATUS status;
    WINE_MODREF *wmImp;
    HMODULE imp_mod;
Eric Pouech's avatar
Eric Pouech committed
577
    const IMAGE_EXPORT_DIRECTORY *exports;
578
    DWORD exp_size;
Eric Pouech's avatar
Eric Pouech committed
579 580
    const IMAGE_THUNK_DATA *import_list;
    IMAGE_THUNK_DATA *thunk_list;
581
    WCHAR buffer[32];
Eric Pouech's avatar
Eric Pouech committed
582
    const char *name = get_rva( module, descr->Name );
583
    DWORD len = strlen(name);
584
    PVOID protect_base;
585
    SIZE_T protect_size = 0;
586
    DWORD protect_old;
587

588 589 590 591 592 593
    thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
    if (descr->u.OriginalFirstThunk)
        import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
    else
        import_list = thunk_list;

594 595 596 597 598 599 600
    if (!import_list->u1.Ordinal)
    {
        WARN( "Skipping unused import %s\n", name );
        *pwm = NULL;
        return TRUE;
    }

601 602 603
    while (len && name[len-1] == ' ') len--;  /* remove trailing spaces */

    if (len * sizeof(WCHAR) < sizeof(buffer))
604 605
    {
        ascii_to_unicode( buffer, name, len );
606
        buffer[len] = 0;
607
        status = load_dll( load_path, buffer, 0, &wmImp );
608 609 610
    }
    else  /* need to allocate a larger buffer */
    {
611
        WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
612
        if (!ptr) return FALSE;
613
        ascii_to_unicode( ptr, name, len );
614
        ptr[len] = 0;
615
        status = load_dll( load_path, ptr, 0, &wmImp );
616 617
        RtlFreeHeap( GetProcessHeap(), 0, ptr );
    }
618 619 620

    if (status)
    {
621
        if (status == STATUS_DLL_NOT_FOUND)
622
            ERR("Library %s (which is needed by %s) not found\n",
623
                name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
624
        else
625
            ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
626
                name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
627
        return FALSE;
628 629
    }

630 631 632 633 634
    /* unprotect the import address table since it can be located in
     * readonly section */
    while (import_list[protect_size].u1.Ordinal) protect_size++;
    protect_base = thunk_list;
    protect_size *= sizeof(*thunk_list);
635
    NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
636
                            &protect_size, PAGE_READWRITE, &protect_old );
637

638 639 640
    imp_mod = wmImp->ldr.BaseAddress;
    exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );

641 642 643 644 645 646 647
    if (!exports)
    {
        /* set all imported function to deadbeef */
        while (import_list->u1.Ordinal)
        {
            if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
            {
648 649
                int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
                WARN("No implementation for %s.%d", name, ordinal );
650
                thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
651 652 653 654
            }
            else
            {
                IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
655
                WARN("No implementation for %s.%s", name, pe_name->Name );
Mike McCormack's avatar
Mike McCormack committed
656
                thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
657
            }
658
            WARN(" imported from %s, allocating stub %p\n",
659 660
                 debugstr_w(current_modref->ldr.FullDllName.Buffer),
                 (void *)thunk_list->u1.Function );
661 662 663
            import_list++;
            thunk_list++;
        }
664
        goto done;
665
    }
666 667 668 669 670 671 672

    while (import_list->u1.Ordinal)
    {
        if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
        {
            int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);

673
            thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
674
                                                                      ordinal - exports->Base, load_path );
675 676
            if (!thunk_list->u1.Function)
            {
677
                thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
678
                WARN("No implementation for %s.%d imported from %s, setting to %p\n",
679 680
                     name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
                     (void *)thunk_list->u1.Function );
681
            }
682
            TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
683 684 685 686 687
        }
        else  /* import by name */
        {
            IMAGE_IMPORT_BY_NAME *pe_name;
            pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
688
            thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
689 690
                                                                    (const char*)pe_name->Name,
                                                                    pe_name->Hint, load_path );
691 692
            if (!thunk_list->u1.Function)
            {
Mike McCormack's avatar
Mike McCormack committed
693
                thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
694
                WARN("No implementation for %s.%s imported from %s, setting to %p\n",
695 696
                     name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
                     (void *)thunk_list->u1.Function );
697
            }
698 699
            TRACE_(imports)("--- %s %s.%d = %p\n",
                            pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
700 701 702 703
        }
        import_list++;
        thunk_list++;
    }
704 705 706

done:
    /* restore old protection of the import address table */
707
    NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
708 709
    *pwm = wmImp;
    return TRUE;
710 711 712
}


713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
/***********************************************************************
 *           create_module_activation_context
 */
static NTSTATUS create_module_activation_context( LDR_MODULE *module )
{
    NTSTATUS status;
    LDR_RESOURCE_INFO info;
    const IMAGE_RESOURCE_DATA_ENTRY *entry;

    info.Type = RT_MANIFEST;
    info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
    info.Language = 0;
    if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
    {
        ACTCTXW ctx;
        ctx.cbSize   = sizeof(ctx);
        ctx.lpSource = NULL;
        ctx.dwFlags  = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
        ctx.hModule  = module->BaseAddress;
        ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
        status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
    }
    return status;
}


739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
/*************************************************************************
 *		is_dll_native_subsystem
 *
 * Check if dll is a proper native driver.
 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
 * while being perfectly normal DLLs.  This heuristic should catch such breakages.
 */
static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
{
    static const WCHAR ntdllW[]    = {'n','t','d','l','l','.','d','l','l',0};
    static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
    const IMAGE_IMPORT_DESCRIPTOR *imports;
    DWORD i, size;
    WCHAR buffer[16];

    if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
755
    if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

    if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
                                                 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
    {
        for (i = 0; imports[i].Name; i++)
        {
            const char *name = get_rva( module, imports[i].Name );
            DWORD len = strlen(name);
            if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
            ascii_to_unicode( buffer, name, len + 1 );
            if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
            {
                TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
                return FALSE;
            }
        }
    }
    return TRUE;
}

776 777 778 779 780 781 782 783 784 785 786
/*************************************************************************
 *		alloc_tls_slot
 *
 * Allocate a TLS slot for a newly-loaded module.
 * The loader_section must be locked while calling this function.
 */
static SHORT alloc_tls_slot( LDR_MODULE *mod )
{
    const IMAGE_TLS_DIRECTORY *dir;
    ULONG i, size;
    void *new_ptr;
787
    LIST_ENTRY *entry;
788 789 790 791 792 793 794

    if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
        return -1;

    size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
    if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;

795 796 797 798 799 800
    for (i = 0; i < tls_module_count; i++)
    {
        if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
            !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
            break;
    }
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

    TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
           (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
           (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );

    if (i == tls_module_count)
    {
        UINT new_count = max( 32, tls_module_count * 2 );

        if (!tls_dirs)
            new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
        else
            new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
                                         new_count * sizeof(*tls_dirs) );
        if (!new_ptr) return -1;
816 817 818 819 820 821 822 823 824 825 826

        /* resize the pointer block in all running threads */
        for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
        {
            TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
            void **old = teb->ThreadLocalStoragePointer;
            void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));

            if (!new) return -1;
            if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
            teb->ThreadLocalStoragePointer = new;
827 828 829 830
#if defined(__APPLE__) && defined(__x86_64__)
            if (teb->Reserved5[0])
                ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
#endif
831 832 833 834
            TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
            /* FIXME: can't free old block here, should be freed at thread exit */
        }

835 836 837 838
        tls_dirs = new_ptr;
        tls_module_count = new_count;
    }

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    /* allocate the data block in all running threads */
    for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
    {
        TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );

        if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
        memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
        memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );

        TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
               (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );

        RtlFreeHeap( GetProcessHeap(), 0,
                     interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
    }

855
    *(DWORD *)dir->AddressOfIndex = i;
856
    tls_dirs[i] = *dir;
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    return i;
}


/*************************************************************************
 *		free_tls_slot
 *
 * Free the module TLS slot on unload.
 * The loader_section must be locked while calling this function.
 */
static void free_tls_slot( LDR_MODULE *mod )
{
    ULONG i = (USHORT)mod->TlsIndex;

    if (mod->TlsIndex == -1) return;
    assert( i < tls_module_count );
873
    memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
874 875
}

876

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
/****************************************************************
 *       fixup_imports
 *
 * Fixup all imports of a given module.
 * The loader_section must be locked while calling this function.
 */
static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
{
    int i, nb_imports;
    const IMAGE_IMPORT_DESCRIPTOR *imports;
    WINE_MODREF *prev;
    DWORD size;
    NTSTATUS status;
    ULONG_PTR cookie;

    if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS;  /* already done */
    wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;

895 896
    wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
                                                  IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
        return STATUS_SUCCESS;

    nb_imports = 0;
    while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;

    if (!nb_imports) return STATUS_SUCCESS;  /* no imports */

    if (!create_module_activation_context( &wm->ldr ))
        RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );

    /* Allocate module dependency list */
    wm->nDeps = nb_imports;
    wm->deps  = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );

    /* load the imported modules. They are automatically
     * added to the modref list of the process.
     */
    prev = current_modref;
    current_modref = wm;
    status = STATUS_SUCCESS;
    for (i = 0; i < nb_imports; i++)
    {
921 922 923
        if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &wm->deps[i] ))
        {
            wm->deps[i] = NULL;
924
            status = STATUS_DLL_NOT_FOUND;
925
        }
926 927 928 929 930 931 932
    }
    current_modref = prev;
    if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
    return status;
}


933
/*************************************************************************
934
 *		alloc_module
935 936
 *
 * Allocate a WINE_MODREF structure and add it to the process list
937
 * The loader_section must be locked while calling this function.
938
 */
939
static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
940 941
{
    WINE_MODREF *wm;
Eric Pouech's avatar
Eric Pouech committed
942 943
    const WCHAR *p;
    const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
944

945
    if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
946

947 948 949 950
    wm->nDeps    = 0;
    wm->deps     = NULL;

    wm->ldr.BaseAddress   = hModule;
951
    wm->ldr.EntryPoint    = NULL;
952
    wm->ldr.SizeOfImage   = nt->OptionalHeader.SizeOfImage;
953
    wm->ldr.Flags         = LDR_DONT_RESOLVE_REFS;
954
    wm->ldr.TlsIndex      = -1;
955
    wm->ldr.LoadCount     = 1;
956 957 958
    wm->ldr.SectionHandle = NULL;
    wm->ldr.CheckSum      = 0;
    wm->ldr.TimeDateStamp = 0;
959
    wm->ldr.ActivationContext = 0;
960 961 962 963 964 965

    RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
    if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
    else p = wm->ldr.FullDllName.Buffer;
    RtlInitUnicodeString( &wm->ldr.BaseDllName, p );

966
    if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
967
    {
968 969
        if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
            wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
970 971
        if (nt->OptionalHeader.AddressOfEntryPoint)
            wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
972 973
    }

974 975
    InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
                   &wm->ldr.InLoadOrderModuleList);
976 977
    InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
                   &wm->ldr.InMemoryOrderModuleList);
978 979 980 981

    /* wait until init is called for inserting into this list */
    wm->ldr.InInitializationOrderModuleList.Flink = NULL;
    wm->ldr.InInitializationOrderModuleList.Blink = NULL;
982 983 984

    if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
    {
985
        ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
986
        WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
987
        NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
988
    }
989 990 991 992
    return wm;
}


993 994 995 996 997 998 999 1000
/*************************************************************************
 *              alloc_thread_tls
 *
 * Allocate the per-thread structure for module TLS storage.
 */
static NTSTATUS alloc_thread_tls(void)
{
    void **pointers;
1001
    UINT i, size;
1002 1003 1004

    if (!tls_module_count) return STATUS_SUCCESS;

1005 1006
    if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                      tls_module_count * sizeof(*pointers) )))
1007 1008 1009 1010
        return STATUS_NO_MEMORY;

    for (i = 0; i < tls_module_count; i++)
    {
1011
        const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1012 1013

        if (!dir) continue;
1014
        size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
        if (!size && !dir->SizeOfZeroFill) continue;

        if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
        {
            while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
            RtlFreeHeap( GetProcessHeap(), 0, pointers );
            return STATUS_NO_MEMORY;
        }
        memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
        memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1025

1026 1027
        TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
               GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1028
    }
1029
    NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1030 1031 1032 1033 1034
#if defined(__APPLE__) && defined(__x86_64__)
    __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
                      :
                      : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
#endif
1035 1036 1037 1038
    return STATUS_SUCCESS;
}


1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
/*************************************************************************
 *              call_tls_callbacks
 */
static void call_tls_callbacks( HMODULE module, UINT reason )
{
    const IMAGE_TLS_DIRECTORY *dir;
    const PIMAGE_TLS_CALLBACK *callback;
    ULONG dirsize;

    dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
    if (!dir || !dir->AddressOfCallBacks) return;

1051
    for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1052 1053
    {
        if (TRACE_ON(relay))
1054 1055 1056
        {
            if (TRACE_ON(pid))
                DPRINTF( "%04x:", GetCurrentProcessId() );
1057
            DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1058
                    GetCurrentThreadId(), *callback, module, reason_names[reason] );
1059
        }
1060 1061
        __TRY
        {
1062
            call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1063
        }
1064
        __EXCEPT_ALL
1065 1066
        {
            if (TRACE_ON(relay))
1067 1068 1069
            {
                if (TRACE_ON(pid))
                    DPRINTF( "%04x:", GetCurrentProcessId() );
1070 1071
                DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
                        GetCurrentThreadId(), callback, module, reason_names[reason] );
1072
            }
1073 1074 1075
            return;
        }
        __ENDTRY
1076
        if (TRACE_ON(relay))
1077 1078 1079
        {
            if (TRACE_ON(pid))
                DPRINTF( "%04x:", GetCurrentProcessId() );
1080
            DPRINTF("%04x:Ret  TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1081
                    GetCurrentThreadId(), *callback, module, reason_names[reason] );
1082
        }
1083 1084 1085 1086
    }
}


1087 1088 1089
/*************************************************************************
 *              MODULE_InitDLL
 */
1090
static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1091
{
1092
    WCHAR mod_name[32];
1093
    NTSTATUS status = STATUS_SUCCESS;
1094 1095
    DLLENTRYPROC entry = wm->ldr.EntryPoint;
    void *module = wm->ldr.BaseAddress;
1096
    BOOL retv = FALSE;
1097 1098 1099

    /* Skip calls for modules loaded with special load flags */

1100
    if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1101
    if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1102
    if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1103 1104

    if (TRACE_ON(relay))
1105
    {
1106
        size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1107 1108
        memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
        mod_name[len / sizeof(WCHAR)] = 0;
1109 1110
        if (TRACE_ON(pid))
            DPRINTF( "%04x:", GetCurrentProcessId() );
1111
        DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1112 1113
                GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
                reason_names[reason], lpReserved );
1114
    }
1115 1116
    else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
               reason_names[reason], lpReserved );
1117

1118 1119 1120 1121 1122 1123
    __TRY
    {
        retv = call_dll_entry_point( entry, module, reason, lpReserved );
        if (!retv)
            status = STATUS_DLL_INIT_FAILED;
    }
1124
    __EXCEPT_ALL
1125 1126
    {
        if (TRACE_ON(relay))
1127 1128 1129
        {
            if (TRACE_ON(pid))
                DPRINTF( "%04x:", GetCurrentProcessId() );
1130 1131
            DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
                    GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1132
        }
1133 1134 1135
        status = GetExceptionCode();
    }
    __ENDTRY
1136 1137

    /* The state of the module list may have changed due to the call
1138
       to the dll. We cannot assume that this module has not been
1139
       deleted.  */
1140
    if (TRACE_ON(relay))
1141 1142 1143
    {
        if (TRACE_ON(pid))
            DPRINTF( "%04x:", GetCurrentProcessId() );
1144
        DPRINTF("%04x:Ret  PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1145 1146
                GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
                reason_names[reason], lpReserved, retv );
1147
    }
1148
    else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1149

1150
    return status;
1151 1152 1153 1154
}


/*************************************************************************
1155
 *		process_attach
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
 *
 * Send the process attach notification to all DLLs the given module
 * depends on (recursively). This is somewhat complicated due to the fact that
 *
 * - we have to respect the module dependencies, i.e. modules implicitly
 *   referenced by another module have to be initialized before the module
 *   itself can be initialized
 *
 * - the initialization routine of a DLL can itself call LoadLibrary,
 *   thereby introducing a whole new set of dependencies (even involving
 *   the 'old' modules) at any time during the whole process
 *
 * (Note that this routine can be recursively entered not only directly
 *  from itself, but also via LoadLibrary from one of the called initialization
 *  routines.)
 *
 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
 * the process *detach* notifications to be sent in the correct order.
 * This must not only take into account module dependencies, but also
 * 'hidden' dependencies created by modules calling LoadLibrary in their
 * attach notification routine.
 *
 * The strategy is rather simple: we move a WINE_MODREF to the head of the
 * list after the attach notification has returned.  This implies that the
 * detach notifications are called in the reverse of the sequence the attach
 * notifications *returned*.
1182 1183
 *
 * The loader_section must be locked while calling this function.
1184
 */
1185
static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1186
{
1187
    NTSTATUS status = STATUS_SUCCESS;
1188
    ULONG_PTR cookie;
1189 1190
    int i;

1191 1192
    if (process_detaching) return status;

1193
    /* prevent infinite recursion in case of cyclical dependencies */
1194 1195
    if (    ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
         || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1196
        return status;
1197

1198
    TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1199 1200

    /* Tag current MODREF to prevent recursive loop */
1201
    wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1202
    if (lpReserved) wm->ldr.LoadCount = -1;  /* pin it if imported by the main exe */
1203
    if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1204 1205

    /* Recursively attach all DLLs this one depends on */
1206 1207 1208
    for ( i = 0; i < wm->nDeps; i++ )
    {
        if (!wm->deps[i]) continue;
1209
        if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1210
    }
1211

1212 1213 1214 1215
    if (!wm->ldr.InInitializationOrderModuleList.Flink)
        InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
                &wm->ldr.InInitializationOrderModuleList);

1216
    /* Call DLL entry point */
1217
    if (status == STATUS_SUCCESS)
1218
    {
1219 1220
        WINE_MODREF *prev = current_modref;
        current_modref = wm;
1221 1222
        status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
        if (status == STATUS_SUCCESS)
1223 1224
            wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
        else
1225
        {
1226
            MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1227 1228 1229 1230
            /* point to the name so LdrInitializeThunk can print it */
            last_failed_modref = wm;
            WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
        }
1231
        current_modref = prev;
1232 1233
    }

1234
    if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1235
    /* Remove recursion flag */
1236
    wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1237

1238
    TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1239
    return status;
1240 1241
}

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

/**********************************************************************
 *	    attach_implicitly_loaded_dlls
 *
 * Attach to the (builtin) dlls that have been implicitly loaded because
 * of a dependency at the Unix level, but not imported at the Win32 level.
 */
static void attach_implicitly_loaded_dlls( LPVOID reserved )
{
    for (;;)
    {
        PLIST_ENTRY mark, entry;

        mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
        for (entry = mark->Flink; entry != mark; entry = entry->Flink)
        {
            LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);

            if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
            TRACE( "found implicitly loaded %s, attaching to it\n",
                   debugstr_w(mod->BaseDllName.Buffer));
            process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
            break;  /* restart the search from the start */
        }
        if (entry == mark) break;  /* nothing found */
    }
}


1271
/*************************************************************************
1272
 *		process_detach
1273 1274
 *
 * Send DLL process detach notifications.  See the comment about calling
1275
 * sequence at process_attach.
1276
 */
1277
static void process_detach(void)
1278
{
1279 1280
    PLIST_ENTRY mark, entry;
    PLDR_MODULE mod;
1281

1282
    mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1283 1284
    do
    {
1285
        for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1286
        {
1287 1288
            mod = CONTAINING_RECORD(entry, LDR_MODULE, 
                                    InInitializationOrderModuleList);
1289
            /* Check whether to detach this DLL */
1290
            if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1291
                continue;
1292
            if ( mod->LoadCount && !process_detaching )
1293 1294 1295
                continue;

            /* Call detach notification */
1296 1297
            mod->Flags &= ~LDR_PROCESS_ATTACHED;
            MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
1298
                            DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1299 1300 1301 1302 1303

            /* Restart at head of WINE_MODREF list, as entries might have
               been added and/or removed while performing the call ... */
            break;
        }
1304
    } while (entry != mark);
1305 1306 1307 1308 1309 1310 1311 1312 1313
}

/*************************************************************************
 *		MODULE_DllThreadAttach
 *
 * Send DLL thread attach notifications. These are sent in the
 * reverse sequence of process detach notification.
 *
 */
1314
NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1315
{
1316 1317 1318
    PLIST_ENTRY mark, entry;
    PLDR_MODULE mod;
    NTSTATUS    status;
1319 1320

    /* don't do any attach calls if process is exiting */
1321
    if (process_detaching) return STATUS_SUCCESS;
1322 1323 1324

    RtlEnterCriticalSection( &loader_section );

1325 1326 1327 1328
    RtlAcquirePebLock();
    InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
    RtlReleasePebLock();

1329
    if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1330

1331 1332
    mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1333
    {
1334 1335 1336
        mod = CONTAINING_RECORD(entry, LDR_MODULE, 
                                InInitializationOrderModuleList);
        if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1337
            continue;
1338
        if ( mod->Flags & LDR_NO_DLL_CALLS )
1339 1340
            continue;

1341 1342
        MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
                        DLL_THREAD_ATTACH, lpReserved );
1343 1344
    }

1345
done:
1346
    RtlLeaveCriticalSection( &loader_section );
1347
    return status;
1348 1349
}

1350 1351 1352 1353 1354
/******************************************************************
 *		LdrDisableThreadCalloutsForDll (NTDLL.@)
 *
 */
NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1355
{
1356 1357 1358 1359 1360
    WINE_MODREF *wm;
    NTSTATUS    ret = STATUS_SUCCESS;

    RtlEnterCriticalSection( &loader_section );

1361
    wm = get_modref( hModule );
1362
    if (!wm || wm->ldr.TlsIndex != -1)
1363
        ret = STATUS_DLL_NOT_FOUND;
1364
    else
1365
        wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1366 1367 1368 1369

    RtlLeaveCriticalSection( &loader_section );

    return ret;
1370
}
1371

1372 1373 1374 1375 1376
/******************************************************************
 *              LdrFindEntryForAddress (NTDLL.@)
 *
 * The loader_section must be locked while calling this function
 */
1377
NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1378
{
1379 1380
    PLIST_ENTRY mark, entry;
    PLDR_MODULE mod;
1381

1382 1383
    mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1384
    {
1385
        mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1386
        if (mod->BaseAddress <= addr &&
Eric Pouech's avatar
Eric Pouech committed
1387
            (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1388
        {
1389
            *pmod = mod;
1390 1391 1392 1393 1394 1395
            return STATUS_SUCCESS;
        }
    }
    return STATUS_NO_MORE_ENTRIES;
}

1396 1397 1398
/******************************************************************
 *		LdrLockLoaderLock  (NTDLL.@)
 *
1399
 * Note: some flags are not implemented.
1400 1401
 * Flag 0x01 is used to raise exceptions on errors.
 */
1402
NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1403
{
1404
    if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1405

1406 1407 1408 1409
    if (result) *result = 0;
    if (magic) *magic = 0;
    if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
    if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1410
    if (!magic) return STATUS_INVALID_PARAMETER_3;
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

    if (flags & 0x2)
    {
        if (!RtlTryEnterCriticalSection( &loader_section ))
        {
            *result = 2;
            return STATUS_SUCCESS;
        }
        *result = 1;
    }
    else
    {
        RtlEnterCriticalSection( &loader_section );
        if (result) *result = 1;
    }
1426 1427 1428 1429 1430 1431 1432 1433
    *magic = GetCurrentThreadId();
    return STATUS_SUCCESS;
}


/******************************************************************
 *		LdrUnlockLoaderUnlock  (NTDLL.@)
 */
1434
NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
{
    if (magic)
    {
        if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
        RtlLeaveCriticalSection( &loader_section );
    }
    return STATUS_SUCCESS;
}


1445 1446
/******************************************************************
 *		LdrGetProcedureAddress  (NTDLL.@)
1447
 */
1448 1449
NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
                                       ULONG ord, PVOID *address)
1450
{
1451 1452 1453
    IMAGE_EXPORT_DIRECTORY *exports;
    DWORD exp_size;
    NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1454

1455
    RtlEnterCriticalSection( &loader_section );
1456

1457 1458 1459 1460
    /* check if the module itself is invalid to return the proper error */
    if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
    else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
                                                      IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1461
    {
1462 1463 1464
        LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
        void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
                          : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1465 1466 1467 1468 1469 1470
        if (proc)
        {
            *address = proc;
            ret = STATUS_SUCCESS;
        }
    }
1471

1472 1473
    RtlLeaveCriticalSection( &loader_section );
    return ret;
1474
}
1475 1476


1477 1478 1479 1480 1481
/***********************************************************************
 *           is_fake_dll
 *
 * Check if a loaded native dll is a Wine fake dll.
 */
1482
static BOOL is_fake_dll( HANDLE handle )
1483 1484
{
    static const char fakedll_signature[] = "Wine placeholder DLL";
1485 1486 1487 1488
    char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
    const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
    IO_STATUS_BLOCK io;
    LARGE_INTEGER offset;
1489

1490 1491 1492 1493
    offset.QuadPart = 0;
    if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
    if (io.Information < sizeof(buffer)) return FALSE;
    if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1494 1495 1496 1497 1498 1499
    if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
        !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
    return FALSE;
}


1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
/***********************************************************************
 *           get_builtin_fullname
 *
 * Build the full pathname for a builtin dll.
 */
static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
{
    static const WCHAR soW[] = {'.','s','o',0};
    WCHAR *p, *fullname;
    size_t i, len = strlen(filename);

    /* check if path can correspond to the dll we have */
    if (path && (p = strrchrW( path, '\\' )))
    {
        p++;
        for (i = 0; i < len; i++)
            if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
        if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
        {
            /* the filename matches, use path as the full path */
            len += p - path;
            if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
            {
                memcpy( fullname, path, len * sizeof(WCHAR) );
                fullname[len] = 0;
            }
            return fullname;
        }
    }

    if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
                                     system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
    {
        memcpy( fullname, system_dir.Buffer, system_dir.Length );
        p = fullname + system_dir.Length / sizeof(WCHAR);
        if (p > fullname && p[-1] != '\\') *p++ = '\\';
        ascii_to_unicode( p, filename, len + 1 );
    }
    return fullname;
}


1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
/*************************************************************************
 *		is_16bit_builtin
 */
static BOOL is_16bit_builtin( HMODULE module )
{
    const IMAGE_EXPORT_DIRECTORY *exports;
    DWORD exp_size;

    if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
        return FALSE;

    return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
}


1558 1559 1560 1561 1562 1563 1564
/***********************************************************************
 *           load_builtin_callback
 *
 * Load a library in memory; callback function for wine_dll_register
 */
static void load_builtin_callback( void *module, const char *filename )
{
1565
    static const WCHAR emptyW[1];
1566 1567
    IMAGE_NT_HEADERS *nt;
    WINE_MODREF *wm;
1568
    WCHAR *fullname;
1569
    const WCHAR *load_path;
1570 1571 1572 1573 1574 1575 1576 1577 1578

    if (!module)
    {
        ERR("could not map image for %s\n", filename ? filename : "main exe" );
        return;
    }
    if (!(nt = RtlImageNtHeader( module )))
    {
        ERR( "bad module for %s\n", filename ? filename : "main exe" );
1579
        builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1580 1581
        return;
    }
1582 1583

    virtual_create_builtin_view( module );
1584

1585 1586
    /* create the MODREF */

1587
    if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1588 1589
    {
        ERR( "can't load %s\n", filename );
1590
        builtin_load_info->status = STATUS_NO_MEMORY;
1591 1592 1593
        return;
    }

1594 1595
    wm = alloc_module( module, fullname );
    RtlFreeHeap( GetProcessHeap(), 0, fullname );
1596 1597 1598
    if (!wm)
    {
        ERR( "can't load %s\n", filename );
1599
        builtin_load_info->status = STATUS_NO_MEMORY;
1600 1601 1602 1603
        return;
    }
    wm->ldr.Flags |= LDR_WINE_INTERNAL;

1604
    if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1605 1606
        nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
        is_16bit_builtin( module ))
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    {
        /* fixup imports */

        load_path = builtin_load_info->load_path;
        if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
        if (!load_path) load_path = emptyW;
        if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
        {
            /* the module has only be inserted in the load & memory order lists */
            RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
            RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
            /* FIXME: free the modref */
            builtin_load_info->status = STATUS_DLL_NOT_FOUND;
            return;
        }
1622
    }
1623

1624
    builtin_load_info->wm = wm;
1625 1626 1627 1628 1629 1630
    TRACE( "loaded %s %p %p\n", filename, wm, module );

    /* send the DLL load event */

    SERVER_START_REQ( load_dll )
    {
1631
        req->mapping    = 0;
1632
        req->base       = wine_server_client_ptr( module );
1633 1634 1635
        req->size       = nt->OptionalHeader.SizeOfImage;
        req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
        req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1636
        req->name       = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1637
        wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1638 1639 1640 1641 1642 1643 1644 1645 1646
        wine_server_call( req );
    }
    SERVER_END_REQ;

    /* setup relay debugging entry points */
    if (TRACE_ON(relay)) RELAY_SetupDLL( module );
}


1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
/***********************************************************************
 *           set_security_cookie
 *
 * Create a random security cookie for buffer overflow protection. Make
 * sure it does not accidentally match the default cookie value.
 */
static void set_security_cookie( void *module, SIZE_T len )
{
    static ULONG seed;
    IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
    ULONG loadcfg_size;
    ULONG_PTR *cookie;

    loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
    if (!loadcfg) return;
    if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
    if (!loadcfg->SecurityCookie) return;
    if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
        loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
    {
        WARN( "security cookie %p outside of image %p-%p\n",
              (void *)loadcfg->SecurityCookie, module, (char *)module + len );
        return;
    }

    cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
    TRACE( "initializing security cookie %p\n", cookie );

    if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
    for (;;)
    {
        if (*cookie == DEFAULT_SECURITY_COOKIE_16)
            *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
        else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
            *cookie = RtlRandom( &seed );
#ifdef DEFAULT_SECURITY_COOKIE_64
        else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
        {
            *cookie = RtlRandom( &seed );
            /* fill up, but keep the highest word clear */
            *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
        }
#endif
        else
            break;
    }
}

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
static NTSTATUS perform_relocations( void *module, SIZE_T len )
{
    IMAGE_NT_HEADERS *nt;
    char *base;
    IMAGE_BASE_RELOCATION *rel, *end;
    const IMAGE_DATA_DIRECTORY *relocs;
    const IMAGE_SECTION_HEADER *sec;
    INT_PTR delta;
    ULONG protect_old[96], i;

    nt = RtlImageNtHeader( module );
    base = (char *)nt->OptionalHeader.ImageBase;

    assert( module != base );

    /* no relocations are performed on non page-aligned binaries */
    if (nt->OptionalHeader.SectionAlignment < page_size)
        return STATUS_SUCCESS;

    if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
        return STATUS_SUCCESS;

    relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];

1719
    if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1720 1721 1722 1723 1724 1725
    {
        WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
              base, module );
        return STATUS_CONFLICTING_ADDRESSES;
    }

1726 1727 1728
    if (!relocs->Size) return STATUS_SUCCESS;
    if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
    if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
        return STATUS_INVALID_IMAGE_FORMAT;

    sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
                                         nt->FileHeader.SizeOfOptionalHeader);
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
    {
        void *addr = get_rva( module, sec[i].VirtualAddress );
        SIZE_T size = sec[i].SizeOfRawData;
        NtProtectVirtualMemory( NtCurrentProcess(), &addr,
                                &size, PAGE_READWRITE, &protect_old[i] );
    }

    TRACE( "relocating from %p-%p to %p-%p\n",
           base, base + len, module, (char *)module + len );

    rel = get_rva( module, relocs->VirtualAddress );
    end = get_rva( module, relocs->VirtualAddress + relocs->Size );
    delta = (char *)module - base;

    while (rel < end - 1 && rel->SizeOfBlock)
    {
        if (rel->VirtualAddress >= len)
        {
            WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
            return STATUS_ACCESS_VIOLATION;
        }
        rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
                                         (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
                                         (USHORT *)(rel + 1), delta );
        if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
    }

    for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
    {
        void *addr = get_rva( module, sec[i].VirtualAddress );
        SIZE_T size = sec[i].SizeOfRawData;
        NtProtectVirtualMemory( NtCurrentProcess(), &addr,
                                &size, protect_old[i], &protect_old[i] );
    }

    return STATUS_SUCCESS;
}
1772

1773 1774 1775
/******************************************************************************
 *	load_native_dll  (internal)
 */
1776 1777
static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
                                 DWORD flags, WINE_MODREF** pwm )
1778 1779
{
    void *module;
1780
    HANDLE mapping;
1781 1782
    LARGE_INTEGER size;
    IMAGE_NT_HEADERS *nt;
1783
    SIZE_T len = 0;
1784 1785 1786
    WINE_MODREF *wm;
    NTSTATUS status;

1787
    TRACE("Trying native dll %s\n", debugstr_w(name));
1788 1789 1790

    size.QuadPart = 0;
    status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1791
                              NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1792
    if (status != STATUS_SUCCESS) return status;
1793 1794

    module = NULL;
1795
    status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1796
                                 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

    /* perform base relocation, if necessary */

    if (status == STATUS_IMAGE_NOT_AT_BASE)
        status = perform_relocations( module, len );

    if (status != STATUS_SUCCESS)
    {
        if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
        goto done;
    }
1808 1809 1810

    /* create the MODREF */

1811 1812 1813 1814 1815
    if (!(wm = alloc_module( module, name )))
    {
        status = STATUS_NO_MEMORY;
        goto done;
    }
1816

1817 1818
    set_security_cookie( module, len );

1819 1820
    /* fixup imports */

1821 1822 1823 1824 1825
    nt = RtlImageNtHeader( module );

    if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
        ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
         nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1826
    {
1827
        if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
        {
            /* the module has only be inserted in the load & memory order lists */
            RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
            RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);

            /* FIXME: there are several more dangling references
             * left. Including dlls loaded by this dll before the
             * failed one. Unrolling is rather difficult with the
             * current structure and we can leave them lying
             * around with no problems, so we don't care.
             * As these might reference our wm, we don't free it.
             */
1840
            goto done;
1841 1842 1843 1844 1845 1846 1847
        }
    }

    /* send DLL load event */

    SERVER_START_REQ( load_dll )
    {
1848
        req->mapping    = wine_server_obj_handle( mapping );
1849
        req->base       = wine_server_client_ptr( module );
1850 1851 1852
        req->size       = nt->OptionalHeader.SizeOfImage;
        req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
        req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1853
        req->name       = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1854
        wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1855 1856 1857 1858
        wine_server_call( req );
    }
    SERVER_END_REQ;

1859
    if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1860

1861
    TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1862

1863
    wm->ldr.LoadCount = 1;
1864
    *pwm = wm;
1865 1866 1867 1868
    status = STATUS_SUCCESS;
done:
    NtClose( mapping );
    return status;
1869 1870 1871
}


1872 1873 1874
/***********************************************************************
 *           load_builtin_dll
 */
1875 1876
static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
                                  DWORD flags, WINE_MODREF** pwm )
1877
{
1878 1879 1880
    char error[256], dllname[MAX_PATH];
    const WCHAR *name, *p;
    DWORD len, i;
1881
    void *handle;
1882
    struct builtin_load_info info, *prev_info;
1883 1884 1885

    /* Fix the name in case we have a full path and extension */
    name = path;
1886 1887
    if ((p = strrchrW( name, '\\' ))) name = p + 1;
    if ((p = strrchrW( name, '/' ))) name = p + 1;
1888

1889
    /* load_library will modify info.status. Note also that load_library can be
1890
     * called several times, if the .so file we're loading has dependencies.
1891
     * info.status will gather all the errors we may get while loading all these
1892 1893
     * libraries
     */
1894
    info.load_path = load_path;
1895
    info.filename  = NULL;
1896 1897
    info.status    = STATUS_SUCCESS;
    info.wm        = NULL;
1898 1899 1900 1901 1902 1903

    if (file)  /* we have a real file, try to load it */
    {
        UNICODE_STRING nt_name;
        ANSI_STRING unix_name;

1904 1905
        TRACE("Trying built-in %s\n", debugstr_w(path));

1906 1907 1908
        if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
            return STATUS_DLL_NOT_FOUND;

1909
        if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1910
        {
1911 1912
            RtlFreeUnicodeString( &nt_name );
            return STATUS_DLL_NOT_FOUND;
1913
        }
1914 1915 1916 1917 1918
        prev_info = builtin_load_info;
        info.filename = nt_name.Buffer + 4;  /* skip \??\ */
        builtin_load_info = &info;
        handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
        builtin_load_info = prev_info;
1919
        RtlFreeUnicodeString( &nt_name );
1920 1921 1922 1923 1924 1925
        RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
        if (!handle)
        {
            WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
            return STATUS_INVALID_IMAGE_FORMAT;
        }
1926 1927 1928
    }
    else
    {
1929 1930
        int file_exists;

1931 1932
        TRACE("Trying built-in %s\n", debugstr_w(name));

1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
        /* we don't want to depend on the current codepage here */
        len = strlenW( name ) + 1;
        if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
        for (i = 0; i < len; i++)
        {
            if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
            dllname[i] = (char)name[i];
            if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
        }

        prev_info = builtin_load_info;
        builtin_load_info = &info;
        handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
        builtin_load_info = prev_info;
1947
        if (!handle)
1948
        {
1949 1950 1951 1952 1953 1954 1955 1956 1957
            if (!file_exists)
            {
                /* The file does not exist -> WARN() */
                WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
                return STATUS_DLL_NOT_FOUND;
            }
            /* ERR() for all other errors (missing functions, ...) */
            ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
            return STATUS_PROCEDURE_NOT_FOUND;
1958 1959
        }
    }
1960

1961 1962 1963 1964 1965
    if (info.status != STATUS_SUCCESS)
    {
        wine_dll_unload( handle );
        return info.status;
    }
1966

1967 1968
    if (!info.wm)
    {
1969
        PLIST_ENTRY mark, entry;
1970

1971 1972
        /* The constructor wasn't called, this means the .so is already
         * loaded under a different name. Try to find the wm for it. */
1973

1974 1975
        mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
        for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1976
        {
1977 1978 1979 1980
            LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
            if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
            {
                info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1981 1982
                TRACE( "Found %s at %p for builtin %s\n",
                       debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1983 1984
                break;
            }
1985
        }
1986
        wine_dll_unload( handle );  /* release the libdl refcount */
1987
        if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1988
        if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1989 1990 1991
    }
    else
    {
1992
        TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1993
        info.wm->ldr.LoadCount = 1;
1994
        info.wm->ldr.SectionHandle = handle;
1995
    }
1996

1997
    *pwm = info.wm;
1998 1999 2000 2001
    return STATUS_SUCCESS;
}


2002 2003 2004 2005 2006 2007 2008 2009
/***********************************************************************
 *	find_actctx_dll
 *
 * Find the full path (if any) of the dll from the activation context.
 */
static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
{
    static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2010
    static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042

    ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
    ACTCTX_SECTION_KEYED_DATA data;
    UNICODE_STRING nameW;
    NTSTATUS status;
    SIZE_T needed, size = 1024;
    WCHAR *p;

    RtlInitUnicodeString( &nameW, libname );
    data.cbSize = sizeof(data);
    status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
                                                    ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
                                                    &nameW, &data );
    if (status != STATUS_SUCCESS) return status;

    for (;;)
    {
        if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
        {
            status = STATUS_NO_MEMORY;
            goto done;
        }
        status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
                                                       AssemblyDetailedInformationInActivationContext,
                                                       info, size, &needed );
        if (status == STATUS_SUCCESS) break;
        if (status != STATUS_BUFFER_TOO_SMALL) goto done;
        RtlFreeHeap( GetProcessHeap(), 0, info );
        size = needed;
        /* restart with larger buffer */
    }

2043 2044 2045 2046 2047 2048
    if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
    {
        status = STATUS_SXS_KEY_NOT_FOUND;
        goto done;
    }

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
    {
        DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);

        p++;
        if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
        {
            /* manifest name does not match directory name, so it's not a global
             * windows/winsxs manifest; use the manifest directory name instead */
            dirlen = p - info->lpAssemblyManifestPath;
            needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
            if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
            {
                status = STATUS_NO_MEMORY;
                goto done;
            }
            memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
            p += dirlen;
            strcpyW( p, libname );
            goto done;
        }
    }

2072 2073
    needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
              sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2074 2075 2076 2077 2078 2079

    if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
    {
        status = STATUS_NO_MEMORY;
        goto done;
    }
2080 2081
    strcpyW( p, user_shared_data->NtSystemRoot );
    p += strlenW(p);
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
    memcpy( p, winsxsW, sizeof(winsxsW) );
    p += sizeof(winsxsW) / sizeof(WCHAR);
    memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
    p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
    *p++ = '\\';
    strcpyW( p, libname );
done:
    RtlFreeHeap( GetProcessHeap(), 0, info );
    RtlReleaseActivationContext( data.hActCtx );
    return status;
}


2095 2096 2097 2098 2099 2100 2101 2102
/***********************************************************************
 *	find_dll_file
 *
 * Find the file (or already loaded module) for a given dll name.
 */
static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
                               WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
{
2103 2104 2105
    OBJECT_ATTRIBUTES attr;
    IO_STATUS_BLOCK io;
    UNICODE_STRING nt_name;
2106
    WCHAR *file_part, *ext, *dllname;
2107 2108
    ULONG len;

2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
    /* first append .dll if needed */

    dllname = NULL;
    if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
    {
        if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
                                         (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
            return STATUS_NO_MEMORY;
        strcpyW( dllname, libname );
        strcatW( dllname, dllW );
        libname = dllname;
    }

2122
    nt_name.Buffer = NULL;
2123 2124 2125

    if (!contains_path( libname ))
    {
2126
        NTSTATUS status;
2127
        WCHAR *fullname = NULL;
2128

2129
        if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2130 2131 2132 2133

        status = find_actctx_dll( libname, &fullname );
        if (status == STATUS_SUCCESS)
        {
2134
            TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2135 2136 2137 2138 2139 2140 2141 2142
            RtlFreeHeap( GetProcessHeap(), 0, dllname );
            libname = dllname = fullname;
        }
        else if (status != STATUS_SXS_KEY_NOT_FOUND)
        {
            RtlFreeHeap( GetProcessHeap(), 0, dllname );
            return status;
        }
2143 2144
    }

2145 2146 2147
    if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
    {
        /* we need to search for it */
2148
        len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2149 2150
        if (len)
        {
2151
            if (len >= *size) goto overflow;
2152
            if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2153

2154
            if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2155 2156
            {
                RtlFreeHeap( GetProcessHeap(), 0, dllname );
2157
                return STATUS_NO_MEMORY;
2158
            }
2159 2160 2161 2162 2163 2164
            attr.Length = sizeof(attr);
            attr.RootDirectory = 0;
            attr.Attributes = OBJ_CASE_INSENSITIVE;
            attr.ObjectName = &nt_name;
            attr.SecurityDescriptor = NULL;
            attr.SecurityQualityOfService = NULL;
2165
            if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2166
            goto found;
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
        }

        /* not found */

        if (!contains_path( libname ))
        {
            /* if libname doesn't contain a path at all, we simply return the name as is,
             * to be loaded as builtin */
            len = strlenW(libname) * sizeof(WCHAR);
            if (len >= *size) goto overflow;
            strcpyW( filename, libname );
2178
            goto found;
2179 2180 2181 2182 2183
        }
    }

    /* absolute path name, or relative path name but not found above */

2184
    if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2185 2186
    {
        RtlFreeHeap( GetProcessHeap(), 0, dllname );
2187
        return STATUS_NO_MEMORY;
2188
    }
2189
    len = nt_name.Length - 4*sizeof(WCHAR);  /* for \??\ prefix */
2190
    if (len >= *size) goto overflow;
2191
    memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2192
    if (!(*pwm = find_fullname_module( filename )) && handle)
2193 2194 2195 2196 2197 2198 2199
    {
        attr.Length = sizeof(attr);
        attr.RootDirectory = 0;
        attr.Attributes = OBJ_CASE_INSENSITIVE;
        attr.ObjectName = &nt_name;
        attr.SecurityDescriptor = NULL;
        attr.SecurityQualityOfService = NULL;
2200
        if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2201
    }
2202
found:
2203
    RtlFreeUnicodeString( &nt_name );
2204
    RtlFreeHeap( GetProcessHeap(), 0, dllname );
2205 2206 2207
    return STATUS_SUCCESS;

overflow:
2208
    RtlFreeUnicodeString( &nt_name );
2209
    RtlFreeHeap( GetProcessHeap(), 0, dllname );
2210 2211 2212 2213 2214
    *size = len + sizeof(WCHAR);
    return STATUS_BUFFER_TOO_SMALL;
}


2215
/***********************************************************************
2216
 *	load_dll  (internal)
2217 2218
 *
 * Load a PE style module according to the load order.
2219
 * The loader_section must be locked while calling this function.
2220
 */
2221
static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2222
{
2223
    enum loadorder loadorder;
2224
    WCHAR buffer[64];
2225 2226
    WCHAR *filename;
    ULONG size;
2227
    WINE_MODREF *main_exe;
2228
    HANDLE handle = 0;
2229
    NTSTATUS nts;
2230

2231
    TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2232

2233
    *pwm = NULL;
2234 2235 2236
    filename = buffer;
    size = sizeof(buffer);
    for (;;)
2237
    {
2238 2239 2240 2241 2242 2243
        nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
        if (nts == STATUS_SUCCESS) break;
        if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
        if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
        /* grow the buffer and retry */
        if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2244
    }
2245 2246

    if (*pwm)  /* found already loaded module */
2247
    {
2248 2249
        if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;

2250
        TRACE("Found %s for %s at %p, count=%d\n",
2251 2252 2253 2254
              debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
              (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
        if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
        return STATUS_SUCCESS;
2255 2256
    }

2257
    main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2258
    loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2259

2260 2261 2262 2263 2264 2265 2266
    if (handle && is_fake_dll( handle ))
    {
        TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
        NtClose( handle );
        handle = 0;
    }

2267
    switch(loadorder)
2268
    {
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
    case LO_INVALID:
        nts = STATUS_NO_MEMORY;
        break;
    case LO_DISABLED:
        nts = STATUS_DLL_NOT_FOUND;
        break;
    case LO_NATIVE:
    case LO_NATIVE_BUILTIN:
        if (!handle) nts = STATUS_DLL_NOT_FOUND;
        else
2279
        {
2280
            nts = load_native_dll( load_path, filename, handle, flags, pwm );
2281
            if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2282 2283
                /* not in PE format, maybe it's a builtin */
                nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2284
        }
2285
        if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2286 2287
            nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
        break;
2288 2289 2290
    case LO_BUILTIN:
    case LO_BUILTIN_NATIVE:
    case LO_DEFAULT:  /* default is builtin,native */
2291 2292 2293
        nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
        if (!handle) break;  /* nothing else we can try */
        /* file is not a builtin library, try without using the specified file */
2294 2295 2296
        if (nts != STATUS_SUCCESS)
            nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
        if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2297
            (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2298 2299 2300 2301 2302 2303
        {
            /* stub-only dll, try native */
            TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
            LdrUnloadDll( (*pwm)->ldr.BaseAddress );
            nts = STATUS_DLL_NOT_FOUND;
        }
2304
        if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2305 2306 2307
            nts = load_native_dll( load_path, filename, handle, flags, pwm );
        break;
    }
2308

2309 2310 2311 2312 2313 2314 2315 2316 2317
    if (nts == STATUS_SUCCESS)
    {
        /* Initialize DLL just loaded */
        TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
              ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
              (*pwm)->ldr.BaseAddress);
        if (handle) NtClose( handle );
        if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
        return nts;
2318 2319
    }

2320
    WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2321
    if (handle) NtClose( handle );
2322
    if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2323
    return nts;
2324 2325 2326 2327 2328
}

/******************************************************************
 *		LdrLoadDll (NTDLL.@)
 */
2329 2330
NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
                                             const UNICODE_STRING *libname, HMODULE* hModule)
2331 2332
{
    WINE_MODREF *wm;
2333
    NTSTATUS nts;
2334 2335 2336

    RtlEnterCriticalSection( &loader_section );

2337 2338
    if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
    nts = load_dll( path_name, libname->Buffer, flags, &wm );
2339 2340

    if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2341
    {
2342
        nts = process_attach( wm, NULL );
2343
        if (nts != STATUS_SUCCESS)
2344
        {
2345
            LdrUnloadDll(wm->ldr.BaseAddress);
2346 2347 2348
            wm = NULL;
        }
    }
2349
    *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2350

2351
    RtlLeaveCriticalSection( &loader_section );
2352 2353 2354
    return nts;
}

2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378

/******************************************************************
 *		LdrGetDllHandle (NTDLL.@)
 */
NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
{
    NTSTATUS status;
    WCHAR buffer[128];
    WCHAR *filename;
    ULONG size;
    WINE_MODREF *wm;

    RtlEnterCriticalSection( &loader_section );

    if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;

    filename = buffer;
    size = sizeof(buffer);
    for (;;)
    {
        status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
        if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
        if (status != STATUS_BUFFER_TOO_SMALL) break;
        /* grow the buffer and retry */
2379 2380 2381 2382 2383
        if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
        {
            status = STATUS_NO_MEMORY;
            break;
        }
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
    }

    if (status == STATUS_SUCCESS)
    {
        if (wm) *base = wm->ldr.BaseAddress;
        else status = STATUS_DLL_NOT_FOUND;
    }

    RtlLeaveCriticalSection( &loader_section );
    TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
    return status;
}


2398 2399 2400 2401 2402 2403 2404 2405
/******************************************************************
 *		LdrAddRefDll (NTDLL.@)
 */
NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
{
    NTSTATUS ret = STATUS_SUCCESS;
    WINE_MODREF *wm;

2406
    if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2407 2408 2409 2410 2411

    RtlEnterCriticalSection( &loader_section );

    if ((wm = get_modref( module )))
    {
2412 2413 2414 2415
        if (flags & LDR_ADDREF_DLL_PIN)
            wm->ldr.LoadCount = -1;
        else
            if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2416 2417 2418 2419 2420 2421 2422 2423 2424
        TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
    }
    else ret = STATUS_INVALID_PARAMETER;

    RtlLeaveCriticalSection( &loader_section );
    return ret;
}


2425 2426 2427 2428 2429 2430
/***********************************************************************
 *           LdrProcessRelocationBlock  (NTDLL.@)
 *
 * Apply relocations to a given page of a mapped PE image.
 */
IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2431
                                                          USHORT *relocs, INT_PTR delta )
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
{
    while (count--)
    {
        USHORT offset = *relocs & 0xfff;
        int type = *relocs >> 12;
        switch(type)
        {
        case IMAGE_REL_BASED_ABSOLUTE:
            break;
        case IMAGE_REL_BASED_HIGH:
            *(short *)((char *)page + offset) += HIWORD(delta);
            break;
        case IMAGE_REL_BASED_LOW:
            *(short *)((char *)page + offset) += LOWORD(delta);
            break;
        case IMAGE_REL_BASED_HIGHLOW:
            *(int *)((char *)page + offset) += delta;
            break;
2450
#ifdef __x86_64__
2451 2452 2453
        case IMAGE_REL_BASED_DIR64:
            *(INT_PTR *)((char *)page + offset) += delta;
            break;
2454 2455 2456 2457 2458
#elif defined(__arm__)
        case IMAGE_REL_BASED_THUMB_MOV32:
        {
            DWORD inst = *(INT_PTR *)((char *)page + offset);
            DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2459
                          ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2460
            DWORD hi_delta;
2461 2462 2463 2464 2465

            if ((inst & 0x8000fbf0) != 0x0000f240)
                ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);

            imm16 += LOWORD(delta);
2466
            hi_delta = HIWORD(delta) + HIWORD(imm16);
2467 2468 2469
            *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
                                                  ((imm16 >> 12) & 0x000f) +
                                                  ((imm16 << 20) & 0x70000000) +
2470
                                                  ((imm16 << 16) & 0xff0000);
2471

2472
            if (hi_delta != 0)
2473 2474 2475
            {
                inst = *(INT_PTR *)((char *)page + offset + 4);
                imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2476
                        ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2477 2478 2479 2480

                if ((inst & 0x8000fbf0) != 0x0000f2c0)
                    ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);

2481
                imm16 += hi_delta;
2482 2483 2484 2485 2486 2487
                if (imm16 > 0xffff)
                    ERR("resulting immediate value won't fit: %08x\n", imm16);
                *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
                                                          ((imm16 >> 1) & 0x0400) +
                                                          ((imm16 >> 12) & 0x000f) +
                                                          ((imm16 << 20) & 0x70000000) +
2488
                                                          ((imm16 << 16) & 0xff0000);
2489 2490 2491
            }
        }
            break;
2492
#endif
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
        default:
            FIXME("Unknown/unsupported fixup type %x.\n", type);
            return NULL;
        }
        relocs++;
    }
    return (IMAGE_BASE_RELOCATION *)relocs;  /* return address of next block */
}


2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
/******************************************************************
 *		LdrQueryProcessModuleInformation
 *
 */
NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
                                                 ULONG buf_size, ULONG* req_size)
{
    SYSTEM_MODULE*      sm = &smi->Modules[0];
    ULONG               size = sizeof(ULONG);
    NTSTATUS            nts = STATUS_SUCCESS;
    ANSI_STRING         str;
    char*               ptr;
2515 2516
    PLIST_ENTRY         mark, entry;
    PLDR_MODULE         mod;
2517
    WORD id = 0;
2518 2519 2520 2521

    smi->ModulesCount = 0;

    RtlEnterCriticalSection( &loader_section );
2522 2523
    mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2524
    {
2525
        mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2526 2527 2528 2529 2530
        size += sizeof(*sm);
        if (size <= buf_size)
        {
            sm->Reserved1 = 0; /* FIXME */
            sm->Reserved2 = 0; /* FIXME */
2531 2532 2533
            sm->ImageBaseAddress = mod->BaseAddress;
            sm->ImageSize = mod->SizeOfImage;
            sm->Flags = mod->Flags;
2534
            sm->Id = id++;
2535 2536 2537 2538
            sm->Rank = 0; /* FIXME */
            sm->Unknown = 0; /* FIXME */
            str.Length = 0;
            str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
Mike McCormack's avatar
Mike McCormack committed
2539
            str.Buffer = (char*)sm->Name;
2540
            RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
Mike McCormack's avatar
Mike McCormack committed
2541 2542
            ptr = strrchr(str.Buffer, '\\');
            sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555

            smi->ModulesCount++;
            sm++;
        }
        else nts = STATUS_INFO_LENGTH_MISMATCH;
    }
    RtlLeaveCriticalSection( &loader_section );

    if (req_size) *req_size = size;

    return nts;
}

2556

2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
{
    NTSTATUS status;
    UNICODE_STRING str;
    ULONG size;
    WCHAR buffer[64];
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;

    RtlInitUnicodeString( &str, name );

    size = sizeof(buffer) - sizeof(WCHAR);
    if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
        return status;

    if (info->Type != REG_DWORD)
    {
        buffer[size / sizeof(WCHAR)] = 0;
        *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
    }
    else memcpy( value, info->Data, sizeof(*value) );
    return status;
}

static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
                                     void *data, ULONG in_size, ULONG *out_size )
{
    NTSTATUS status;
    UNICODE_STRING str;
    ULONG size;
    char *buffer;
    KEY_VALUE_PARTIAL_INFORMATION *info;
    static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );

    RtlInitUnicodeString( &str, name );

    size = info_size + in_size;
    if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
    info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
    status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
    if (!status || status == STATUS_BUFFER_OVERFLOW)
    {
        if (out_size) *out_size = info->DataLength;
        if (data && !status) memcpy( data, info->Data, info->DataLength );
    }
    RtlFreeHeap( GetProcessHeap(), 0, buffer );
    return status;
}


/******************************************************************
 *		LdrQueryImageFileExecutionOptions  (NTDLL.@)
 */
NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
                                                   void *data, ULONG in_size, ULONG *out_size )
{
    static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
                                     'S','o','f','t','w','a','r','e','\\',
                                     'M','i','c','r','o','s','o','f','t','\\',
                                     'W','i','n','d','o','w','s',' ','N','T','\\',
                                     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                     'I','m','a','g','e',' ','F','i','l','e',' ',
                                     'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
    WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING name_str;
    HANDLE hkey;
    NTSTATUS status;
    ULONG len;
    WCHAR *p;

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &name_str;
    attr.Attributes = OBJ_CASE_INSENSITIVE;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;

    if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
    else p = key->Buffer;
    len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
    name_str.Buffer = path;
    name_str.Length = sizeof(optionsW) + len;
    name_str.MaximumLength = name_str.Length;
    memcpy( path, optionsW, sizeof(optionsW) );
    memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
    if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;

    if (type == REG_DWORD)
    {
        if (out_size) *out_size = sizeof(ULONG);
        if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
        else status = STATUS_BUFFER_OVERFLOW;
    }
    else status = query_string_option( hkey, value, type, data, in_size, out_size );

    NtClose( hkey );
    return status;
}


2657 2658 2659 2660 2661 2662 2663 2664
/******************************************************************
 *		RtlDllShutdownInProgress  (NTDLL.@)
 */
BOOLEAN WINAPI RtlDllShutdownInProgress(void)
{
    return process_detaching;
}

2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
/****************************************************************************
 *              LdrResolveDelayLoadedAPI   (NTDLL.@)
 */
void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
                                       PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
                                       IMAGE_THUNK_DATA* addr, ULONG flags )
{
    IMAGE_THUNK_DATA *pIAT, *pINT;
    DELAYLOAD_INFO delayinfo;
    UNICODE_STRING mod;
    const CHAR* name;
    HMODULE *phmod;
    NTSTATUS nts;
    FARPROC fp;
    DWORD id;

    FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);

    phmod = get_rva(base, desc->ModuleHandleRVA);
    pIAT = get_rva(base, desc->ImportAddressTableRVA);
    pINT = get_rva(base, desc->ImportNameTableRVA);
    name = get_rva(base, desc->DllNameRVA);
    id = addr - pIAT;

    if (!*phmod)
    {
        if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
        {
            nts = STATUS_NO_MEMORY;
            goto fail;
        }
        nts = LdrLoadDll(NULL, 0, &mod, phmod);
        RtlFreeUnicodeString(&mod);
        if (nts) goto fail;
    }

    if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
        nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
    else
    {
        const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
        ANSI_STRING fnc;

        RtlInitAnsiString(&fnc, (char*)iibn->Name);
        nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
    }
    if (!nts)
    {
        pIAT[id].u1.Function = (ULONG_PTR)fp;
        return fp;
    }

fail:
    delayinfo.Size = sizeof(delayinfo);
    delayinfo.DelayloadDescriptor = desc;
    delayinfo.ThunkAddress = addr;
    delayinfo.TargetDllName = name;
    delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
    delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
    delayinfo.TargetModuleBase = *phmod;
    delayinfo.Unused = NULL;
    delayinfo.LastError = nts;
    return dllhook(4, &delayinfo);
}
2729

2730 2731 2732 2733
/******************************************************************
 *		LdrShutdownProcess (NTDLL.@)
 *
 */
2734
void WINAPI LdrShutdownProcess(void)
2735 2736
{
    TRACE("()\n");
2737
    process_detaching = TRUE;
2738
    process_detach();
2739 2740
}

2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754

/******************************************************************
 *		RtlExitUserProcess (NTDLL.@)
 */
void WINAPI RtlExitUserProcess( DWORD status )
{
    RtlEnterCriticalSection( &loader_section );
    RtlAcquirePebLock();
    NtTerminateProcess( 0, status );
    LdrShutdownProcess();
    NtTerminateProcess( GetCurrentProcess(), status );
    exit( status );
}

2755 2756 2757 2758
/******************************************************************
 *		LdrShutdownThread (NTDLL.@)
 *
 */
2759
void WINAPI LdrShutdownThread(void)
2760
{
2761 2762
    PLIST_ENTRY mark, entry;
    PLDR_MODULE mod;
2763 2764
    UINT i;
    void **pointers;
2765

2766 2767 2768
    TRACE("()\n");

    /* don't do any detach calls if process is exiting */
2769
    if (process_detaching) return;
2770 2771 2772

    RtlEnterCriticalSection( &loader_section );

2773 2774
    mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
    for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2775
    {
2776 2777 2778
        mod = CONTAINING_RECORD(entry, LDR_MODULE, 
                                InInitializationOrderModuleList);
        if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2779
            continue;
2780
        if ( mod->Flags & LDR_NO_DLL_CALLS )
2781 2782
            continue;

2783 2784
        MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
                        DLL_THREAD_DETACH, NULL );
2785 2786
    }

2787 2788 2789 2790
    RtlAcquirePebLock();
    RemoveEntryList( &NtCurrentTeb()->TlsLinks );
    RtlReleasePebLock();

2791 2792 2793 2794 2795
    if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
    {
        for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
        RtlFreeHeap( GetProcessHeap(), 0, pointers );
    }
2796 2797
    RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
    RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2798 2799 2800
    RtlLeaveCriticalSection( &loader_section );
}

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820

/***********************************************************************
 *           free_modref
 *
 */
static void free_modref( WINE_MODREF *wm )
{
    RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
    RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
    if (wm->ldr.InInitializationOrderModuleList.Flink)
        RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);

    TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
    if (!TRACE_ON(module))
        TRACE_(loaddll)("Unloaded module %s : %s\n",
                        debugstr_w(wm->ldr.FullDllName.Buffer),
                        (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );

    SERVER_START_REQ( unload_dll )
    {
2821
        req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2822 2823 2824 2825
        wine_server_call( req );
    }
    SERVER_END_REQ;

2826
    free_tls_slot( &wm->ldr );
2827
    RtlReleaseActivationContext( wm->ldr.ActivationContext );
2828
    if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2829
    NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2830 2831 2832 2833 2834 2835
    if (cached_modref == wm) cached_modref = NULL;
    RtlFreeUnicodeString( &wm->ldr.FullDllName );
    RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
    RtlFreeHeap( GetProcessHeap(), 0, wm );
}

2836 2837 2838 2839 2840
/***********************************************************************
 *           MODULE_FlushModrefs
 *
 * Remove all unused modrefs and call the internal unloading routines
 * for the library type.
2841 2842
 *
 * The loader_section must be locked while calling this function.
2843 2844 2845
 */
static void MODULE_FlushModrefs(void)
{
2846 2847 2848
    PLIST_ENTRY mark, entry, prev;
    PLDR_MODULE mod;
    WINE_MODREF*wm;
2849

2850 2851
    mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
    for (entry = mark->Blink; entry != mark; entry = prev)
2852
    {
2853
        mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2854 2855
        wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
        prev = entry->Blink;
2856 2857
        if (!mod->LoadCount) free_modref( wm );
    }
2858

2859 2860 2861 2862 2863 2864 2865 2866
    /* check load order list too for modules that haven't been initialized yet */
    mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
    for (entry = mark->Blink; entry != mark; entry = prev)
    {
        mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
        wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
        prev = entry->Blink;
        if (!mod->LoadCount) free_modref( wm );
2867 2868 2869 2870 2871 2872
    }
}

/***********************************************************************
 *           MODULE_DecRefCount
 *
2873
 * The loader_section must be locked while calling this function.
2874 2875 2876 2877 2878
 */
static void MODULE_DecRefCount( WINE_MODREF *wm )
{
    int i;

2879
    if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2880 2881
        return;

2882
    if ( wm->ldr.LoadCount <= 0 )
2883 2884
        return;

2885
    --wm->ldr.LoadCount;
2886
    TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2887

2888
    if ( wm->ldr.LoadCount == 0 )
2889
    {
2890
        wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2891 2892 2893 2894 2895

        for ( i = 0; i < wm->nDeps; i++ )
            if ( wm->deps[i] )
                MODULE_DecRefCount( wm->deps[i] );

2896
        wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
    }
}

/******************************************************************
 *		LdrUnloadDll (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
{
2907
    WINE_MODREF *wm;
2908 2909
    NTSTATUS retv = STATUS_SUCCESS;

2910 2911
    if (process_detaching) return retv;

2912 2913 2914 2915
    TRACE("(%p)\n", hModule);

    RtlEnterCriticalSection( &loader_section );

2916 2917
    free_lib_count++;
    if ((wm = get_modref( hModule )) != NULL)
2918
    {
2919
        TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2920

2921 2922
        /* Recursively decrement reference counts */
        MODULE_DecRefCount( wm );
2923

2924 2925 2926 2927 2928
        /* Call process detach notifications */
        if ( free_lib_count <= 1 )
        {
            process_detach();
            MODULE_FlushModrefs();
2929 2930
        }

2931
        TRACE("END\n");
2932
    }
2933 2934 2935 2936
    else
        retv = STATUS_DLL_NOT_FOUND;

    free_lib_count--;
2937 2938 2939 2940 2941 2942

    RtlLeaveCriticalSection( &loader_section );

    return retv;
}

2943 2944 2945 2946 2947
/***********************************************************************
 *           RtlImageNtHeader   (NTDLL.@)
 */
PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
{
2948
    IMAGE_NT_HEADERS *ret;
2949

2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    __TRY
    {
        IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;

        ret = NULL;
        if (dos->e_magic == IMAGE_DOS_SIGNATURE)
        {
            ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
            if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
        }
    }
2961
    __EXCEPT_PAGE_FAULT
2962
    {
2963
        return NULL;
2964
    }
2965
    __ENDTRY
2966 2967 2968 2969
    return ret;
}


2970 2971 2972 2973 2974 2975 2976 2977 2978
/***********************************************************************
 *           attach_process_dlls
 *
 * Initial attach to all the dlls loaded by the process.
 */
static NTSTATUS attach_process_dlls( void *wm )
{
    NTSTATUS status;

2979
    pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2980

2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
    RtlEnterCriticalSection( &loader_section );
    if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
    {
        if (last_failed_modref)
            ERR( "%s failed to initialize, aborting\n",
                 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
        return status;
    }
    attach_implicitly_loaded_dlls( (LPVOID)1 );
    RtlLeaveCriticalSection( &loader_section );
    return status;
}


2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
/***********************************************************************
 *           load_global_options
 */
static void load_global_options(void)
{
    static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
                                     'S','y','s','t','e','m','\\',
                                     'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                     'C','o','n','t','r','o','l','\\',
                                     'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
    static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
    static const WCHAR critsectW[] = {'C','r','i','t','i','c','a','l','S','e','c','t','i','o','n','T','i','m','e','o','u','t',0};
    static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
    static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
    static const WCHAR decommittotalW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','T','o','t','a','l','F','r','e','e','T','h','r','e','s','h','o','l','d',0};
    static const WCHAR decommitfreeW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','F','r','e','e','B','l','o','c','k','T','h','r','e','s','h','o','l','d',0};

    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING name_str;
    HANDLE hkey;
    ULONG value;

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &name_str;
    attr.Attributes = OBJ_CASE_INSENSITIVE;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &name_str, sessionW );

    if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;

    query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );

    query_dword_option( hkey, critsectW, &value );
    NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;

    query_dword_option( hkey, heapresW, &value );
    NtCurrentTeb()->Peb->HeapSegmentReserve = value;

    query_dword_option( hkey, heapcommitW, &value );
    NtCurrentTeb()->Peb->HeapSegmentCommit = value;

    query_dword_option( hkey, decommittotalW, &value );
    NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;

    query_dword_option( hkey, decommitfreeW, &value );
    NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;

    NtClose( hkey );
}


3048 3049 3050
/***********************************************************************
 *           start_process
 */
3051
static void start_process( void *arg )
3052
{
3053 3054
    struct start_params *start_params = (struct start_params *)arg;
    call_thread_entry_point( start_params->kernel_start, start_params->entry );
3055 3056
}

3057 3058 3059 3060
/******************************************************************
 *		LdrInitializeThunk (NTDLL.@)
 *
 */
3061 3062
void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
                                ULONG_PTR unknown3, ULONG_PTR unknown4 )
3063
{
3064
    static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3065 3066
    NTSTATUS status;
    WINE_MODREF *wm;
3067
    LPCWSTR load_path;
3068
    PEB *peb = NtCurrentTeb()->Peb;
3069
    struct start_params start_params;
3070

3071 3072
    if (main_exe_file) NtClose( main_exe_file );  /* at this point the main module is created */

3073
    /* allocate the modref for the main exe (if not already done) */
3074 3075 3076
    wm = get_modref( peb->ImageBaseAddress );
    assert( wm );
    if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3077
    {
3078 3079
        ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
        exit(1);
3080
    }
3081

3082
    peb->LoaderLock = &loader_section;
3083
    peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3084 3085
    if (!peb->ProcessParameters->WindowTitle.Buffer)
        peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3086
    version_init( wm->ldr.FullDllName.Buffer );
3087
    virtual_set_large_address_space();
3088

3089 3090 3091
    LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
                                       REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );

3092 3093 3094
    /* the main exe needs to be the first in the load order list */
    RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
    InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3095 3096
    RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
    InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3097

3098
    if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
3099
    if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
3100

3101
    actctx_init();
3102 3103
    load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
    if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
3104
    heap_set_debug_flags( GetProcessHeap() );
3105

3106 3107 3108 3109
    /* Store original entrypoint (in case it gets corrupted) */
    start_params.kernel_start = kernel_start;
    start_params.entry = wm->ldr.EntryPoint;

3110 3111
    status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
    if (status != STATUS_SUCCESS) goto error;
3112

3113
    virtual_release_address_space();
3114
    virtual_clear_thread_stack();
3115
    wine_switch_to_stack( start_process, &start_params, NtCurrentTeb()->Tib.StackBase );
3116 3117

error:
3118
    ERR( "Main exe initialization for %s failed, status %x\n",
3119
         debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3120
    NtTerminateProcess( GetCurrentProcess(), status );
3121 3122 3123
}


3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
/***********************************************************************
 *           RtlImageDirectoryEntryToData   (NTDLL.@)
 */
PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
{
    const IMAGE_NT_HEADERS *nt;
    DWORD addr;

    if ((ULONG_PTR)module & 1)  /* mapped as data file */
    {
        module = (HMODULE)((ULONG_PTR)module & ~1);
        image = FALSE;
    }
    if (!(nt = RtlImageNtHeader( module ))) return NULL;
3138 3139
    if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
3140
        const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3141 3142 3143 3144 3145 3146 3147 3148

        if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
        if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
        *size = nt64->OptionalHeader.DataDirectory[dir].Size;
        if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
    }
    else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
    {
3149
        const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3150 3151 3152 3153 3154 3155 3156

        if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
        if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
        *size = nt32->OptionalHeader.DataDirectory[dir].Size;
        if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
    }
    else return NULL;
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169

    /* not mapped as image, need to find the section containing the virtual address */
    return RtlImageRvaToVa( nt, module, addr, NULL );
}


/***********************************************************************
 *           RtlImageRvaToSection   (NTDLL.@)
 */
PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
                                                   HMODULE module, DWORD rva )
{
    int i;
Eric Pouech's avatar
Eric Pouech committed
3170 3171 3172 3173
    const IMAGE_SECTION_HEADER *sec;

    sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
                                        nt->FileHeader.SizeOfOptionalHeader);
3174 3175 3176
    for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
    {
        if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
Eric Pouech's avatar
Eric Pouech committed
3177
            return (PIMAGE_SECTION_HEADER)sec;
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
    }
    return NULL;
}


/***********************************************************************
 *           RtlImageRvaToVa   (NTDLL.@)
 */
PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
                              DWORD rva, IMAGE_SECTION_HEADER **section )
{
    IMAGE_SECTION_HEADER *sec;

    if (section && *section)  /* try this section first */
    {
        sec = *section;
        if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
            goto found;
    }
    if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
 found:
    if (section) *section = sec;
    return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
}
3202 3203


3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
/***********************************************************************
 *           RtlPcToFileHeader   (NTDLL.@)
 */
PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
{
    LDR_MODULE *module;
    PVOID ret = NULL;

    RtlEnterCriticalSection( &loader_section );
    if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
    RtlLeaveCriticalSection( &loader_section );
    *address = ret;
    return ret;
}


3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
/***********************************************************************
 *           NtLoadDriver   (NTDLL.@)
 *           ZwLoadDriver   (NTDLL.@)
 */
NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
{
    FIXME("(%p), stub!\n",DriverServiceName);
    return STATUS_NOT_IMPLEMENTED;
}


/***********************************************************************
 *           NtUnloadDriver   (NTDLL.@)
 *           ZwUnloadDriver   (NTDLL.@)
 */
NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
{
    FIXME("(%p), stub!\n",DriverServiceName);
    return STATUS_NOT_IMPLEMENTED;
}


3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
/******************************************************************
 *		DllMain   (NTDLL.@)
 */
BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
{
    if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
    return TRUE;
}


3252 3253 3254 3255 3256
/******************************************************************
 *		__wine_init_windows_dir   (NTDLL.@)
 *
 * Windows and system dir initialization once kernel32 has been loaded.
 */
3257
void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3258 3259 3260 3261
{
    PLIST_ENTRY mark, entry;
    LPWSTR buffer, p;

3262
    strcpyW( user_shared_data->NtSystemRoot, windir );
3263
    DIR_init_windows_dir( windir, sysdir );
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285

    /* prepend the system dir to the name of the already created modules */
    mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
    for (entry = mark->Flink; entry != mark; entry = entry->Flink)
    {
        LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );

        assert( mod->Flags & LDR_WINE_INTERNAL );

        buffer = RtlAllocateHeap( GetProcessHeap(), 0,
                                  system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
        if (!buffer) continue;
        strcpyW( buffer, system_dir.Buffer );
        p = buffer + strlenW( buffer );
        if (p > buffer && p[-1] != '\\') *p++ = '\\';
        strcpyW( p, mod->FullDllName.Buffer );
        RtlInitUnicodeString( &mod->FullDllName, buffer );
        RtlInitUnicodeString( &mod->BaseDllName, p );
    }
}


3286
/***********************************************************************
3287
 *           __wine_process_init
3288
 */
3289
void __wine_process_init(void)
3290
{
3291
    static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3292

3293 3294 3295
    WINE_MODREF *wm;
    NTSTATUS status;
    ANSI_STRING func_name;
3296
    void (* DECLSPEC_NORETURN CDECL init_func)(void);
3297

3298
    main_exe_file = thread_init();
3299

3300 3301 3302 3303
    /* retrieve current umask */
    FILE_umask = umask(0777);
    umask( FILE_umask );

3304 3305
    load_global_options();

3306
    /* setup the load callback and create ntdll modref */
3307
    wine_dll_set_callback( load_builtin_callback );
3308

3309
    if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3310
    {
3311
        MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3312 3313
        exit(1);
    }
3314 3315 3316
    RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
    LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );

3317 3318 3319 3320
    RtlInitAnsiString( &func_name, "__wine_kernel_init" );
    if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
                                          0, (void **)&init_func )) != STATUS_SUCCESS)
    {
3321
        MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3322 3323 3324
        exit(1);
    }
    init_func();
3325
}