libmwemu 0.24.1

x86 32/64bits and system internals emulator, for securely emulating malware and other stuff.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
use lazy_static::lazy_static;
use std::sync::Mutex;

use crate::constants;
use crate::emu;
use crate::emu::Emu;
use crate::peb::peb64;
use crate::serialization;

pub mod activate_act_ctx;
pub mod add_vectored_exception_handler;
pub mod are_file_api_is_ansi;
pub mod begin_update_resource_a;
pub mod close_handle;
pub mod compare_string_w;
pub mod connect_named_pipe;
pub mod copy_file_a;
pub mod copy_file_w;
pub mod create_act_ctx_a;
pub mod create_event_a;
pub mod create_file_a;
pub mod create_file_mapping_a;
pub mod create_file_mapping_w;
pub mod create_file_w;
pub mod create_mutex_a;
pub mod create_mutex_w;
pub mod create_named_pipe_a;
pub mod create_named_pipe_w;
pub mod create_process_a;
pub mod create_process_w;
pub mod create_remote_thread;
pub mod create_thread;
pub mod create_toolhelp32_snapshot;
pub mod decode_pointer;
pub mod delete_file_a;
pub mod disconnect_named_pipe;
pub mod encode_pointer;
pub mod enter_critical_section;
pub mod exit_process;
pub mod expand_environment_strings_a;
pub mod expand_environment_strings_w;
pub mod file_time_to_system_time;
pub mod find_act_ctx_section_string_w;
pub mod find_close;
pub mod find_first_file_a;
pub mod find_first_file_ex_w;
pub mod find_first_file_w;
pub mod find_next_file_a;
pub mod find_next_file_w;
pub mod find_resource_a;
pub mod find_resource_w;
pub mod fls_alloc;
pub mod fls_get_value;
pub mod fls_set_value;
pub mod free_resource;
pub mod get_acp;
pub mod get_command_line_a;
pub mod get_command_line_w;
pub mod get_computer_name_a;
pub mod get_computer_name_w;
pub mod get_console_cp;
pub mod get_console_mode;
pub mod get_console_output_cp;
pub mod get_cp_info;
pub mod get_current_directory_a;
pub mod get_current_directory_w;
pub mod get_current_process;
pub mod get_current_process_id;
pub mod get_current_thread;
pub mod get_current_thread_id;
pub mod get_disk_free_space_a;
pub mod get_environment_strings_w;
pub mod get_environment_variable_w;
pub mod get_file_attributes_a;
pub mod get_file_attributes_w;
pub mod get_file_size;
pub mod get_file_type;
pub mod get_full_path_name_a;
pub mod get_full_path_name_w;
pub mod get_last_error;
pub mod get_local_time;
pub mod get_locale_info_a;
pub mod get_locale_info_w;
pub mod get_logical_drives;
pub mod get_module_file_name_a;
pub mod get_module_file_name_w;
pub mod get_module_handle_a;
pub mod get_module_handle_w;
pub mod get_native_system_info;
pub mod get_proc_address;
pub mod get_process_affinity_mask;
pub mod get_process_heap;
pub mod get_startup_info_a;
pub mod get_startup_info_w;
pub mod get_std_handle;
pub mod get_system_directory_a;
pub mod get_system_directory_w;
pub mod get_system_firmware_table;
pub mod get_system_info;
pub mod get_system_time;
pub mod get_system_time_as_file_time;
pub mod get_temp_path_w;
pub mod get_thread_context;
pub mod get_thread_locale;
pub mod get_tick_count;
pub mod get_time_zone_information;
pub mod get_user_default_lang_id;
pub mod get_user_default_lcid;
pub mod get_version;
pub mod get_version_ex_a;
pub mod get_version_ex_w;
pub mod get_windows_directory_a;
pub mod get_windows_directory_w;
pub mod global_add_atom_a;
pub mod heap_alloc;
pub mod heap_create;
pub mod heap_free;
pub mod heap_re_alloc;
pub mod init_once_begin_initialize;
pub mod initialize_critical_section;
pub mod initialize_critical_section_and_spin_count;
pub mod initialize_critical_section_ex;
pub mod is_bad_read_ptr;
pub mod is_debugger_present;
pub mod is_processor_feature_present;
pub mod leave_critical_section;
pub mod load_library_a;
pub mod load_library_ex_a;
pub mod load_library_ex_w;
pub mod load_library_w;
pub mod load_resource;
pub mod local_alloc;
pub mod lock_resource;
pub mod lstrcat_a;
pub mod lstrcat_w;
pub mod lstrcmpi;
pub mod lstrcmpi_w;
pub mod lstrcpy;
pub mod lstrcpy_w;
pub mod lstrcpyn;
pub mod lstrlen_a;
pub mod lstrlen_w;
pub mod map_view_of_file;
pub mod move_file_a;
pub mod move_file_w;
pub mod multi_byte_to_wide_char;
pub mod open_process;
pub mod open_process_token;
pub mod open_thread;

pub mod process32_first;
pub mod process32_next;
pub mod query_performance_counter;
pub mod read_file;
pub mod read_process_memory;
pub mod reg_close_key;
pub mod reg_create_key_ex_a;
pub mod reg_create_key_ex_w;
pub mod reg_open_key_a;
pub mod reg_set_value_ex_a;
pub mod reg_set_value_ex_w;
pub mod reset_event;

pub mod device_io_control;
mod local_free;
pub mod resume_thread;
pub mod set_current_directory_a;
pub mod set_error_mode;
pub mod set_file_pointer;
pub mod set_last_error;
pub mod set_thread_locale;
pub mod set_thread_stack_guarantee;
pub mod set_unhandled_exception_filter;
pub mod sizeof_resource;
pub mod sleep;
pub mod system_time_to_file_time;
pub mod system_time_to_tz_specific_local_time;
pub mod terminate_process;
pub mod thread32_first;
pub mod thread32_next;
pub mod tls_alloc;
pub mod tls_free;
pub mod tls_get_value;
pub mod tls_set_value;
pub mod unhandled_exception_filter;
pub mod virtual_alloc;
pub mod virtual_alloc_ex;
pub mod virtual_alloc_ex_numa;
pub mod virtual_free;
pub mod virtual_lock;
pub mod virtual_protect;
pub mod virtual_protect_ex;
pub mod wait_for_single_object;
pub mod wide_char_to_multi_byte;
pub mod win_exec;
pub mod write_console_w;
pub mod write_file;
pub mod write_process_memory;
mod GetFileSize;
mod get_file_size_ex;

// Re-export all functions
pub use activate_act_ctx::ActivateActCtx;
pub use add_vectored_exception_handler::AddVectoredExceptionHandler;
pub use are_file_api_is_ansi::AreFileApiIsAnsi;
pub use begin_update_resource_a::BeginUpdateResourceA;
pub use close_handle::CloseHandle;
pub use compare_string_w::CompareStringW;
pub use connect_named_pipe::ConnectNamedPipe;
pub use copy_file_a::CopyFileA;
pub use copy_file_w::CopyFileW;
pub use create_act_ctx_a::CreateActCtxA;
pub use create_event_a::CreateEventA;
pub use create_file_a::CreateFileA;
pub use create_file_mapping_a::CreateFileMappingA;
pub use create_file_mapping_w::CreateFileMappingW;
pub use create_file_w::CreateFileW;
pub use create_mutex_a::CreateMutexA;
pub use create_mutex_w::CreateMutexW;
pub use create_named_pipe_a::CreateNamedPipeA;
pub use create_named_pipe_w::CreateNamedPipeW;
pub use create_process_a::CreateProcessA;
pub use create_process_w::CreateProcessW;
pub use create_remote_thread::CreateRemoteThread;
pub use create_thread::CreateThread;
pub use create_toolhelp32_snapshot::CreateToolhelp32Snapshot;
pub use decode_pointer::DecodePointer;
pub use delete_file_a::DeleteFileA;
pub use disconnect_named_pipe::DisconnectNamedPipe;
pub use encode_pointer::EncodePointer;
pub use enter_critical_section::EnterCriticalSection;
pub use exit_process::ExitProcess;
pub use expand_environment_strings_a::ExpandEnvironmentStringsA;
pub use expand_environment_strings_w::ExpandEnvironmentStringsW;
pub use file_time_to_system_time::FileTimeToSystemTime;
pub use find_act_ctx_section_string_w::FindActCtxSectionStringW;
pub use find_close::FindClose;
pub use find_first_file_a::FindFirstFileA;
pub use find_first_file_ex_w::FindFirstFileExW;
pub use find_first_file_w::FindFirstFileW;
pub use find_next_file_a::FindNextFileA;
pub use find_next_file_w::FindNextFileW;
pub use find_resource_a::FindResourceA;
pub use find_resource_w::FindResourceW;
pub use fls_alloc::FlsAlloc;
pub use fls_get_value::FlsGetValue;
pub use fls_set_value::FlsSetValue;
pub use free_resource::FreeResource;
pub use get_acp::GetACP;
pub use get_command_line_a::GetCommandLineA;
pub use get_command_line_w::GetCommandLineW;
pub use get_computer_name_a::GetComputerNameA;
pub use get_computer_name_w::GetComputerNameW;
pub use get_console_cp::GetConsoleCP;
pub use get_console_mode::GetConsoleMode;
pub use get_console_output_cp::GetConsoleOutputCP;
pub use get_cp_info::GetCPInfo;
pub use get_current_directory_a::GetCurrentDirectoryA;
pub use get_current_directory_w::GetCurrentDirectoryW;
pub use get_current_process::GetCurrentProcess;
pub use get_current_process_id::GetCurrentProcessId;
pub use get_current_thread::GetCurrentThread;
pub use get_current_thread_id::GetCurrentThreadId;
pub use get_disk_free_space_a::GetDiskFreeSpaceA;
pub use get_environment_strings_w::GetEnvironmentStringsW;
pub use get_environment_variable_w::GetEnvironmentVariableW;
pub use get_file_attributes_a::GetFileAttributesA;
pub use get_file_attributes_w::GetFileAttributesW;
pub use get_file_size::GetFileSize;
pub use get_file_type::GetFileType;
pub use get_full_path_name_a::GetFullPathNameA;
pub use get_full_path_name_w::GetFullPathNameW;
pub use get_last_error::GetLastError;
pub use get_local_time::GetLocalTime;
pub use get_locale_info_a::GetLocaleInfoA;
pub use get_locale_info_w::GetLocaleInfoW;
pub use get_logical_drives::GetLogicalDrives;
pub use get_module_file_name_a::GetModuleFileNameA;
pub use get_module_file_name_w::GetModuleFileNameW;
pub use get_module_handle_a::GetModuleHandleA;
pub use get_module_handle_w::GetModuleHandleW;
pub use get_native_system_info::GetNativeSystemInfo;
pub use get_proc_address::GetProcAddress;
pub use get_process_affinity_mask::GetProcessAffinityMask;
pub use get_process_heap::GetProcessHeap;
pub use get_startup_info_a::GetStartupInfoA;
pub use get_startup_info_w::GetStartupInfoW;
pub use get_std_handle::GetStdHandle;
pub use get_system_directory_a::GetSystemDirectoryA;
pub use get_system_directory_w::GetSystemDirectoryW;
pub use get_system_firmware_table::GetSystemFirmwareTable;
pub use get_system_info::GetSystemInfo;
pub use get_system_time::GetSystemTime;
pub use get_system_time_as_file_time::GetSystemTimeAsFileTime;
pub use get_temp_path_w::GetTempPathW;
pub use get_thread_context::GetThreadContext;
pub use get_thread_locale::GetThreadLocale;
pub use get_tick_count::GetTickCount;
pub use get_time_zone_information::GetTimeZoneInformation;
pub use get_user_default_lang_id::GetUserDefaultLangId;
pub use get_user_default_lcid::GetUserDefaultLCID;
pub use get_version::GetVersion;
pub use get_version_ex_a::GetVersionExA;
pub use get_version_ex_w::GetVersionExW;
pub use get_windows_directory_a::GetWindowsDirectoryA;
pub use get_windows_directory_w::GetWindowsDirectoryW;
pub use global_add_atom_a::GlobalAddAtomA;
pub use heap_alloc::HeapAlloc;
pub use heap_create::HeapCreate;
pub use heap_free::HeapFree;
pub use heap_re_alloc::HeapReAlloc;
pub use init_once_begin_initialize::InitOnceBeginInitialize;
pub use initialize_critical_section::InitializeCriticalSection;
pub use initialize_critical_section_and_spin_count::InitializeCriticalSectionAndSpinCount;
pub use initialize_critical_section_ex::InitializeCriticalSectionEx;
pub use is_bad_read_ptr::IsBadReadPtr;
pub use is_debugger_present::IsDebuggerPresent;
pub use is_processor_feature_present::IsProcessorFeaturePresent;
pub use leave_critical_section::LeaveCriticalSection;
pub use load_library_a::LoadLibraryA;
pub use load_library_ex_a::LoadLibraryExA;
pub use load_library_ex_w::LoadLibraryExW;
pub use load_library_w::LoadLibraryW;
pub use load_resource::LoadResource;
pub use local_alloc::LocalAlloc;
pub use lock_resource::LockResource;
pub use lstrcat_a::lstrcatA;
pub use lstrcat_w::lstrcatW;
pub use lstrcmpi::LStrCmpI;
pub use lstrcmpi_w::LStrCmpIW;
pub use lstrcpy::lstrcpy;
pub use lstrcpy_w::lstrcpyW;
pub use lstrcpyn::lstrcpyn;
pub use lstrlen_a::lstrlenA;
pub use lstrlen_w::lstrlenW;
pub use map_view_of_file::MapViewOfFile;
pub use move_file_a::MoveFileA;
pub use move_file_w::MoveFileW;
pub use multi_byte_to_wide_char::MultiByteToWideChar;
pub use open_process::OpenProcess;
pub use open_process_token::OpenProcessToken;
pub use open_thread::OpenThread;

pub use process32_first::Process32First;
pub use process32_next::Process32Next;
pub use query_performance_counter::QueryPerformanceCounter;
pub use read_file::ReadFile;
pub use read_process_memory::ReadProcessMemory;
pub use reg_close_key::RegCloseKey;
pub use reg_create_key_ex_a::RegCreateKeyExA;
pub use reg_create_key_ex_w::RegCreateKeyExW;
pub use reg_open_key_a::RegOpenKeyA;
pub use reg_set_value_ex_a::RegSetValueExA;
pub use reg_set_value_ex_w::RegSetValueExW;
pub use reset_event::ResetEvent;

pub use device_io_control::api_DeviceIoControl;
pub use local_free::LocalFree;
pub use resume_thread::ResumeThread;
pub use set_current_directory_a::SetCurrentDirectoryA;
pub use set_error_mode::SetErrorMode;
pub use set_file_pointer::SetFilePointer;
pub use set_last_error::SetLastError;
pub use set_thread_locale::SetThreadLocale;
pub use set_thread_stack_guarantee::SetThreadStackGuarantee;
pub use set_unhandled_exception_filter::SetUnhandledExceptionFilter;
pub use sizeof_resource::SizeofResource;
pub use sleep::Sleep;
pub use system_time_to_file_time::SystemTimeToFileTime;
pub use system_time_to_tz_specific_local_time::SystemTimeToTzSpecificLocalTime;
pub use terminate_process::TerminateProcess;
pub use thread32_first::Thread32First;
pub use thread32_next::Thread32Next;
pub use tls_alloc::TlsAlloc;
pub use tls_free::TlsFree;
pub use tls_get_value::TlsGetValue;
pub use tls_set_value::TlsSetValue;
pub use unhandled_exception_filter::UnhandledExceptionFilter;
pub use virtual_alloc::VirtualAlloc;
pub use virtual_alloc_ex::VirtualAllocEx;
pub use virtual_alloc_ex_numa::VirtualAllocExNuma;
pub use virtual_free::VirtualFree;
pub use virtual_lock::VirtualLock;
pub use virtual_protect::VirtualProtect;
pub use virtual_protect_ex::VirtualProtectEx;
pub use wait_for_single_object::WaitForSingleObject;
pub use wide_char_to_multi_byte::WideCharToMultiByte;
pub use win_exec::WinExec;
pub use write_console_w::WriteConsoleW;
pub use write_file::WriteFile;
pub use write_process_memory::WriteProcessMemory;
use crate::winapi::winapi64::kernel32::get_file_size_ex::GetFileSizeEx;
// a in RCX, b in RDX, c in R8, d in R9, then e pushed on stack

pub fn clear_last_error(emu: &mut emu::Emu) {
    let mut err = LAST_ERROR.lock().unwrap();
    *err = constants::ERROR_SUCCESS;
}

pub fn gateway(addr: u64, emu: &mut emu::Emu) -> String {
    let api = guess_api_name(emu, addr);
    let api = api.split("!").last().unwrap_or(&api);
    match api {
        "ActivateActCtx" => ActivateActCtx(emu),
        "AddVectoredExceptionHandler" => AddVectoredExceptionHandler(emu),
        "AreFileApiIsAnsi" => AreFileApiIsAnsi(emu),
        "BeginUpdateResourceA" => BeginUpdateResourceA(emu),
        "CloseHandle" => CloseHandle(emu),
        "CompareStringW" => CompareStringW(emu),
        "ConnectNamedPipe" => ConnectNamedPipe(emu),
        "DeleteFileA" => DeleteFileA(emu),
        "CopyFileA" => CopyFileA(emu),
        "CopyFileW" => CopyFileW(emu),
        "CreateActCtxA" => CreateActCtxA(emu),
        "CreateEventA" => CreateEventA(emu),
        "CreateFileA" => CreateFileA(emu),
        "CreateFileW" => CreateFileW(emu),
        "CreateFileMappingA" => CreateFileMappingA(emu),
        "CreateFileMappingW" => CreateFileMappingW(emu),
        "CreateMutexA" => CreateMutexA(emu),
        "CreateMutexW" => CreateMutexW(emu),
        "CreateNamedPipeA" => CreateNamedPipeA(emu),
        "CreateNamedPipeW" => CreateNamedPipeW(emu),
        "CreateProcessA" => CreateProcessA(emu),
        "CreateProcessW" => CreateProcessW(emu),
        "CreateRemoteThread" => CreateRemoteThread(emu),
        "CreateThread" => CreateThread(emu),
        "CreateToolhelp32Snapshot" => CreateToolhelp32Snapshot(emu),
        "DecodePointer" => DecodePointer(emu),
        "DisconnectNamedPipe" => DisconnectNamedPipe(emu),
        "EncodePointer" => EncodePointer(emu),
        "EnterCriticalSection" => EnterCriticalSection(emu),
        "ExitProcess" => ExitProcess(emu),
        "ExpandEnvironmentStringsA" => ExpandEnvironmentStringsA(emu),
        "ExpandEnvironmentStringsW" => ExpandEnvironmentStringsW(emu),
        "FileTimeToSystemTime" => FileTimeToSystemTime(emu),
        "FindActCtxSectionStringW" => FindActCtxSectionStringW(emu),
        "FindClose" => FindClose(emu),
        "FindFirstFileA" => FindFirstFileA(emu),
        "FindFirstFileExW" => FindFirstFileExW(emu),
        "FindFirstFileW" => FindFirstFileW(emu),
        "FindNextFileA" => FindNextFileA(emu),
        "FindNextFileW" => FindNextFileW(emu),
        "FindResourceA" => FindResourceA(emu),
        "FindResourceW" => FindResourceW(emu),
        "FlsAlloc" => FlsAlloc(emu),
        "FlsGetValue" => FlsGetValue(emu),
        "FlsSetValue" => FlsSetValue(emu),
        "FreeResource" => FreeResource(emu),
        "GetACP" => GetACP(emu),
        "GetCommandLineA" => GetCommandLineA(emu),
        "GetCommandLineW" => GetCommandLineW(emu),
        "GetComputerNameA" => GetComputerNameA(emu),
        "GetComputerNameW" => GetComputerNameW(emu),
        "GetDiskFreeSpaceA" => GetDiskFreeSpaceA(emu),
        "GetConsoleCP" => GetConsoleCP(emu),
        "GetConsoleMode" => GetConsoleMode(emu),
        "GetConsoleOutputCP" => GetConsoleOutputCP(emu),
        "GetCPInfo" => GetCPInfo(emu),
        "GetCurrentDirectoryA" => GetCurrentDirectoryA(emu),
        "GetCurrentDirectoryW" => GetCurrentDirectoryW(emu),
        "GetCurrentProcess" => GetCurrentProcess(emu),
        "GetCurrentProcessId" => GetCurrentProcessId(emu),
        "GetCurrentThread" => GetCurrentThread(emu),
        "GetCurrentThreadId" => GetCurrentThreadId(emu),
        "GetEnvironmentStringsW" => GetEnvironmentStringsW(emu),
        "GetEnvironmentVariableW" => GetEnvironmentVariableW(emu),
        "GetFileAttributesA" => GetFileAttributesA(emu),
        "GetFileAttributesW" => GetFileAttributesW(emu),
        "GetFileSize" => GetFileSize(emu),
        "GetFileSizeEx" => GetFileSizeEx(emu),
        "GetFileType" => GetFileType(emu),
        "GetFullPathNameA" => GetFullPathNameA(emu),
        "GetFullPathNameW" => GetFullPathNameW(emu),
        "GetLastError" => GetLastError(emu),
        "GetLocaleInfoA" => GetLocaleInfoA(emu),
        "GetLocaleInfoW" => GetLocaleInfoW(emu),
        "GetLocalTime" => GetLocalTime(emu),
        "GetLogicalDrives" => GetLogicalDrives(emu),
        "GetModuleFileNameA" => GetModuleFileNameA(emu),
        "GetModuleFileNameW" => GetModuleFileNameW(emu),
        "GetModuleHandleA" => GetModuleHandleA(emu),
        "GetModuleHandleW" => GetModuleHandleW(emu),
        "GetNativeSystemInfo" => GetNativeSystemInfo(emu),
        "GetProcAddress" => GetProcAddress(emu),
        "GetProcessAffinityMask" => GetProcessAffinityMask(emu),
        "GetProcessHeap" => GetProcessHeap(emu),
        "GetStartupInfoA" => GetStartupInfoA(emu),
        "GetStartupInfoW" => GetStartupInfoW(emu),
        "GetStdHandle" => GetStdHandle(emu),
        "GetThreadId" => GetThreadId(emu),
        "GetSystemDirectoryA" => GetSystemDirectoryA(emu),
        "GetSystemDirectoryW" => GetSystemDirectoryW(emu),
        "GetSystemFirmwareTable" => GetSystemFirmwareTable(emu),
        "GetSystemInfo" => GetSystemInfo(emu),
        "GetSystemTime" => GetSystemTime(emu),
        "GetSystemTimeAsFileTime" => GetSystemTimeAsFileTime(emu),
        "GetTempPathW" => GetTempPathW(emu),
        "GetThreadContext" => GetThreadContext(emu),
        "GetThreadLocale" => GetThreadLocale(emu),
        "GetTickCount" => GetTickCount(emu),
        "GetTimeZoneInformation" => GetTimeZoneInformation(emu),
        "GetUserDefaultLangId" => GetUserDefaultLangId(emu),
        "GetUserDefaultLCID" => GetUserDefaultLCID(emu),
        "GetVersion" => GetVersion(emu),
        "GetVersionExA" => GetVersionExA(emu),
        "GetVersionExW" => GetVersionExW(emu),
        "GetWindowsDirectoryA" => GetWindowsDirectoryA(emu),
        "GetWindowsDirectoryW" => GetWindowsDirectoryW(emu),
        "GlobalAddAtomA" => GlobalAddAtomA(emu),
        "HeapAlloc" => HeapAlloc(emu),
        "HeapCreate" => HeapCreate(emu),
        "HeapFree" => HeapFree(emu),
        "HeapReAlloc" => HeapReAlloc(emu),
        "InitializeCriticalSection" => InitializeCriticalSection(emu),
        "InitializeCriticalSectionAndSpinCount" => InitializeCriticalSectionAndSpinCount(emu),
        "InitializeCriticalSectionEx" => InitializeCriticalSectionEx(emu),
        "InitOnceBeginInitialize" => InitOnceBeginInitialize(emu),
        "IsBadReadPtr" => IsBadReadPtr(emu),
        "IsDebuggerPresent" => IsDebuggerPresent(emu),
        "IsProcessorFeaturePresent" => IsProcessorFeaturePresent(emu),
        "LeaveCriticalSection" => LeaveCriticalSection(emu),
        "LoadLibraryA" => LoadLibraryA(emu),
        "LoadLibraryExA" => LoadLibraryExA(emu),
        "LoadLibraryExW" => LoadLibraryExW(emu),
        "LoadLibraryW" => LoadLibraryW(emu),
        "LoadResource" => LoadResource(emu),
        "LocalAlloc" => LocalAlloc(emu),
        "LocalFree" => LocalFree(emu),
        "LockResource" => LockResource(emu),
        "lstrcatA" => lstrcatA(emu),
        "lstrcatW" => lstrcatW(emu),
        "LStrCmpI" => LStrCmpI(emu),
        "lstrcmpiW" => LStrCmpIW(emu),
        "LStrCmpIW" => LStrCmpIW(emu),
        "lstrcpy" => lstrcpy(emu),
        "lstrcpyn" => lstrcpyn(emu),
        "lstrcpyW" => lstrcpyW(emu),
        "lstrlenA" => lstrlenA(emu),
        "lstrlenW" => lstrlenW(emu),
        "MapViewOfFile" => MapViewOfFile(emu),
        "MoveFileA" => MoveFileA(emu),
        "MoveFileW" => MoveFileW(emu),
        "MultiByteToWideChar" => MultiByteToWideChar(emu),
        "OpenProcess" => OpenProcess(emu),
        "OpenProcessToken" => OpenProcessToken(emu),
        "OpenThread" => OpenThread(emu),

        "Process32First" => Process32First(emu),
        "Process32Next" => Process32Next(emu),
        "QueryPerformanceCounter" => QueryPerformanceCounter(emu),
        "ReadFile" => ReadFile(emu),
        "ReadProcessMemory" => ReadProcessMemory(emu),
        "RegCloseKey" => RegCloseKey(emu),
        "RegCreateKeyExA" => RegCreateKeyExA(emu),
        "RegCreateKeyExW" => RegCreateKeyExW(emu),
        "RegOpenKeyA" => RegOpenKeyA(emu),
        "RegSetValueExA" => RegSetValueExA(emu),
        "RegSetValueExW" => RegSetValueExW(emu),
        "ResetEvent" => ResetEvent(emu),

        "ResumeThread" => ResumeThread(emu),
        "SetCurrentDirectoryA" => SetCurrentDirectoryA(emu),
        "SetErrorMode" => SetErrorMode(emu),
        "SetFilePointer" => SetFilePointer(emu),
        "SetLastError" => SetLastError(emu),
        "SetThreadLocale" => SetThreadLocale(emu),
        "SetThreadStackGuarantee" => SetThreadStackGuarantee(emu),
        "SetUnhandledExceptionFilter" => SetUnhandledExceptionFilter(emu),
        "SizeofResource" => SizeofResource(emu),
        "Sleep" => Sleep(emu),
        "SystemTimeToFileTime" => SystemTimeToFileTime(emu),
        "SystemTimeToTzSpecificLocalTime" => SystemTimeToTzSpecificLocalTime(emu),
        "TerminateProcess" => TerminateProcess(emu),
        "Thread32First" => Thread32First(emu),
        "Thread32Next" => Thread32Next(emu),
        "TlsAlloc" => TlsAlloc(emu),
        "TlsFree" => TlsFree(emu),
        "TlsGetValue" => TlsGetValue(emu),
        "TlsSetValue" => TlsSetValue(emu),
        "UnhandledExceptionFilter" => UnhandledExceptionFilter(emu),
        "VirtualAlloc" => VirtualAlloc(emu),
        "VirtualAllocEx" => VirtualAllocEx(emu),
        "VirtualAllocExNuma" => VirtualAllocExNuma(emu),
        "VirtualFree" => VirtualFree(emu),
        "VirtualLock" => VirtualLock(emu),
        "VirtualProtect" => VirtualProtect(emu),
        "VirtualProtectEx" => VirtualProtectEx(emu),
        "WaitForSingleObject" => WaitForSingleObject(emu),
        "WideCharToMultiByte" => WideCharToMultiByte(emu),
        "WinExec" => WinExec(emu),
        "WriteConsoleW" => WriteConsoleW(emu),
        "WriteFile" => WriteFile(emu),
        "WriteProcessMemory" => WriteProcessMemory(emu),
        "DeviceIoControl" => api_DeviceIoControl(emu),
        _ => {
            if emu.cfg.skip_unimplemented == false {
                if emu.cfg.dump_on_exit && emu.cfg.dump_filename.is_some() {
                    serialization::Serialization::dump_to_file(
                        &emu,
                        emu.cfg.dump_filename.as_ref().unwrap(),
                    );
                }

                unimplemented!("atemmpt to call unimplemented API 0x{:x} {}", addr, api);
            }
            log::warn!(
                "calling unimplemented API 0x{:x} {} at 0x{:x}",
                addr,
                api,
                emu.regs().rip
            );
            return api.to_ascii_lowercase();
        }
    }

    String::new()
}

fn GetThreadId(emu: &mut Emu) {
    let hndl = emu.regs().rcx;

    for i in 0..emu.threads.len() {
        if emu.threads[i].handle == hndl {
            emu.regs_mut().rax = emu.threads[i].id;
            log_red!(
                emu,
                "kernel32!GetThreadId hndl:{} (requested handle exists and its tid {})",
                hndl,
                emu.threads[i].id
            );
            return;
        }
    }
    log_red!(emu, "kernel32!GetThreadId hndl:{} (requested handle doesn't exist, returning a fake handle for now but should return zero.)", hndl);
    emu.regs_mut().rax = 0x2c2878; // if handle not found should return zero.
}

lazy_static! {
    pub static ref COUNT_READ: Mutex<u32> = Mutex::new(0);
    pub static ref COUNT_WRITE: Mutex<u32> = Mutex::new(0);
    pub static ref LAST_ERROR: Mutex<u64> = Mutex::new(0);
}

pub fn set_last_error(err_code: u64) {
    let mut guard = LAST_ERROR.lock().unwrap();
    *guard = err_code;
}

pub fn dump_module_iat(emu: &mut emu::Emu, module: &str) {
    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();

    loop {
        if flink.mod_name.to_lowercase().contains(module) && flink.export_table_rva > 0 {
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let ordinal = flink.get_function_ordinal(emu, i);
                log::trace!(
                    "0x{:x} {}!{}",
                    ordinal.func_va,
                    &flink.mod_name,
                    &ordinal.func_name
                );
            }
        }
        flink.next(emu);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }
}

pub fn resolve_api_addr_to_name(emu: &mut emu::Emu, addr: u64) -> String {
    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();

    loop {
        if flink.export_table_rva > 0 {
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let ordinal = flink.get_function_ordinal(emu, i);
                if ordinal.func_va == addr {
                    let s = ordinal.func_name.to_string();
                    return s;
                }
            }
        }
        flink.next(emu);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }

    "".to_string()
}

fn module_name_matches(flink_mod: &str, want: &str) -> bool {
    let mn = flink_mod.to_lowercase();
    let mn_base = mn.rsplit_once('\\').map(|(_, x)| x).unwrap_or(&mn);
    let mn_base = mn_base.strip_suffix(".dll").unwrap_or(mn_base);
    let want = want.to_lowercase();
    let want = want.strip_suffix(".dll").unwrap_or(&want);
    mn_base == want
}

fn resolve_in_module_exports_depth(
    emu: &mut emu::Emu,
    module_hint: &str,
    name: &str,
    depth: u32,
) -> u64 {
    if depth > 8 {
        return 0;
    }
    let want = module_hint.trim().to_lowercase();
    let want = want.strip_suffix(".dll").unwrap_or(&want);

    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();
    loop {
        if flink.export_table_rva > 0 && module_name_matches(&flink.mod_name, want) {
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let func_name_rva = emu
                    .maps
                    .read_dword(flink.func_name_tbl + i * 4)
                    .unwrap_or(0) as u64;
                let export_name = emu.maps.read_string(func_name_rva + flink.mod_base);
                if export_name.to_lowercase() != name.to_lowercase() {
                    continue;
                }

                let ordinal = flink.get_function_ordinal_depth(emu, i, depth);
                return ordinal.func_va;
            }
        }
        flink.next(emu);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }

    0
}

/// Resolve `name` preferring the module named in the PE import table (`KERNEL32.DLL`, etc.).
/// API-set / `ext-ms-*` names are mapped to the backing DLLs used in `maps64` (see `get_dependencies`).
pub fn resolve_api_name_in_module(emu: &mut emu::Emu, module: &str, name: &str) -> u64 {
    let module_lc = module.trim().to_lowercase();

    if module_lc.starts_with("api-ms-win-") {
        let addr = resolve_in_module_exports_depth(emu, "kernelbase.dll", name, 0);
        if addr != 0 {
            return addr;
        }
        let addr = resolve_in_module_exports_depth(emu, "kernel32.dll", name, 0);
        if addr != 0 {
            return addr;
        }
        return 0;
    }
    if module_lc.starts_with("ext-ms-") {
        let addr = resolve_in_module_exports_depth(emu, "kernelbase.dll", name, 0);
        if addr != 0 {
            return addr;
        }
        let addr = resolve_in_module_exports_depth(emu, "kernel32.dll", name, 0);
        if addr != 0 {
            return addr;
        }
        return 0;
    }

    let addr = resolve_in_module_exports_depth(emu, &module_lc, name, 0);
    if addr != 0 {
        return addr;
    }
    resolve_api_name(emu, name)
}

/// Resolve a PE export forwarder string (`KERNELBASE.QueryPerformanceCounter`).
pub fn resolve_forwarded_export_string(emu: &mut emu::Emu, forwarder: &str) -> u64 {
    resolve_forwarded_export_string_depth(emu, forwarder, 0)
}

pub(crate) fn resolve_forwarded_export_string_depth(
    emu: &mut emu::Emu,
    forwarder: &str,
    inner_depth: u32,
) -> u64 {
    if inner_depth > 8 {
        return 0;
    }
    let forwarder = forwarder.trim();
    let Some(dot) = forwarder.find('.') else {
        return 0;
    };
    let dll_part = forwarder[..dot].trim();
    let sym_part = forwarder[dot + 1..].trim();
    if dll_part.is_empty() || sym_part.is_empty() {
        return 0;
    }
    let dll = if dll_part.to_lowercase().ends_with(".dll") {
        dll_part.to_lowercase()
    } else {
        format!("{}.dll", dll_part.to_lowercase())
    };
    // Avoid re-entering the PE loader during export resolution (can recurse from delay-load binding).
    // Forwarders should resolve against already-linked modules in the current LDR state.
    let mapped_dll = if dll.starts_with("api-ms-win-") || dll.starts_with("ext-ms-") {
        "kernelbase.dll".to_string()
    } else {
        dll
    };
    if peb64::get_module_base(&mapped_dll, emu).is_none() {
        return 0;
    }
    resolve_in_module_exports_depth(emu, &mapped_dll, sym_part, inner_depth)
}

pub fn resolve_api_name(emu: &mut emu::Emu, name: &str) -> u64 {
    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();
    loop {
        if flink.export_table_rva > 0 {
            //println!("export_table_rva: 0x{:x}", flink.export_table_rva);
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let ordinal = flink.get_function_ordinal(emu, i);
                if ordinal.func_name.to_lowercase() == name.to_lowercase() {
                    //if ordinal.func_name.contains(name) {
                    //println!("found api id:{} name: 0x{:x} {}!{}", i, ordinal.func_va, flink.mod_name, ordinal.func_name);
                    return ordinal.func_va;
                }
            }
        }
        flink.next(emu);

        //log::trace!("flink: 0x{:x} first_ptr: 0x{:x}", flink.get_ptr(), first_ptr);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }

    0 //TODO: use Option<>
}

pub fn search_api_name(emu: &mut emu::Emu, name: &str) -> (u64, String, String) {
    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();

    loop {
        if flink.export_table_rva > 0 {
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let ordinal = flink.get_function_ordinal(emu, i);
                if ordinal.func_name.contains(name) {
                    return (
                        ordinal.func_va,
                        flink.mod_name.clone(),
                        ordinal.func_name.clone(),
                    );
                }
            }
        }
        flink.next(emu);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }

    (0, String::new(), String::new()) //TODO: use Option<>
}

pub fn guess_api_name(emu: &mut emu::Emu, addr: u64) -> String {
    let mut flink = peb64::Flink::new(emu);
    flink.load(emu);
    let first_ptr = flink.get_ptr();

    loop {
        //let mod_name = flink.mod_name.clone();

        if flink.export_table_rva > 0 {
            for i in 0..flink.num_of_funcs {
                if flink.pe_hdr == 0 {
                    continue;
                }

                let ordinal = flink.get_function_ordinal(emu, i);

                if ordinal.func_va == addr {
                    let lib = flink
                        .mod_name
                        .rsplit_once('.')
                        .map(|(name, _)| name)
                        .unwrap_or(&flink.mod_name);

                    let s = format!("{}!{}", lib, ordinal.func_name);
                    return s;
                }
            }
        }

        flink.next(emu);

        if flink.get_ptr() == first_ptr {
            break;
        }
    }

    "".to_string()
}

pub fn is_library_loaded(emu: &mut emu::Emu, libname: &str) -> bool {
    let mut dll = libname.to_string().to_lowercase();

    if dll.is_empty() {
        return false;
    }

    if !dll.ends_with(".dll") {
        dll.push_str(".dll");
    }

    let mut dll_path = emu.cfg.maps_folder.clone();
    dll_path.push('/');
    dll_path.push_str(&dll);

    match peb64::get_module_base(&dll, emu) {
        Some(base) => true,
        None => false,
    }
}

pub fn load_library(emu: &mut emu::Emu, libname: &str) -> u64 {
    // log::trace!("kern32!load_library: {}", libname);

    let mut dll = libname.to_string().to_lowercase();

    if dll.is_empty() {
        emu.regs_mut().rax = 0;
        return 0;
    }

    if !dll.ends_with(".dll") {
        dll.push_str(".dll");
    }

    // API set DLL names are virtual contracts that map to host DLLs.
    if dll.starts_with("api-ms-win-") || dll.starts_with("ext-ms-") {
        if peb64::get_module_base("kernelbase.dll", emu).is_some() {
            return peb64::get_module_base("kernelbase.dll", emu).unwrap_or(0);
        }
        if peb64::get_module_base("kernel32.dll", emu).is_some() {
            return peb64::get_module_base("kernel32.dll", emu).unwrap_or(0);
        }
        dll = "kernelbase.dll".to_string();
    }

    let mut dll_path = emu.cfg.maps_folder.clone();
    dll_path.push_str(&dll);

    match peb64::get_module_base(&dll, emu) {
        Some(base) => {
            // already linked
            if emu.cfg.verbose > 0 {
                log::trace!("dll {} already linked.", dll);
            }
            base
        }
        None => {
            // do link
            let path =  std::path::Path::new(&dll_path);
            if path.try_exists().unwrap() {
                let (base, pe_off) = emu.load_pe64(&dll_path, false, 0);
                peb64::dynamic_link_module(base, pe_off, &dll, emu);
                emu.library_loaded = true; // Signal to GDB that library list changed
                base
            } else {
                log::trace!("dll {} not found.", dll_path);
                0
            }
        }
    }
}

pub fn get_library_handle(emu: &mut emu::Emu, libname: &str) -> u64 {
    // log::trace!("kern32!load_library: {}", libname);

    let mut dll = libname.to_string().to_lowercase();

    if dll.is_empty() {
        emu.regs_mut().rax = 0;
        return 0;
    }

    if !dll.ends_with(".dll") {
        dll.push_str(".dll");
    }

    let mut dll_path = emu.cfg.maps_folder.clone();
    dll_path.push('/');
    dll_path.push_str(&dll);

    match peb64::get_module_base(&dll, emu) {
        Some(base) => {
            return base;
        }
        None => {
            // if is not linked, don't link, this is not a load_library
            return 0;
        }
    }
}