mirrored from https://gitlab.winehq.org/wine/wine.git
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathloader.c
4851 lines (4141 loc) · 167 KB
/
loader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Loader functions
*
* Copyright 1995, 2003 Alexandre Julliard
* Copyright 2002 Dmitry Timoshkov for CodeWeavers
*
* 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
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <assert.h>
#include <stdarg.h>
#include <stdlib.h>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winnt.h"
#include "winioctl.h"
#include "winternl.h"
#include "delayloadhandler.h"
#include "wine/exception.h"
#include "wine/debug.h"
#include "wine/list.h"
#include "ntdll_misc.h"
#include "ddk/ntddk.h"
#include "ddk/wdm.h"
WINE_DEFAULT_DEBUG_CHANNEL(module);
WINE_DECLARE_DEBUG_CHANNEL(relay);
WINE_DECLARE_DEBUG_CHANNEL(snoop);
WINE_DECLARE_DEBUG_CHANNEL(loaddll);
WINE_DECLARE_DEBUG_CHANNEL(imports);
#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)
#ifdef __i386__
static const WCHAR pe_dir[] = L"\\i386-windows";
#elif defined __x86_64__
static const WCHAR pe_dir[] = L"\\x86_64-windows";
#elif defined __arm__
static const WCHAR pe_dir[] = L"\\arm-windows";
#elif defined __aarch64__
static const WCHAR pe_dir[] = L"\\aarch64-windows";
#else
static const WCHAR pe_dir[] = L"";
#endif
/* we don't want to include winuser.h */
#define RT_MANIFEST ((ULONG_PTR)24)
#define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
typedef void (CALLBACK *LDRENUMPROC)(LDR_DATA_TABLE_ENTRY *, void *, BOOLEAN *);
void (FASTCALL *pBaseThreadInitThunk)(DWORD,LPTHREAD_START_ROUTINE,void *) = NULL;
NTSTATUS (WINAPI *__wine_unix_call_dispatcher)( unixlib_handle_t, unsigned int, void * ) = NULL;
static DWORD (WINAPI *pCtrlRoutine)(void *);
SYSTEM_DLL_INIT_BLOCK LdrSystemDllInitBlock = { 0xf0 };
void *__wine_syscall_dispatcher = NULL;
unixlib_handle_t __wine_unixlib_handle = 0;
/* windows directory */
const WCHAR windows_dir[] = L"C:\\windows";
/* system directory with trailing backslash */
const WCHAR system_dir[] = L"C:\\windows\\system32\\";
/* system search path */
static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
static BOOL is_prefix_bootstrap; /* are we bootstrapping the prefix? */
static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
static LONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
static LONG dll_safe_mode = 1; /* dll search mode */
static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
static UNICODE_STRING system_dll_path; /* path to search for system dependency dlls */
static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
static WCHAR *default_load_path; /* default dll search path */
struct dll_dir_entry
{
struct list entry;
WCHAR dir[1];
};
static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
struct ldr_notification
{
struct list entry;
PLDR_DLL_NOTIFICATION_FUNCTION callback;
void *context;
};
static struct list ldr_notifications = LIST_INIT( ldr_notifications );
static const char * const reason_names[] =
{
"PROCESS_DETACH",
"PROCESS_ATTACH",
"THREAD_ATTACH",
"THREAD_DETACH",
};
struct file_id
{
BYTE ObjectId[16];
};
#define HASH_MAP_SIZE 32
static LIST_ENTRY hash_table[HASH_MAP_SIZE];
/* internal representation of loaded modules */
typedef struct _wine_modref
{
LDR_DATA_TABLE_ENTRY ldr;
struct file_id id;
ULONG CheckSum;
BOOL system;
} WINE_MODREF;
static UINT tls_module_count = 32; /* number of modules with TLS directory */
static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
static RTL_CRITICAL_SECTION loader_section;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
{
0, 0, &loader_section,
{ &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
};
static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
static CRITICAL_SECTION dlldir_section;
static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
{
0, 0, &dlldir_section,
{ &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
};
static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
static RTL_CRITICAL_SECTION peb_lock;
static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
{
0, 0, &peb_lock,
{ &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
};
static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
static PEB_LDR_DATA ldr =
{
sizeof(ldr), TRUE, NULL,
{ &ldr.InLoadOrderModuleList, &ldr.InLoadOrderModuleList },
{ &ldr.InMemoryOrderModuleList, &ldr.InMemoryOrderModuleList },
{ &ldr.InInitializationOrderModuleList, &ldr.InInitializationOrderModuleList }
};
static RTL_RB_TREE base_address_index_tree;
static RTL_BITMAP tls_bitmap;
static RTL_BITMAP tls_expansion_bitmap;
static WINE_MODREF *cached_modref;
static WINE_MODREF *current_modref;
static WINE_MODREF *last_failed_modref;
static LDR_DDAG_NODE *node_ntdll, *node_kernel32;
static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, DWORD flags, WINE_MODREF** pwm, BOOL system );
static NTSTATUS process_attach( LDR_DDAG_NODE *node, LPVOID lpReserved );
static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
/* check whether the file name contains a path */
static inline BOOL contains_path( LPCWSTR name )
{
return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
}
#define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
typedef struct _RTL_UNLOAD_EVENT_TRACE
{
void *BaseAddress;
SIZE_T SizeOfImage;
ULONG Sequence;
ULONG TimeDateStamp;
ULONG CheckSum;
WCHAR ImageName[32];
} RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
static unsigned int unload_trace_seq;
static void module_push_unload_trace( const WINE_MODREF *wm )
{
RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
const LDR_DATA_TABLE_ENTRY *ldr = &wm->ldr;
unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
ptr->BaseAddress = ldr->DllBase;
ptr->SizeOfImage = ldr->SizeOfImage;
ptr->Sequence = unload_trace_seq;
ptr->TimeDateStamp = ldr->TimeDateStamp;
ptr->CheckSum = wm->CheckSum;
memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
unload_trace_ptr = unload_traces;
}
static int rtl_rb_tree_put( RTL_RB_TREE *tree, const void *key, RTL_BALANCED_NODE *entry,
int (*compare_func)( const void *key, const RTL_BALANCED_NODE *entry ))
{
RTL_BALANCED_NODE *parent = tree->root;
BOOLEAN right = 0;
int c;
while (parent)
{
if (!(c = compare_func( key, parent ))) return -1;
right = c > 0;
if (!parent->Children[right]) break;
parent = parent->Children[right];
}
RtlRbInsertNodeEx( tree, parent, right, entry );
return 0;
}
static RTL_BALANCED_NODE *rtl_rb_tree_get( RTL_RB_TREE *tree, const void *key,
int (*compare_func)( const void *key, const RTL_BALANCED_NODE *entry ))
{
RTL_BALANCED_NODE *parent = tree->root;
int c;
while (parent)
{
if (!(c = compare_func( key, parent ))) return parent;
parent = parent->Children[c > 0];
}
return NULL;
}
/*********************************************************************
* RtlGetUnloadEventTrace [NTDLL.@]
*/
RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
{
return unload_traces;
}
/*********************************************************************
* RtlGetUnloadEventTraceEx [NTDLL.@]
*/
void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
{
static ULONG element_size = sizeof(*unload_traces);
static ULONG element_count = ARRAY_SIZE(unload_traces);
*size = &element_size;
*count = &element_count;
*trace = &unload_trace_ptr;
}
/*************************************************************************
* call_dll_entry_point
*
* Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
* 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.
*/
#if defined(__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"
__ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
__ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
"movl %esp,%ebp\n\t"
__ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
"pushl %ebx\n\t"
__ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
"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")
"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"
"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")
"popl %ebx\n\t"
__ASM_CFI(".cfi_same_value %ebx\n\t")
"popl %ebp\n\t"
__ASM_CFI(".cfi_def_cfa %esp,4\n\t")
__ASM_CFI(".cfi_same_value %ebp\n\t")
"ret" )
#elif defined(__x86_64__) && !defined(__arm64ec__)
extern BOOL CDECL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
/* Some apps modify rbx in TLS entry point. */
__ASM_GLOBAL_FUNC(call_dll_entry_point,
"pushq %rbx\n\t"
__ASM_SEH(".seh_pushreg %rbx\n\t")
__ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
__ASM_CFI(".cfi_rel_offset %rbx,0\n\t")
"subq $48,%rsp\n\t"
__ASM_SEH(".seh_stackalloc 48\n\t")
__ASM_SEH(".seh_endprologue\n\t")
__ASM_CFI(".cfi_adjust_cfa_offset 48\n\t")
"mov %rcx,%r10\n\t"
"mov %rdx,%rcx\n\t"
"mov %r8d,%edx\n\t"
"mov %r9,%r8\n\t"
"call *%r10\n\t"
"addq $48,%rsp\n\t"
__ASM_CFI(".cfi_adjust_cfa_offset -48\n\t")
"popq %rbx\n\t"
__ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
__ASM_CFI(".cfi_same_value %rbx\n\t")
"ret" )
#else
static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
UINT reason, void *reserved )
{
return proc( module, reason, reserved );
}
#endif
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
/*************************************************************************
* stub_entry_point
*
* Entry point for stub functions.
*/
static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
{
EXCEPTION_RECORD rec;
rec.ExceptionCode = EXCEPTION_WINE_STUB;
rec.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
rec.ExceptionRecord = NULL;
rec.ExceptionAddress = ret_addr;
rec.NumberParameters = 2;
rec.ExceptionInformation[0] = (ULONG_PTR)dll;
rec.ExceptionInformation[1] = (ULONG_PTR)name;
for (;;) RtlRaiseException( &rec );
}
#include "pshpack1.h"
#ifdef __i386__
struct stub
{
BYTE pushl1; /* pushl $name */
const char *name;
BYTE pushl2; /* pushl $dll */
const char *dll;
BYTE call; /* call stub_entry_point */
DWORD entry;
};
#elif defined(__arm__)
struct stub
{
DWORD ldr_r0; /* ldr r0, $dll */
DWORD ldr_r1; /* ldr r1, $name */
DWORD mov_r2_lr; /* mov r2, lr */
DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
const char *dll;
const char *name;
const void* entry;
};
#elif defined(__aarch64__)
struct stub
{
DWORD ldr_x0; /* ldr x0, $dll */
DWORD ldr_x1; /* ldr x1, $name */
DWORD mov_x2_lr; /* mov x2, lr */
DWORD ldr_x16; /* ldr x16, $entry */
DWORD br_x16; /* br x16 */
const char *dll;
const char *name;
const void *entry;
};
#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
#include "poppack.h"
/*************************************************************************
* allocate_stub
*
* Allocate a stub entry point.
*/
static ULONG_PTR allocate_stub( const char *dll, const char *name )
{
#define MAX_SIZE 65536
static struct stub *stubs;
static unsigned int nb_stubs;
struct stub *stub;
if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
if (!stubs)
{
SIZE_T size = MAX_SIZE;
if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
return 0xdeadbeef;
}
stub = &stubs[nb_stubs++];
#ifdef __i386__
stub->pushl1 = 0x68; /* pushl $name */
stub->name = name;
stub->pushl2 = 0x68; /* pushl $dll */
stub->dll = dll;
stub->call = 0xe8; /* call stub_entry_point */
stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
#elif defined(__arm__)
stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
stub->dll = dll;
stub->name = name;
stub->entry = stub_entry_point;
#elif defined(__aarch64__)
stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
stub->br_x16 = 0xd61f0200; /* br x16 */
stub->dll = dll;
stub->name = name;
stub->entry = stub_entry_point;
#else
stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
stub->movq_rdi[1] = 0xb9;
stub->dll = dll;
stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
stub->movq_rsi[1] = 0xba;
stub->name = name;
stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
stub->movq_rsp_rdx[1] = 0x8b;
stub->movq_rsp_rdx[2] = 0x04;
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
return (ULONG_PTR)stub;
}
#else /* __i386__ */
static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
#endif /* __i386__ */
/* call ldr notifications */
static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
{
struct ldr_notification *notify, *notify_next;
LDR_DLL_NOTIFICATION_DATA data;
if (process_detaching && reason == LDR_DLL_NOTIFICATION_REASON_UNLOADED) return;
data.Loaded.Flags = 0;
data.Loaded.FullDllName = &module->FullDllName;
data.Loaded.BaseDllName = &module->BaseDllName;
data.Loaded.DllBase = module->DllBase;
data.Loaded.SizeOfImage = module->SizeOfImage;
LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
{
TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%lu,data=%p,context=%p)\n",
notify->callback, reason, &data, notify->context );
notify->callback(reason, &data, notify->context);
TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%lu,data=%p,context=%p)\n",
notify->callback, reason, &data, notify->context );
}
}
/* compare base address */
static int base_address_compare( const void *key, const RTL_BALANCED_NODE *entry )
{
const LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, BaseAddressIndexNode);
const char *base = key;
if (base < (char *)mod->DllBase) return -1;
if (base > (char *)mod->DllBase) return 1;
return 0;
}
/* compute basename hash */
static ULONG hash_basename( const UNICODE_STRING *basename )
{
ULONG hash = 0;
RtlHashUnicodeString( basename, TRUE, HASH_STRING_ALGORITHM_DEFAULT, &hash );
return hash % HASH_MAP_SIZE;
}
/*************************************************************************
* get_modref
*
* Looks for the referenced HMODULE in the current process
* The loader_section must be locked while calling this function.
*/
static WINE_MODREF *get_modref( HMODULE hmod )
{
PLDR_DATA_TABLE_ENTRY mod;
RTL_BALANCED_NODE *node;
if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
if (!(node = rtl_rb_tree_get( &base_address_index_tree, hmod, base_address_compare ))) return NULL;
mod = CONTAINING_RECORD(node, LDR_DATA_TABLE_ENTRY, BaseAddressIndexNode);
return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
}
/**********************************************************************
* find_basename_module
*
* Find a module from its base name.
* The loader_section must be locked while calling this function
*/
static WINE_MODREF *find_basename_module( LPCWSTR name )
{
PLIST_ENTRY mark, entry;
UNICODE_STRING name_str;
RtlInitUnicodeString( &name_str, name );
if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
return cached_modref;
mark = &hash_table[hash_basename( &name_str )];
for (entry = mark->Flink; entry != mark; entry = entry->Flink)
{
WINE_MODREF *mod = CONTAINING_RECORD(entry, WINE_MODREF, ldr.HashLinks);
if (RtlEqualUnicodeString( &name_str, &mod->ldr.BaseDllName, TRUE ) && !mod->system)
{
cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
return cached_modref;
}
}
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( const UNICODE_STRING *nt_name )
{
PLIST_ENTRY mark, entry;
UNICODE_STRING name = *nt_name;
if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
name.Buffer += 4;
if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
return cached_modref;
mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
for (entry = mark->Flink; entry != mark; entry = entry->Flink)
{
LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
{
cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
return cached_modref;
}
}
return NULL;
}
/**********************************************************************
* find_fileid_module
*
* Find a module from its file id.
* The loader_section must be locked while calling this function
*/
static WINE_MODREF *find_fileid_module( const struct file_id *id )
{
LIST_ENTRY *mark, *entry;
if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
for (entry = mark->Flink; entry != mark; entry = entry->Flink)
{
LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
if (!memcmp( &wm->id, id, sizeof(*id) ))
{
cached_modref = wm;
return wm;
}
}
return NULL;
}
/******************************************************************************
* get_apiset_entry
*/
static NTSTATUS get_apiset_entry( const API_SET_NAMESPACE *map, const WCHAR *name, ULONG len,
const API_SET_NAMESPACE_ENTRY **entry )
{
const API_SET_HASH_ENTRY *hash_entry;
ULONG hash, i, hash_len;
int min, max;
if (len <= 4) return STATUS_INVALID_PARAMETER;
if (wcsnicmp( name, L"api-", 4 ) && wcsnicmp( name, L"ext-", 4 )) return STATUS_INVALID_PARAMETER;
if (!map) return STATUS_APISET_NOT_PRESENT;
for (i = hash_len = 0; i < len; i++)
{
if (name[i] == '.') break;
if (name[i] == '-') hash_len = i;
}
for (i = hash = 0; i < hash_len; i++)
hash = hash * map->HashFactor + ((name[i] >= 'A' && name[i] <= 'Z') ? name[i] + 32 : name[i]);
hash_entry = (API_SET_HASH_ENTRY *)((char *)map + map->HashOffset);
min = 0;
max = map->Count - 1;
while (min <= max)
{
int pos = (min + max) / 2;
if (hash_entry[pos].Hash < hash) min = pos + 1;
else if (hash_entry[pos].Hash > hash) max = pos - 1;
else
{
*entry = (API_SET_NAMESPACE_ENTRY *)((char *)map + map->EntryOffset) + hash_entry[pos].Index;
if ((*entry)->HashedLength != hash_len * sizeof(WCHAR)) break;
if (wcsnicmp( (WCHAR *)((char *)map + (*entry)->NameOffset), name, hash_len )) break;
return STATUS_SUCCESS;
}
}
return STATUS_APISET_NOT_PRESENT;
}
/******************************************************************************
* get_apiset_target
*/
static NTSTATUS get_apiset_target( const API_SET_NAMESPACE *map, const API_SET_NAMESPACE_ENTRY *entry,
const WCHAR *host, UNICODE_STRING *ret )
{
const API_SET_VALUE_ENTRY *value = (API_SET_VALUE_ENTRY *)((char *)map + entry->ValueOffset);
ULONG i, len;
if (!entry->ValueCount) return STATUS_DLL_NOT_FOUND;
if (host)
{
/* look for specific host in entries 1..n, entry 0 is the default */
for (i = 1; i < entry->ValueCount; i++)
{
len = value[i].NameLength / sizeof(WCHAR);
if (!wcsnicmp( host, (WCHAR *)((char *)map + value[i].NameOffset), len ) && !host[len])
{
value += i;
break;
}
}
}
if (!value->ValueOffset) return STATUS_DLL_NOT_FOUND;
ret->Buffer = (WCHAR *)((char *)map + value->ValueOffset);
ret->Length = value->ValueLength;
return STATUS_SUCCESS;
}
/**********************************************************************
* build_import_name
*/
static NTSTATUS build_import_name( WCHAR buffer[256], const char *import, int len )
{
const API_SET_NAMESPACE *map = NtCurrentTeb()->Peb->ApiSetMap;
const API_SET_NAMESPACE_ENTRY *entry;
const WCHAR *host = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
UNICODE_STRING str;
while (len && import[len-1] == ' ') len--; /* remove trailing spaces */
if (len + sizeof(".dll") > 256) return STATUS_DLL_NOT_FOUND;
ascii_to_unicode( buffer, import, len );
buffer[len] = 0;
if (!wcschr( buffer, '.' )) wcscpy( buffer + len, L".dll" );
if (get_apiset_entry( map, buffer, wcslen(buffer), &entry )) return STATUS_SUCCESS;
if (get_apiset_target( map, entry, host, &str )) return STATUS_DLL_NOT_FOUND;
if (str.Length >= 256 * sizeof(WCHAR)) return STATUS_DLL_NOT_FOUND;
TRACE( "found %s for %s\n", debugstr_us(&str), debugstr_w(buffer));
memcpy( buffer, str.Buffer, str.Length );
buffer[str.Length / sizeof(WCHAR)] = 0;
return STATUS_SUCCESS;
}
/**********************************************************************
* append_dll_ext
*/
static WCHAR *append_dll_ext( const WCHAR *name )
{
const WCHAR *ext = wcsrchr( name, '.' );
if (!ext || wcschr( ext, '/' ) || wcschr( ext, '\\'))
{
WCHAR *ret = RtlAllocateHeap( GetProcessHeap(), 0,
wcslen(name) * sizeof(WCHAR) + sizeof(L".dll") );
if (!ret) return NULL;
wcscpy( ret, name );
wcscat( ret, L".dll" );
return ret;
}
return NULL;
}
/***********************************************************************
* is_import_dll_system
*/
static BOOL is_import_dll_system( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_IMPORT_DESCRIPTOR *import )
{
const char *name = get_rva( mod->DllBase, import->Name );
return !_stricmp( name, "ntdll.dll" ) || !_stricmp( name, "kernel32.dll" );
}
/**********************************************************************
* insert_single_list_tail
*/
static void insert_single_list_after( LDRP_CSLIST *list, SINGLE_LIST_ENTRY *prev, SINGLE_LIST_ENTRY *entry )
{
if (!list->Tail)
{
assert( !prev );
entry->Next = entry;
list->Tail = entry;
return;
}
if (!prev)
{
/* Insert at head. */
entry->Next = list->Tail->Next;
list->Tail->Next = entry;
return;
}
entry->Next = prev->Next;
prev->Next = entry;
if (prev == list->Tail) list->Tail = entry;
}
/**********************************************************************
* remove_single_list_entry
*/
static void remove_single_list_entry( LDRP_CSLIST *list, SINGLE_LIST_ENTRY *entry )
{
SINGLE_LIST_ENTRY *prev;
assert( list->Tail );
if (entry->Next == entry)
{
assert( list->Tail == entry );
list->Tail = NULL;
return;
}
prev = list->Tail->Next;
while (prev->Next != entry && prev != list->Tail)
prev = prev->Next;
assert( prev->Next == entry );
prev->Next = entry->Next;
if (list->Tail == entry) list->Tail = prev;
entry->Next = NULL;
}
/**********************************************************************
* add_module_dependency_after
*/
static BOOL add_module_dependency_after( LDR_DDAG_NODE *from, LDR_DDAG_NODE *to,
SINGLE_LIST_ENTRY *dep_after )
{
LDR_DEPENDENCY *dep;
if (!(dep = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*dep) ))) return FALSE;
dep->dependency_from = from;
insert_single_list_after( &from->Dependencies, dep_after, &dep->dependency_to_entry );
dep->dependency_to = to;
insert_single_list_after( &to->IncomingDependencies, NULL, &dep->dependency_from_entry );
return TRUE;
}
/**********************************************************************
* add_module_dependency
*/
static BOOL add_module_dependency( LDR_DDAG_NODE *from, LDR_DDAG_NODE *to )
{
return add_module_dependency_after( from, to, from->Dependencies.Tail );
}
/**********************************************************************
* remove_module_dependency
*/
static void remove_module_dependency( LDR_DEPENDENCY *dep )
{
remove_single_list_entry( &dep->dependency_to->IncomingDependencies, &dep->dependency_from_entry );
remove_single_list_entry( &dep->dependency_from->Dependencies, &dep->dependency_to_entry );
RtlFreeHeap( GetProcessHeap(), 0, dep );
}
/**********************************************************************
* walk_node_dependencies
*/
static NTSTATUS walk_node_dependencies( LDR_DDAG_NODE *node, void *context,
NTSTATUS (*callback)( LDR_DDAG_NODE *, void * ))
{
SINGLE_LIST_ENTRY *entry;
LDR_DEPENDENCY *dep;
NTSTATUS status;
if (!(entry = node->Dependencies.Tail)) return STATUS_SUCCESS;
do
{
entry = entry->Next;
dep = CONTAINING_RECORD( entry, LDR_DEPENDENCY, dependency_to_entry );
assert( dep->dependency_from == node );
if ((status = callback( dep->dependency_to, context ))) break;
} while (entry != node->Dependencies.Tail);
return status;
}
/*************************************************************************
* find_forwarded_export
*
* Find the final function pointer for a forwarded function.
* The loader_section must be locked while calling this function.
*/
static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
{
const IMAGE_EXPORT_DIRECTORY *exports;
DWORD exp_size;
WINE_MODREF *wm;
WCHAR mod_name[256];
const char *end = strrchr(forward, '.');
FARPROC proc = NULL;
if (!end) return NULL;
if (build_import_name( mod_name, forward, end - forward )) return NULL;
if (!(wm = find_basename_module( mod_name )))
{
WINE_MODREF *imp = get_modref( module );
TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
if (load_dll( load_path, mod_name, 0, &wm, imp->system ) == STATUS_SUCCESS &&
!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
{
if (!imports_fixup_done && current_modref)
{
add_module_dependency( current_modref->ldr.DdagNode, wm->ldr.DdagNode );
}
else if (process_attach( wm->ldr.DdagNode, NULL ) != STATUS_SUCCESS)
{
LdrUnloadDll( wm->ldr.DllBase );
wm = NULL;
}
}
if (!wm)
{
ERR( "module not found for forward '%s' used by %s\n",
forward, debugstr_w(imp->ldr.FullDllName.Buffer) );
return NULL;
}
}
if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
{
const char *name = end + 1;
if (*name == '#') { /* ordinal */
proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size,
atoi(name+1) - exports->Base, load_path );
} else
proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
}
if (!proc)
{
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) );
}
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.
*/
static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
{
FARPROC proc;
const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
if (ordinal >= exports->NumberOfFunctions)
{
TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
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 */
if (((const char *)proc >= (const char *)exports) &&
((const char *)proc < (const char *)exports + exp_size))
return find_forwarded_export( module, (const char *)proc, load_path );
if (TRACE_ON(snoop))
{
const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
}
if (TRACE_ON(relay))
{
const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;