├── .gitignore ├── FullSpeed.sln ├── LICENSE ├── README.md ├── afl-fuzz ├── afl-fuzz.c ├── afl-fuzz.vcxproj ├── afl-fuzz.vcxproj.filters ├── afl.h ├── alloc-inl.h ├── config.h ├── debug.h ├── forkserver.c ├── forkserver.h ├── fullspeed.c ├── fullspeed.h ├── hash.h ├── process.c ├── process.h ├── pt_cpu.c ├── ptdecode.c ├── ptdecode.h ├── types.h ├── utils.h ├── winaflpt.cpp └── winaflpt.h ├── docs ├── IdaInstall.png ├── architecture.png ├── dir.png ├── forkserverError.png ├── installPythonToPath.png ├── rabbit.png ├── scriptFile.png ├── soultionExplorer.png ├── startupItem.png ├── toyExample.png ├── vmSetup.png ├── walkthrough.md ├── winnieSuccess.png └── winnieWorking.png ├── experiments ├── CreateUserProcess_benchmark │ ├── CreateUserProcess_benchmark.cpp │ ├── CreateUserProcess_benchmark.vcxproj │ ├── CreateUserProcess_benchmark.vcxproj.filters │ ├── pch.cpp │ └── pch.h ├── README.md ├── debugger │ ├── debugger.cpp │ ├── debugger.vcxproj │ ├── debugger.vcxproj.filters │ ├── pch.cpp │ └── pch.h ├── dump_parser │ ├── README.md │ ├── dump_parser.cpp │ ├── dump_parser.vcxproj │ ├── dump_parser.vcxproj.filters │ ├── pch.cpp │ └── pch.h ├── hook-example │ ├── hook-example.cpp │ ├── hook-example.vcxproj │ ├── hook-example.vcxproj.filters │ ├── pch.cpp │ └── pch.h └── test_fork_with_pt │ ├── .gitignore │ ├── README.md │ ├── debug.h │ ├── pch.cpp │ ├── pch.h │ ├── pt_cpu.c │ ├── ptdecode.cpp │ ├── ptdecode.h │ ├── test_fork_with_pt.cpp │ ├── test_fork_with_pt.vcxproj │ └── test_fork_with_pt.vcxproj.filters ├── forklib ├── .gitignore ├── csrss.cpp ├── csrss.h ├── dllmain.cpp ├── fork.cpp ├── fork.h ├── forklib.cpp ├── forklib.vcxproj ├── forklib.vcxproj.filters ├── gen_csrss_offsets.py ├── handle_inherit.cpp ├── include │ └── forklib.h ├── pdbparse │ ├── __init__.py │ ├── dbgold.py │ ├── dbi.py │ ├── fpo.py │ ├── gdata.py │ ├── info.py │ ├── omap.py │ ├── pe.py │ ├── peinfo.py │ ├── postfix_eval.py │ ├── symlookup.py │ ├── tpi.py │ ├── undecorate.py │ └── undname.py ├── phnt │ ├── README.md │ ├── include │ │ ├── ntdbg.h │ │ ├── ntexapi.h │ │ ├── ntgdi.h │ │ ├── ntioapi.h │ │ ├── ntkeapi.h │ │ ├── ntldr.h │ │ ├── ntlpcapi.h │ │ ├── ntmisc.h │ │ ├── ntmmapi.h │ │ ├── ntnls.h │ │ ├── ntobapi.h │ │ ├── ntpebteb.h │ │ ├── ntpfapi.h │ │ ├── ntpnpapi.h │ │ ├── ntpoapi.h │ │ ├── ntpsapi.h │ │ ├── ntregapi.h │ │ ├── ntrtl.h │ │ ├── ntsam.h │ │ ├── ntseapi.h │ │ ├── ntsmss.h │ │ ├── nttmapi.h │ │ ├── nttp.h │ │ ├── ntwow64.h │ │ ├── ntxcapi.h │ │ ├── ntzwapi.h │ │ ├── phnt.h │ │ ├── phnt_ntdef.h │ │ ├── phnt_windows.h │ │ ├── subprocesstag.h │ │ └── winsta.h │ └── zw_options.txt ├── stdafx.cpp ├── stdafx.h ├── targetver.h ├── windows_phnt.h └── wow64ext.h ├── forkserver-proto.h ├── harness-api.h ├── harnessgen ├── .gitignore ├── README.md ├── common.py ├── dominator.py ├── harconf.py ├── harnessor.py ├── lib │ ├── .gitignore │ └── Tracer │ │ ├── Tracer.sln │ │ ├── Tracer.vcxproj │ │ └── library_trace.cpp ├── logger.py ├── requirements.txt ├── syn-multi.py ├── synthesizer.py ├── template.py ├── util.py └── util │ └── ida_func_type.py ├── injected-harness ├── README.md ├── Source.def ├── dllmain.cpp ├── exports.h ├── hookcallback.asm ├── injected-harness.cpp ├── injected-harness.vcxproj ├── injected-harness.vcxproj.filters ├── stdafx.cpp ├── stdafx.h └── targetver.h ├── intel-libipt ├── LICENSE ├── README.txt ├── Win32 │ ├── libipt.dll │ └── libipt.lib ├── include │ ├── intel-pt.h │ └── internal │ │ ├── posix │ │ └── pt_section_posix.h │ │ ├── pt_asid.h │ │ ├── pt_block_cache.h │ │ ├── pt_block_decoder.h │ │ ├── pt_config.h │ │ ├── pt_cpu.h │ │ ├── pt_cpuid.h │ │ ├── pt_decoder_function.h │ │ ├── pt_encoder.h │ │ ├── pt_event_queue.h │ │ ├── pt_ild.h │ │ ├── pt_image.h │ │ ├── pt_image_section_cache.h │ │ ├── pt_insn.h │ │ ├── pt_insn_decoder.h │ │ ├── pt_last_ip.h │ │ ├── pt_mapped_section.h │ │ ├── pt_msec_cache.h │ │ ├── pt_opcodes.h │ │ ├── pt_packet.h │ │ ├── pt_packet_decoder.h │ │ ├── pt_query_decoder.h │ │ ├── pt_retstack.h │ │ ├── pt_section.h │ │ ├── pt_section_file.h │ │ ├── pt_sync.h │ │ ├── pt_time.h │ │ ├── pt_tnt_cache.h │ │ ├── pti-disp-defs.h │ │ ├── pti-disp.h │ │ ├── pti-disp_default.h │ │ ├── pti-imm-defs.h │ │ ├── pti-imm.h │ │ ├── pti-modrm-defs.h │ │ ├── pti-modrm.h │ │ ├── pti-sib.h │ │ └── windows │ │ └── pt_section_windows.h ├── libipt.dll └── libipt.lib ├── ipttool ├── LICENSE ├── README.txt ├── include │ └── ipttool.h ├── ipttool.c └── ipttool.vcxproj ├── libipt ├── LICENSE ├── README.txt ├── include │ ├── ipt.h │ ├── libipt.h │ └── libiptnt.h ├── libipt.vcxproj └── win32.c ├── minidump_config.reg ├── samples ├── desrubi_harness │ ├── DerusbiWrap.cpp │ └── main.cpp ├── srcds_bsp_harness │ ├── csgo.h │ └── harness.cpp └── toy_example │ ├── Harness.cpp │ ├── README.md │ ├── example.cc │ ├── example.def │ ├── example_library.cpp │ ├── example_library.vcxproj │ ├── example_library.vcxproj.filters │ ├── harness.vcxproj │ ├── harness.vcxproj.filters │ ├── in │ └── input │ ├── toy_example.sln │ ├── toy_example.vcxproj │ └── toy_example.vcxproj.filters ├── scripts ├── ghidra_basic_blocks.py └── ida_basic_blocks.py └── wow64ext ├── CMemPtr.h ├── README.md ├── internal.h ├── lgpl-3.0.txt ├── resource.h ├── wow64ext.cpp ├── wow64ext.h ├── wow64ext.rc └── wow64ext.vcxproj /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 gts3.org (SSLab@Gatech) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /afl-fuzz/afl-fuzz.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | Source Files 23 | 24 | 25 | Source Files 26 | 27 | 28 | Source Files 29 | 30 | 31 | Source Files 32 | 33 | 34 | Source Files 35 | 36 | 37 | Source Files 38 | 39 | 40 | 41 | 42 | Header Files 43 | 44 | 45 | Header Files 46 | 47 | 48 | Header Files 49 | 50 | 51 | Header Files 52 | 53 | 54 | Header Files 55 | 56 | 57 | Header Files 58 | 59 | 60 | Header Files 61 | 62 | 63 | Header Files 64 | 65 | 66 | Header Files 67 | 68 | 69 | Header Files 70 | 71 | 72 | Header Files 73 | 74 | 75 | Header Files 76 | 77 | 78 | 79 | 80 | Header Files 81 | 82 | 83 | -------------------------------------------------------------------------------- /afl-fuzz/afl.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /* Execution status fault codes */ 4 | 5 | enum { 6 | /* 00 */ FAULT_NONE, 7 | /* 01 */ FAULT_TMOUT, 8 | /* 02 */ FAULT_CRASH, 9 | /* 03 */ FAULT_ERROR, 10 | /* 04 */ FAULT_NOINST, 11 | /* 05 */ FAULT_NOBITS 12 | }; 13 | 14 | u64 get_cur_time(void); 15 | char *argv_to_cmd(char** argv); 16 | 17 | extern volatile u8 stop_soon; 18 | 19 | extern u8 use_fork; 20 | extern u8 use_fullspeed; 21 | extern u8 use_intelpt; 22 | extern u8 forkserver_same_console; 23 | 24 | extern s32 forksrv_pid; 25 | extern s32 persistent_pid; 26 | 27 | extern u32 queued_paths; 28 | extern char run_dryrun; 29 | extern u8 *out_dir; 30 | extern u8 *trace_bits; 31 | extern u8 *binary_name; 32 | extern char *out_file; 33 | extern char no_trim; 34 | 35 | extern u64 mem_limit; 36 | extern u64 cpu_aff; 37 | extern u64 total_execs; 38 | 39 | extern char *fuzzer_id; 40 | extern struct winafl_breakpoint *breakpoints; 41 | 42 | char *argv_to_cmd(char** argv); 43 | char *alloc_printf(const char *_str, ...); 44 | -------------------------------------------------------------------------------- /afl-fuzz/forkserver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include // CLIENT_ID 5 | 6 | #include "../forkserver-proto.h" 7 | 8 | #define DEBUGGER_PROCESS_EXIT 0 9 | #define DEBUGGER_FUZZMETHOD_REACHED 1 10 | #define DEBUGGER_FUZZMETHOD_END 2 11 | #define DEBUGGER_CRASHED 3 12 | #define DEBUGGER_HANGED 4 13 | #define DEBUGGER_ERROR 5 // some weird unknown error 14 | 15 | #define COVERAGE_BB 0 16 | 17 | #define BREAKPOINT_UNKNOWN 0 18 | #define BREAKPOINT_ENTRYPOINT 1 19 | #define BREAKPOINT_MODULELOADED 2 20 | #define BREAKPOINT_FUZZMETHOD 3 21 | #define BREAKPOINT_BB 4 22 | 23 | #ifdef _WIN64 24 | #define INSTRUCTION_POINTER Rip 25 | #else 26 | #define INSTRUCTION_POINTER Eip 27 | #endif 28 | 29 | typedef struct _forkserver_option_t { 30 | bool debug_mode; 31 | int coverage_kind; 32 | char fuzz_harness[MAX_PATH+1]; 33 | char minidump_path[MAX_PATH+1]; 34 | void *fuzz_address; 35 | bool enable_wer; // enable Windows Error Reporting 36 | } forkserver_option_t; 37 | 38 | extern forkserver_option_t options; 39 | 40 | void forkserver_options_init(int argc, const char *argv[]); 41 | void load_bbs(char *bbfile); 42 | CLIENT_ID spawn_child_with_injection(char* cmd, INJECTION_MODE injection_type, uint32_t timeout, uint32_t init_timeout); 43 | void resume_child(); 44 | int get_child_result(); 45 | void kill_process(); 46 | 47 | void get_coverage_info(u32 *visited_bbs_out, u32 *total_bbs_out); 48 | 49 | typedef struct _CHILD_IDS 50 | { 51 | DWORD ProcessId; 52 | DWORD ThreadId; 53 | } CHILD_IDS; 54 | 55 | // --- Fork mode --- 56 | DWORD spawn_forkserver(char** argv, uint32_t timeout, uint32_t init_timeout); 57 | CHILD_IDS fork_new_child(); 58 | int fork_run_child(); 59 | 60 | // --- Persistent mode --- 61 | void reset_persistent(); 62 | void start_persistent(char** argv, uint32_t timeout, uint32_t init_timeout); 63 | int run_with_persistent(); 64 | 65 | struct winafl_breakpoint { 66 | int type; 67 | struct _module_info_t* module; 68 | int file_offset; 69 | uintptr_t rva; 70 | unsigned char original_opcode; 71 | BOOL visited; 72 | int id; 73 | struct winafl_breakpoint *next; 74 | }; 75 | struct winafl_breakpoint *breakpoints; 76 | 77 | // HERE'S HOW YOU USE THE FORKSERVER API. 78 | // A. DRY-RUN MODE 79 | // 1. spawn_child_with_injection() 80 | // Spawns a child process with the harness injected in a SUSPENDED state. 81 | // The harness has not run yet but it IS injected and the target hooks are in place. 82 | // 2. resume_child() 83 | // Now you need to RESUME the child process so the program will run and it will get 84 | // to the harness hook. 85 | // 3. get_child_result() 86 | // Now you need to consume all of the results from the pipe from the child, such as 87 | // the coverage events and whatever. 88 | // 4. kill_process() 89 | // The process will wait for YOU to kill it, will not kill itself! This method 90 | // also will close all the handles and whatever. 91 | // 92 | // B. FORK MODE 93 | // 1. spawn_forkserver() 94 | // Spawn a forkserver first if there isn't one yet. You only need to do this ONCE. 95 | // This will do spawn_child_with_injection(), resume_child() for you 96 | // 2. fork_new_child() 97 | // Forks a new child ready to execute the target function in a SUSPENDED state. 98 | // 3. fork_run_child() 99 | // RESUMES the awaiting child and runs the target function. This will give you a PID 100 | // of the child that you need to use later to kill it once it finishes. 101 | // 4. get_child_result() 102 | // You need to consume the fuzzing events from the pipe, or else it will have junk 103 | // that will cause an error next iteration. 104 | // 5. TerminateProcess() 105 | // You need to MANUALLY kill the child. It will wait for YOU to clean it up. 106 | // 107 | // C. PERSISTENT MODE 108 | // 1. start_persistent() 109 | // Spin up the persistent-mode daemon. This is similar to spawn_forkserver(). 110 | // You only need to do this ONCE. It will SUSPEND when it gets to the target function. 111 | // 2. run_with_persistent() 112 | // RESUMES the daemon and iterates the target function once. It will SELF-SUSPEND at the end 113 | // unless it crashes or hangs. This will also take care of the pipe stuff for you so 114 | // don't bother with get_child_result(). Just run this over and over again 115 | 116 | -------------------------------------------------------------------------------- /afl-fuzz/fullspeed.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | int fullspeed_init(int argc, char **argv); 4 | int run_target_fullspeed(char **argv, uint32_t timeout, uint32_t init_timeout, int drun); 5 | void destroy_target_process(); 6 | void setup_watchdog_timer(); 7 | 8 | // from forkserver.c 9 | void get_coverage_info(u32 *visited_bbs_out, u32 *total_bbs_out); 10 | -------------------------------------------------------------------------------- /afl-fuzz/hash.h: -------------------------------------------------------------------------------- 1 | /* 2 | american fuzzy lop - hashing function 3 | ------------------------------------- 4 | 5 | Original AFL code written by Michal Zalewski 6 | 7 | Windows fork written and maintained by Ivan Fratric 8 | 9 | Copyright 2016 Google Inc. All Rights Reserved. 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | 23 | */ 24 | 25 | /* 26 | The hash32() function is a variant of MurmurHash3, a good 27 | non-cryptosafe hashing function developed by Austin Appleby. 28 | 29 | For simplicity, this variant does *NOT* accept buffer lengths 30 | that are not divisible by 8 bytes. The 32-bit version is otherwise 31 | similar to the original; the 64-bit one is a custom hack with 32 | mostly-unproven properties. 33 | 34 | Austin's original code is public domain. 35 | 36 | */ 37 | 38 | #ifndef _HAVE_HASH_H 39 | #define _HAVE_HASH_H 40 | 41 | #include "types.h" 42 | 43 | #ifdef _WIN64 44 | 45 | #define ROL64(_x, _r) ((((u64)(_x)) << (_r)) | (((u64)(_x)) >> (64 - (_r)))) 46 | 47 | static inline u32 hash32(const void* key, u32 len, u32 seed) { 48 | 49 | const u64* data = (u64*)key; 50 | u64 h1 = seed ^ len; 51 | 52 | len >>= 3; 53 | 54 | while (len--) { 55 | 56 | u64 k1 = *data++; 57 | 58 | k1 *= 0x87c37b91114253d5ULL; 59 | k1 = ROL64(k1, 31); 60 | k1 *= 0x4cf5ad432745937fULL; 61 | 62 | h1 ^= k1; 63 | h1 = ROL64(h1, 27); 64 | h1 = h1 * 5 + 0x52dce729; 65 | 66 | } 67 | 68 | h1 ^= h1 >> 33; 69 | h1 *= 0xff51afd7ed558ccdULL; 70 | h1 ^= h1 >> 33; 71 | h1 *= 0xc4ceb9fe1a85ec53ULL; 72 | h1 ^= h1 >> 33; 73 | 74 | //printf("hash:%lu\n", h1); 75 | return h1; 76 | 77 | } 78 | 79 | #else 80 | 81 | #define ROL32(_x, _r) ((((u32)(_x)) << (_r)) | (((u32)(_x)) >> (32 - (_r)))) 82 | 83 | static inline u32 hash32(const void* key, u32 len, u32 seed) { 84 | 85 | const u32* data = (u32*)key; 86 | u32 h1 = seed ^ len; 87 | 88 | len >>= 2; 89 | 90 | while (len--) { 91 | 92 | u32 k1 = *data++; 93 | 94 | k1 *= 0xcc9e2d51; 95 | k1 = ROL32(k1, 15); 96 | k1 *= 0x1b873593; 97 | 98 | h1 ^= k1; 99 | h1 = ROL32(h1, 13); 100 | h1 = h1 * 5 + 0xe6546b64; 101 | 102 | } 103 | 104 | h1 ^= h1 >> 16; 105 | h1 *= 0x85ebca6b; 106 | h1 ^= h1 >> 13; 107 | h1 *= 0xc2b2ae35; 108 | h1 ^= h1 >> 16; 109 | 110 | //printf("hash:%ud\n", h1); 111 | return h1; 112 | 113 | } 114 | 115 | #endif /* ^_WIN64 */ 116 | 117 | #endif /* !_HAVE_HASH_H */ 118 | -------------------------------------------------------------------------------- /afl-fuzz/process.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | DWORD get_all_modules(HANDLE child_handle, HMODULE **modules); 12 | 13 | HMODULE FindModule(HANDLE hProcess, const char* szModuleName); 14 | 15 | HMODULE InjectDll(HANDLE hProcess, LPCSTR szDllFilename); 16 | 17 | void *get_entrypoint(HANDLE child_handle, void *base_address); 18 | 19 | DWORD get_proc_offset(char *data, char *name); 20 | 21 | PIMAGE_NT_HEADERS map_pe_file(LPCSTR szPath, LPVOID* lpBase, HANDLE* hMapping, HANDLE* hFile); 22 | 23 | DWORD get_entry_point(LPCSTR szPath); 24 | 25 | DWORD GetModuleBaseAddress(DWORD pid, char* DLLName); 26 | 27 | HMODULE find_module(HANDLE hProcess, const char* szModuleName); 28 | -------------------------------------------------------------------------------- /afl-fuzz/ptdecode.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /* 4 | WinAFL - Intel PT decoding 5 | ------------------------------------------------ 6 | 7 | Written and maintained by Ivan Fratric 8 | 9 | Copyright 2016 Google Inc. All Rights Reserved. 10 | Licensed under the Apache License, Version 2.0 (the "License"); 11 | you may not use this file except in compliance with the License. 12 | You may obtain a copy of the License at 13 | 14 | http://www.apache.org/licenses/LICENSE-2.0 15 | 16 | Unless required by applicable law or agreed to in writing, software 17 | distributed under the License is distributed on an "AS IS" BASIS, 18 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | See the License for the specific language governing permissions and 20 | limitations under the License. 21 | */ 22 | 23 | #include 24 | #include // EXTERN_C 25 | 26 | typedef void(*trace_callback)(uint64_t ip); 27 | 28 | EXTERN_C void analyze_trace_full_reference(unsigned char *trace_data, size_t trace_size, struct pt_image *image, bool skip_first_bb, trace_callback func); 29 | EXTERN_C void decode_trace_tip_fast(unsigned char *data, size_t size, int coverage_kind, trace_callback func); 30 | EXTERN_C void decode_trace_tip_reference(unsigned char *trace_data, size_t trace_size, int coverage_kind, trace_callback func); 31 | EXTERN_C int check_trace_start(unsigned char *data, size_t size, uint64_t expected_ip); 32 | -------------------------------------------------------------------------------- /afl-fuzz/types.h: -------------------------------------------------------------------------------- 1 | /* 2 | american fuzzy lop - type definitions and minor macros 3 | ------------------------------------------------------ 4 | 5 | Original AFL code written by Michal Zalewski 6 | 7 | Windows fork written and maintained by Ivan Fratric 8 | 9 | Copyright 2016 Google Inc. All Rights Reserved. 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | 23 | */ 24 | 25 | #ifndef _HAVE_TYPES_H 26 | #define _HAVE_TYPES_H 27 | 28 | #include 29 | #include 30 | 31 | typedef uint8_t u8; 32 | typedef uint16_t u16; 33 | typedef uint32_t u32; 34 | 35 | /* 36 | 37 | Ugh. There is an unintended compiler / glibc #include glitch caused by 38 | combining the u64 type an %llu in format strings, necessitating a workaround. 39 | 40 | In essence, the compiler is always looking for 'unsigned long long' for %llu. 41 | On 32-bit systems, the u64 type (aliased to uint64_t) is expanded to 42 | 'unsigned long long' in , so everything checks out. 43 | 44 | But on 64-bit systems, it is #ifdef'ed in the same file as 'unsigned long'. 45 | Now, it only happens in circumstances where the type happens to have the 46 | expected bit width, *but* the compiler does not know that... and complains 47 | about 'unsigned long' being unsafe to pass to %llu. 48 | 49 | */ 50 | 51 | #ifdef _WIN64 52 | typedef unsigned long long u64; 53 | #else 54 | typedef uint64_t u64; 55 | #endif /* ^sizeof(...) */ 56 | 57 | typedef int8_t s8; 58 | typedef int16_t s16; 59 | typedef int32_t s32; 60 | typedef int64_t s64; 61 | 62 | #ifndef MIN 63 | # define MIN(_a,_b) ((_a) > (_b) ? (_b) : (_a)) 64 | # define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b)) 65 | #endif /* !MIN */ 66 | 67 | #define SWAP16(x) (((x) >> 8) | ((x) << 8)) 68 | #define SWAP32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) 69 | 70 | #define R(x) (rand() % (x)) 71 | 72 | #define STRINGIFY_INTERNAL(x) #x 73 | #define STRINGIFY(x) STRINGIFY_INTERNAL(x) 74 | 75 | #define MEM_BARRIER() \ 76 | asm volatile("" ::: "memory") 77 | 78 | #endif /* ! _HAVE_TYPES_H */ 79 | -------------------------------------------------------------------------------- /afl-fuzz/utils.h: -------------------------------------------------------------------------------- 1 | /* *************************************************************************** 2 | * Copyright (c) 2012-2013 Google, Inc. All rights reserved. 3 | * ***************************************************************************/ 4 | 5 | /* 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * 12 | * * Redistributions in binary form must reproduce the above copyright notice, 13 | * this list of conditions and the following disclaimer in the documentation 14 | * and/or other materials provided with the distribution. 15 | * 16 | * * Neither the name of Google, Inc. nor the names of its contributors may be 17 | * used to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE, INC. OR CONTRIBUTORS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 30 | * DAMAGE. 31 | */ 32 | 33 | /* 34 | DynamoRIO utility macros. Copied from the DyanmoRIO project, 35 | http://dynamorio.org/ 36 | */ 37 | 38 | 39 | #ifndef CLIENTS_COMMON_UTILS_H_ 40 | #define CLIENTS_COMMON_UTILS_H_ 41 | 42 | //#include "dr_api.h" 43 | 44 | #ifdef DEBUG 45 | # define ASSERT(x, msg) DR_ASSERT_MSG(x, msg) 46 | # define IF_DEBUG(x) x 47 | #else 48 | # define ASSERT(x, msg) /* nothing */ 49 | # define IF_DEBUG(x) /* nothing */ 50 | #endif 51 | 52 | /* XXX: should be moved to DR API headers? */ 53 | #define BUFFER_SIZE_BYTES(buf) sizeof(buf) 54 | #define BUFFER_SIZE_ELEMENTS(buf) (BUFFER_SIZE_BYTES(buf) / sizeof((buf)[0])) 55 | #define BUFFER_LAST_ELEMENT(buf) (buf)[BUFFER_SIZE_ELEMENTS(buf) - 1] 56 | #define NULL_TERMINATE_BUFFER(buf) BUFFER_LAST_ELEMENT(buf) = 0 57 | #define ALIGNED(x, alignment) ((((ptr_uint_t)x) & ((alignment)-1)) == 0) 58 | #define TESTANY(mask, var) (((mask) & (var)) != 0) 59 | #define TEST TESTANY 60 | 61 | #ifdef WINDOWS 62 | # define IF_WINDOWS(x) x 63 | # define IF_UNIX_ELSE(x,y) y 64 | #else 65 | # define IF_WINDOWS(x) 66 | # define IF_UNIX_ELSE(x,y) x 67 | #endif 68 | 69 | /* Checks for both debug and release builds: */ 70 | #define USAGE_CHECK(x, msg) DR_ASSERT_MSG(x, msg) 71 | 72 | /* 73 | static inline generic_func_t 74 | cast_to_func(void *p) 75 | { 76 | #ifdef WINDOWS 77 | # pragma warning(push) 78 | # pragma warning(disable : 4055) 79 | #endif 80 | return (generic_func_t) p; 81 | #ifdef WINDOWS 82 | # pragma warning(pop) 83 | #endif 84 | } 85 | */ 86 | 87 | #endif /* CLIENTS_COMMON_UTILS_H_ */ 88 | -------------------------------------------------------------------------------- /afl-fuzz/winaflpt.h: -------------------------------------------------------------------------------- 1 | /* 2 | WinAFL - Intel PT instrumentation and presistence via debugger code 3 | ------------------------------------------------ 4 | 5 | Written and maintained by Ivan Fratric 6 | 7 | Copyright 2016 Google Inc. All Rights Reserved. 8 | Licensed under the Apache License, Version 2.0 (the "License"); 9 | you may not use this file except in compliance with the License. 10 | You may obtain a copy of the License at 11 | 12 | http://www.apache.org/licenses/LICENSE-2.0 13 | 14 | Unless required by applicable law or agreed to in writing, software 15 | distributed under the License is distributed on an "AS IS" BASIS, 16 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | See the License for the specific language governing permissions and 18 | limitations under the License. 19 | */ 20 | 21 | #define COVERAGE_BB 0 22 | #define COVERAGE_EDGE 1 23 | 24 | #define TRACE_BUFFER_SIZE_DEFAULT (128*1024) //should be a power of 2 25 | 26 | #define TRACE_CACHE_SIZE_MIN 10000000 27 | #define TRACE_CACHE_SIZE_MAX 100000000 28 | 29 | bool findpsb(unsigned char **data, size_t *size); 30 | 31 | EXTERN_C int run_target_pt(char **argv, uint32_t timeout, uint32_t init_timeout, int drun); 32 | EXTERN_C int pt_init(int argc, const char **argv, char *module_dir); 33 | EXTERN_C void destroy_target_process_pt(); 34 | -------------------------------------------------------------------------------- /docs/IdaInstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/IdaInstall.png -------------------------------------------------------------------------------- /docs/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/architecture.png -------------------------------------------------------------------------------- /docs/dir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/dir.png -------------------------------------------------------------------------------- /docs/forkserverError.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/forkserverError.png -------------------------------------------------------------------------------- /docs/installPythonToPath.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/installPythonToPath.png -------------------------------------------------------------------------------- /docs/rabbit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/rabbit.png -------------------------------------------------------------------------------- /docs/scriptFile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/scriptFile.png -------------------------------------------------------------------------------- /docs/soultionExplorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/soultionExplorer.png -------------------------------------------------------------------------------- /docs/startupItem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/startupItem.png -------------------------------------------------------------------------------- /docs/toyExample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/toyExample.png -------------------------------------------------------------------------------- /docs/vmSetup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/vmSetup.png -------------------------------------------------------------------------------- /docs/winnieSuccess.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/winnieSuccess.png -------------------------------------------------------------------------------- /docs/winnieWorking.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/docs/winnieWorking.png -------------------------------------------------------------------------------- /experiments/CreateUserProcess_benchmark/CreateUserProcess_benchmark.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | 23 | 24 | Source Files 25 | 26 | 27 | Source Files 28 | 29 | 30 | -------------------------------------------------------------------------------- /experiments/CreateUserProcess_benchmark/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed 2 | 3 | #include "pch.h" 4 | 5 | // In general, ignore this file, but keep it around if you are using pre-compiled headers. 6 | -------------------------------------------------------------------------------- /experiments/CreateUserProcess_benchmark/pch.h: -------------------------------------------------------------------------------- 1 | // Tips for Getting Started: 2 | // 1. Use the Solution Explorer window to add/manage files 3 | // 2. Use the Team Explorer window to connect to source control 4 | // 3. Use the Output window to see build output and other messages 5 | // 4. Use the Error List window to view errors 6 | // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project 7 | // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file 8 | 9 | #ifndef PCH_H 10 | #define PCH_H 11 | 12 | // TODO: add headers that you want to pre-compile here 13 | 14 | #endif //PCH_H 15 | -------------------------------------------------------------------------------- /experiments/README.md: -------------------------------------------------------------------------------- 1 | # experiments 2 | 3 | This directory contains miscellaneous standalone projects used to test individual components of the fuzzer. 4 | 5 | - **CreateUserProcess_benchmark** -- forklib benchmark 6 | - **debugger** -- runtime tracer using debug API 7 | - **dump_parser** -- minidump parser 8 | - **hook-example** -- driver for the injected forkserver that tests hooking, forkserver, coverage, etc. without full fuzzer functionality 9 | - **test_fork_with_pt** -- forklib + parent-traces-child with Intel PT 10 | 11 | The easiest way to build these examples is just to move them to the top-level directory and add them to the solution. 12 | -------------------------------------------------------------------------------- /experiments/debugger/debugger.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | 23 | 24 | Source Files 25 | 26 | 27 | Source Files 28 | 29 | 30 | -------------------------------------------------------------------------------- /experiments/debugger/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed 2 | 3 | #include "pch.h" 4 | 5 | // In general, ignore this file, but keep it around if you are using pre-compiled headers. 6 | -------------------------------------------------------------------------------- /experiments/debugger/pch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | -------------------------------------------------------------------------------- /experiments/dump_parser/README.md: -------------------------------------------------------------------------------- 1 | # minidump parser 2 | 3 | Listens for new crashdumps (minidump files) in C:\sslab\minidumps and parses them for exception info. 4 | 5 | You need to apply the [registry keys](../../docs/minidump_config.reg); refer to the full README for more info. 6 | -------------------------------------------------------------------------------- /experiments/dump_parser/dump_parser.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | 23 | 24 | Source Files 25 | 26 | 27 | Source Files 28 | 29 | 30 | -------------------------------------------------------------------------------- /experiments/dump_parser/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed 2 | 3 | #include "pch.h" 4 | 5 | // In general, ignore this file, but keep it around if you are using pre-compiled headers. 6 | -------------------------------------------------------------------------------- /experiments/dump_parser/pch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | -------------------------------------------------------------------------------- /experiments/hook-example/hook-example.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | 23 | 24 | Source Files 25 | 26 | 27 | Source Files 28 | 29 | 30 | -------------------------------------------------------------------------------- /experiments/hook-example/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed 2 | 3 | #include "pch.h" 4 | 5 | // In general, ignore this file, but keep it around if you are using pre-compiled headers. 6 | -------------------------------------------------------------------------------- /experiments/hook-example/pch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #define _CRT_SECURE_NO_WARNINGS 3 | #include 4 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/.gitignore: -------------------------------------------------------------------------------- 1 | ptmodules/ 2 | trace.bin 3 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/README.md: -------------------------------------------------------------------------------- 1 | # Forklib with Intel PT 2 | 3 | Intel PT works with forklib and parent can trace child 4 | 5 | ### Experimental data 6 | 7 | Check `bin` directory. The trace contains a repetitive pattern of `00007FF68A211EC0`, which corresponds to the spinloop nop basic block. 8 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/debug.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define FATAL(f, ...) {printf(f ": GLE=%d\n", ##__VA_ARGS__##, GetLastError()); getc(stdin); ExitProcess(0); } 4 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: source file corresponding to pre-compiled header; necessary for compilation to succeed 2 | 3 | #include "pch.h" 4 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/pch.h: -------------------------------------------------------------------------------- 1 | #ifndef PCH_H 2 | #define PCH_H 3 | 4 | #define _CRT_SECURE_NO_WARNINGS 5 | #include 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/ptdecode.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /* 4 | WinAFL - Intel PT decoding 5 | ------------------------------------------------ 6 | 7 | Written and maintained by Ivan Fratric 8 | 9 | Copyright 2016 Google Inc. All Rights Reserved. 10 | Licensed under the Apache License, Version 2.0 (the "License"); 11 | you may not use this file except in compliance with the License. 12 | You may obtain a copy of the License at 13 | 14 | http://www.apache.org/licenses/LICENSE-2.0 15 | 16 | Unless required by applicable law or agreed to in writing, software 17 | distributed under the License is distributed on an "AS IS" BASIS, 18 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | See the License for the specific language governing permissions and 20 | limitations under the License. 21 | */ 22 | 23 | #include 24 | #include // EXTERN_C 25 | 26 | typedef void(*trace_callback)(int pt_status, pt_block* pt_block); 27 | 28 | EXTERN_C void analyze_trace_full_reference(unsigned char *trace_data, size_t trace_size, struct pt_image *image, bool skip_first_bb, trace_callback func); 29 | -------------------------------------------------------------------------------- /experiments/test_fork_with_pt/test_fork_with_pt.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | 29 | 30 | Source Files 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | Source Files 40 | 41 | 42 | -------------------------------------------------------------------------------- /forklib/.gitignore: -------------------------------------------------------------------------------- 1 | csrss_offsets.h 2 | 3 | -------------------------------------------------------------------------------- /forklib/csrss.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | #include "csrss.h" 3 | 4 | static HMODULE ntdll = GetModuleHandleA("ntdll.dll"); 5 | CsrClientConnectToServer_t CsrClientConnectToServer = (CsrClientConnectToServer_t)GetProcAddress(ntdll, "CsrClientConnectToServer"); 6 | CsrClientCallServer_t CsrClientCallServer = (CsrClientCallServer_t)GetProcAddress(ntdll, "CsrClientCallServer"); 7 | CsrClientCallServer64_t CsrClientCallServer64 = (CsrClientCallServer64_t)CsrClientCallServer; 8 | -------------------------------------------------------------------------------- /forklib/csrss.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // https://codereview.chromium.org/1456343002/patch/20001/30001 4 | // https://github.com/begoon/stuff/blob/master/windows/ntfork/main.cpp 5 | // https://doxygen.reactos.org/d6/d18/basemsg_8h_source.html 6 | // Size should be 0x108. 7 | // From kernelbase.dll!CreateProcessInternalW: CsrClientCallServer(&v345, v232, 0x10000i64, 0x108i64); 8 | typedef struct _BASE_CREATE_PROCESS { 9 | HANDLE ProcessHandle; 10 | HANDLE ThreadHandle; 11 | CLIENT_ID ClientId; 12 | ULONG CreationFlags; 13 | ULONG VdmBinaryType; 14 | ULONG VdmTask; 15 | HANDLE hVDM; 16 | PVOID something_sxs[23]; // Notice how this is one less on windows 10. Undocumented magic lol (24 on Win7) 17 | PVOID PebAddressNative; 18 | PVOID unk0; 19 | USHORT ProcessorArchitecture; 20 | } BASE_CREATE_PROCESS, *PBASE_CREATE_PROCESS; 21 | 22 | // No longer used in Win10, judging from basesrv.dll, the dispatch table entry now points to BaseSrvDeadEntry. 23 | typedef struct _BASE_CREATE_THREAD 24 | { 25 | HANDLE ThreadHandle; 26 | CLIENT_ID ClientId; 27 | } BASE_CREATE_THREAD, *PBASE_CREATE_THREAD; 28 | 29 | // WoW64 -- need to explicitly specify all pointer types as 64-bit, not 32-bit since csrss uses the x64 structs. 30 | typedef struct { 31 | ULONGLONG ProcessHandle; 32 | ULONGLONG ThreadHandle; 33 | CLIENT_ID64 ClientId; 34 | ULONG CreationFlags; 35 | ULONG VdmBinaryType; 36 | ULONG VdmTask; 37 | ULONGLONG hVDM; 38 | ULONGLONG something_sxs[23]; // Notice how this is one less on windows 10. Undocumented magic lol (24 on Win7) 39 | ULONGLONG PebAddressNative; 40 | ULONGLONG unk0; 41 | USHORT ProcessorArchitecture; 42 | } BASE_CREATE_PROCESS64, *PBASE_CREATE_PROCESS64; 43 | 44 | typedef struct _BASE_CREATE_THREAD64 45 | { 46 | ULONGLONG ThreadHandle; 47 | CLIENT_ID64 ClientId; 48 | } BASE_CREATE_THREAD64, *PBASE_CREATE_THREAD64; 49 | 50 | // This is documented here: 51 | // http://www.geoffchappell.com/studies/windows/win32/csrsrv/api/apireqst/api_msg.htm 52 | struct CSR_CAPTURE_HEADER; 53 | 54 | typedef struct 55 | { 56 | PORT_MESSAGE h; 57 | CSR_CAPTURE_HEADER *CaptureBuffer; 58 | ULONG ApiNumber; 59 | ULONG ReturnValue; 60 | ULONG Reserved; 61 | 62 | union 63 | { 64 | BASE_CREATE_PROCESS CreateProcessRequest; 65 | BASE_CREATE_THREAD CreateThreadRequest; 66 | ULONG_PTR ApiMessageData[0x2E]; 67 | }; 68 | } CSR_API_MSG, *PCSR_API_MESSAGE; 69 | 70 | // WoW64 version with 64-bit pointer types 71 | typedef struct 72 | { 73 | PORT_MESSAGE64 h; 74 | ULONGLONG CaptureBuffer; 75 | ULONG ApiNumber; 76 | ULONG ReturnValue; 77 | ULONG Reserved; 78 | union 79 | { 80 | BASE_CREATE_PROCESS64 CreateProcessRequest; 81 | BASE_CREATE_THREAD64 CreateThreadRequest; 82 | ULONG_PTR ApiMessageData[0x2E]; 83 | }; 84 | } CSR_API_MSG64, *PCSR_API_MESSAGE64; 85 | 86 | 87 | // https://github.com/mic101/windows/blob/master/WRK-v1.2/public/sdk/inc/ntcsrmsg.h 88 | typedef ULONG CSR_API_NUMBER; 89 | 90 | #define CSR_MAKE_API_NUMBER( DllIndex, ApiIndex ) \ 91 | (CSR_API_NUMBER)(((DllIndex) << 16) | (ApiIndex)) 92 | 93 | #define CSRSRV_SERVERDLL_INDEX 0 94 | #define CSRSRV_FIRST_API_NUMBER 0 95 | 96 | #define BASESRV_SERVERDLL_INDEX 1 97 | #define BASESRV_FIRST_API_NUMBER 0 98 | 99 | #define CONSRV_SERVERDLL_INDEX 2 100 | #define CONSRV_FIRST_API_NUMBER 512 101 | 102 | #define USERSRV_SERVERDLL_INDEX 3 103 | #define USERSRV_FIRST_API_NUMBER 1024 104 | 105 | // Windows Server 2003 table from http://j00ru.vexillium.org/csrss_list/api_list.html#Windows_2k3 106 | // See basesrv.dll!BaseServerApiDispatchTable 107 | typedef enum _BASESRV_API_NUMBER 108 | { 109 | BasepCreateProcess = BASESRV_FIRST_API_NUMBER, 110 | BasepCreateThread, // No longer used in Win10 111 | // Rest don't matter lol 112 | } BASESRV_API_NUMBER, *PBASESRV_API_NUMBER;; 113 | 114 | // High and low words of ApiNumber determine which API routine to call 115 | // NTSTATUS __stdcall CsrClientCallServer(PCSR_API_MESSAGE ApiMessage, PCSR_CAPTURE_BUFFER CaptureBuffer, CSR_API_NUMBER ApiNumber, ULONG DataLength) 116 | typedef NTSTATUS(WINAPI *CsrClientCallServer_t)(PCSR_API_MESSAGE ApiMsg, PVOID CaptureBuffer, ULONG ApiNumber, ULONG ApiMessageDataSize); 117 | typedef NTSTATUS(WINAPI *CsrClientCallServer64_t)(PCSR_API_MESSAGE64 ApiMsg, PVOID CaptureBuffer, ULONG ApiNumber, ULONG ApiMessageDataSize); 118 | 119 | typedef NTSTATUS(NTAPI *CsrClientConnectToServer_t)( 120 | IN PWSTR ObjectDirectory, 121 | IN ULONG ServerId, 122 | IN PVOID ConnectionInfo, 123 | IN ULONG ConnectionInfoSize, 124 | OUT PBOOLEAN ServerToServerCall 125 | ); 126 | 127 | extern CsrClientConnectToServer_t CsrClientConnectToServer; 128 | extern CsrClientCallServer_t CsrClientCallServer; 129 | extern CsrClientCallServer64_t CsrClientCallServer64; 130 | 131 | #include "csrss_offsets.h" 132 | -------------------------------------------------------------------------------- /forklib/dllmain.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | BOOL APIENTRY DllMain( HMODULE hModule, 4 | DWORD ul_reason_for_call, 5 | LPVOID lpReserved 6 | ) 7 | { 8 | switch (ul_reason_for_call) 9 | { 10 | case DLL_PROCESS_ATTACH: 11 | case DLL_THREAD_ATTACH: 12 | case DLL_THREAD_DETACH: 13 | case DLL_PROCESS_DETACH: 14 | break; 15 | } 16 | return TRUE; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /forklib/fork.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | extern "C" 4 | { 5 | __declspec(dllexport) DWORD fork(_Out_ LPPROCESS_INFORMATION lpProcessInformation); 6 | 7 | __declspec(dllexport) BOOL EnumerateProcessHandles(void(*callback)(HANDLE, POBJECT_TYPE_INFORMATION, PUNICODE_STRING)); 8 | 9 | __declspec(dllexport) BOOL MarkAllHandles(); 10 | 11 | __declspec(dllexport) BOOL SuspendOtherThreads(); 12 | } 13 | -------------------------------------------------------------------------------- /forklib/forklib.cpp: -------------------------------------------------------------------------------- 1 | // forklib.cpp : Defines the exported functions for the DLL application. 2 | // 3 | 4 | #include "stdafx.h" 5 | 6 | 7 | -------------------------------------------------------------------------------- /forklib/forklib.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | Header Files 32 | 33 | 34 | Header Files 35 | 36 | 37 | 38 | 39 | Source Files 40 | 41 | 42 | Source Files 43 | 44 | 45 | Source Files 46 | 47 | 48 | Source Files 49 | 50 | 51 | Source Files 52 | 53 | 54 | Source Files 55 | 56 | 57 | -------------------------------------------------------------------------------- /forklib/include/forklib.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | typedef struct _OBJECT_TYPE_INFORMATION 7 | { 8 | UNICODE_STRING TypeName; 9 | ULONG TotalNumberOfObjects; 10 | ULONG TotalNumberOfHandles; 11 | ULONG TotalPagedPoolUsage; 12 | ULONG TotalNonPagedPoolUsage; 13 | ULONG TotalNamePoolUsage; 14 | ULONG TotalHandleTableUsage; 15 | ULONG HighWaterNumberOfObjects; 16 | ULONG HighWaterNumberOfHandles; 17 | ULONG HighWaterPagedPoolUsage; 18 | ULONG HighWaterNonPagedPoolUsage; 19 | ULONG HighWaterNamePoolUsage; 20 | ULONG HighWaterHandleTableUsage; 21 | ULONG InvalidAttributes; 22 | GENERIC_MAPPING GenericMapping; 23 | ULONG ValidAccessMask; 24 | BOOLEAN SecurityRequired; 25 | BOOLEAN MaintainHandleCount; 26 | UCHAR TypeIndex; // since WINBLUE 27 | CHAR ReservedByte; 28 | ULONG PoolType; 29 | ULONG DefaultPagedPoolCharge; 30 | ULONG DefaultNonPagedPoolCharge; 31 | } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | __declspec(dllimport) DWORD fork(_Out_ LPPROCESS_INFORMATION lpProcessInformation); 37 | __declspec(dllimport) BOOL EnumerateProcessHandles(void(*)(HANDLE, POBJECT_TYPE_INFORMATION, PUNICODE_STRING)); 38 | __declspec(dllimport) BOOL MarkAllHandles(); 39 | __declspec(dllimport) BOOL SuspendOtherThreads(); 40 | #ifdef __cplusplus 41 | } 42 | #endif 43 | 44 | -------------------------------------------------------------------------------- /forklib/pdbparse/dbgold.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from construct import * 4 | 5 | from pdbparse.info import GUID 6 | from pdbparse.pe import IMAGE_SECTION_HEADER 7 | 8 | CV_RSDS_HEADER = "CV_RSDS" / Struct( 9 | "Signature" / Const(b"RSDS", Bytes(4)), 10 | GUID("GUID"), 11 | "Age" / Int32ul, 12 | "Filename" / CString(encoding = "utf8"), 13 | ) 14 | 15 | CV_NB10_HEADER = "CV_NB10" / Struct( 16 | "Signature" / Const(b"NB10", Bytes(4)), 17 | "Offset" / Int32ul, 18 | "Timestamp" / Int32ul, 19 | "Age" / Int32ul, 20 | "Filename" / CString(encoding = "utf8"), 21 | ) 22 | 23 | DebugDirectoryType = "Type" / Enum( 24 | Int32ul, 25 | IMAGE_DEBUG_TYPE_UNKNOWN = 0, 26 | IMAGE_DEBUG_TYPE_COFF = 1, 27 | IMAGE_DEBUG_TYPE_CODEVIEW = 2, 28 | IMAGE_DEBUG_TYPE_FPO = 3, 29 | IMAGE_DEBUG_TYPE_MISC = 4, 30 | IMAGE_DEBUG_TYPE_EXCEPTION = 5, 31 | IMAGE_DEBUG_TYPE_FIXUP = 6, 32 | IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7, 33 | IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8, 34 | IMAGE_DEBUG_TYPE_BORLAND = 9, 35 | IMAGE_DEBUG_TYPE_RESERVED = 10, 36 | _default_ = "IMAGE_DEBUG_TYPE_UNKNOWN", 37 | ) 38 | 39 | DebugMiscType = "Type" / Enum( 40 | Int32ul, 41 | IMAGE_DEBUG_MISC_EXENAME = 1, 42 | _default_ = Pass, 43 | ) 44 | 45 | IMAGE_SEPARATE_DEBUG_HEADER = "IMAGE_SEPARATE_DEBUG_HEADER" / Struct( 46 | "Signature" / Const(b"DI", Bytes(2)), 47 | "Flags" / Int16ul, 48 | "Machine" / Int16ul, 49 | "Characteristics" / Int16ul, 50 | "TimeDateStamp" / Int16ul, 51 | "CheckSum" / Int16ul, 52 | "ImageBase" / Int16ul, 53 | "SizeOfImage" / Int16ul, 54 | "NumberOfSections" / Int16ul, 55 | "ExportedNamesSize" / Int16ul, 56 | "DebugDirectorySize" / Int16ul, 57 | "SectionAlignment" / Int16ul, 58 | Array(2, "Reserved" / Int32ul), 59 | ) 60 | 61 | IMAGE_DEBUG_DIRECTORY = "IMAGE_DEBUG_DIRECTORY" / Struct( 62 | "Characteristics" / Int32ul, 63 | "TimeDateStamp" / Int32ul, 64 | "MajorVersion" / Int16ul, 65 | "MinorVersion" / Int16ul, 66 | DebugDirectoryType, 67 | "SizeOfData" / Int32ul, 68 | "AddressOfRawData" / Int32ul, 69 | "PointerToRawData" / Int32ul, 70 | "Data" / Pointer(lambda ctx: ctx.PointerToRawData, Bytes(lambda ctx: ctx.SizeOfData)), 71 | ) 72 | 73 | IMAGE_DEBUG_MISC = "IMAGE_DEBUG_MISC" / Struct( 74 | DebugMiscType, 75 | "Length" / Int32ul, 76 | "Unicode" / Byte, 77 | Array(3, "Reserved" / Byte), 78 | "Strings" / RestreamData( 79 | Bytes(lambda ctx: ctx.Length - 12), 80 | GreedyRange(CString(encoding = "utf8")), 81 | ), 82 | ) 83 | 84 | IMAGE_FUNCTION_ENTRY = "IMAGE_FUNCTION_ENTRY" / Struct( 85 | "StartingAddress" / Int32ul, 86 | "EndingAddress" / Int32ul, 87 | "EndOfPrologue" / Int32ul, 88 | ) 89 | 90 | DbgFile = "DbgFile" / Struct( 91 | IMAGE_SEPARATE_DEBUG_HEADER, 92 | Array(lambda ctx: ctx.IMAGE_SEPARATE_DEBUG_HEADER.NumberOfSections, IMAGE_SECTION_HEADER), 93 | "ExportedNames" / RestreamData( 94 | Bytes(lambda ctx: ctx.IMAGE_SEPARATE_DEBUG_HEADER.ExportedNamesSize), 95 | GreedyRange(CString(encoding = "utf8")), 96 | ), 97 | Array(lambda ctx: ctx.IMAGE_SEPARATE_DEBUG_HEADER.DebugDirectorySize / IMAGE_DEBUG_DIRECTORY.sizeof(), 98 | IMAGE_DEBUG_DIRECTORY)) 99 | -------------------------------------------------------------------------------- /forklib/pdbparse/fpo.py: -------------------------------------------------------------------------------- 1 | from construct import * 2 | 3 | # FPO DATA 4 | FPO_DATA = "FPO_DATA" / Struct( 5 | "ulOffStart" / Int32ul, # offset 1st byte of function code 6 | "cbProcSize" / Int32ul, # number of bytes in function 7 | "cdwLocals" / Int32ul, # number of bytes in locals/4 8 | "cdwParams" / Int16ul, # number of bytes in params/4 9 | "BitValues" / BitStruct( 10 | "cbProlog" / Octet, # number of bytes in prolog 11 | "cbFrame" / BitsInteger(2), # frame type 12 | "reserved" / Bit, # reserved for future use 13 | "fUseBP" / Flag, # TRUE if EBP has been allocated 14 | "fHasSEH" / Flag, # TRUE if SEH in func 15 | "cbRegs" / BitsInteger(3), # number of regs saved 16 | ), 17 | ) 18 | 19 | # New style FPO records with program strings 20 | FPO_DATA_V2 = "FPO_DATA_V2" / Struct( 21 | "ulOffStart" / Int32ul, 22 | "cbProcSize" / Int32ul, 23 | "cbLocals" / Int32ul, 24 | "cbParams" / Int32ul, 25 | "maxStack" / Int32ul, # so far only observed to be 0 26 | "ProgramStringOffset" / Int32ul, 27 | "cbProlog" / Int16ul, 28 | "cbSavedRegs" / Int16ul, 29 | "flags" / FlagsEnum( 30 | Int32ul, 31 | SEH = 1, 32 | CPPEH = 2, # conjectured 33 | fnStart = 4, 34 | ), 35 | ) 36 | 37 | # Ranges for both types 38 | FPO_DATA_LIST = GreedyRange(FPO_DATA) 39 | FPO_DATA_LIST_V2 = GreedyRange(FPO_DATA_V2) 40 | 41 | # Program string storage 42 | # May move this to a new file; in private symbols the values 43 | # include things that are not just FPO related. 44 | FPO_STRING_DATA = Struct( 45 | "Signature" / Const(b"\xFE\xEF\xFE\xEF", Bytes(4)), 46 | "Unk1" / Int32ul, 47 | "szDataLen" / Int32ul, 48 | "StringData" / Union( 49 | 0, 50 | "Data" / Bytes(lambda ctx: ctx._.szDataLen), 51 | "Strings" / RestreamData( 52 | Bytes(lambda ctx: ctx._.szDataLen), 53 | GreedyRange(CString(encoding = "utf8")), 54 | ), 55 | ), 56 | "lastDwIndex" / Int32ul, # data remaining = (last_dword_index+1)*4 57 | "UnkData" / HexDump(Bytes(lambda ctx: ((ctx.lastDwIndex + 1) * 4))), 58 | Terminated, 59 | ) 60 | 61 | 62 | def parse_FPO_DATA_LIST(data): 63 | fpo = FPO_DATA_LIST.parse(data) 64 | new_entry_list = [] 65 | for entry in fpo: 66 | new_entry = Container( 67 | ulOffStart = entry.ulOffStart, 68 | cbProcSize = entry.cbProcSize, 69 | cdwLocals = entry.cdwLocals, 70 | cdwParams = entry.cdwParams, 71 | cbProlog = entry.BitValues.cbProlog, 72 | cbFrame = entry.BitValues.cbFrame, 73 | reserved = entry.BitValues.reserved, 74 | fUseBP = entry.BitValues.fUseBP, 75 | fHasSEH = entry.BitValues.fHasSEH, 76 | cbRegs = entry.BitValues.cbRegs) 77 | new_entry_list.append(new_entry) 78 | return ListContainer(new_entry_list) 79 | -------------------------------------------------------------------------------- /forklib/pdbparse/gdata.py: -------------------------------------------------------------------------------- 1 | # Python 2 and 3 2 | 3 | from construct import * 4 | 5 | gsym = Struct( 6 | "leaf_type" / Int16ul, "data" / Switch( 7 | lambda ctx: ctx.leaf_type, { 8 | 0x110E: 9 | "data_v3" / Struct( 10 | "symtype" / Int32ul, 11 | "offset" / Int32ul, 12 | "segment" / Int16ul, 13 | "name" / CString(encoding = "utf8"), 14 | ), 15 | 0x1009: 16 | "data_v2" / Struct( 17 | "symtype" / Int32ul, 18 | "offset" / Int32ul, 19 | "segment" / Int16ul, 20 | "name" / PascalString(lengthfield = "length" / Int8ul, encoding = "utf8"), 21 | ), 22 | })) 23 | 24 | GlobalsData = "globals" / GreedyRange( 25 | Struct( 26 | "length" / Int16ul, 27 | "symbol" / RestreamData(Bytes(lambda ctx: ctx.length), gsym), 28 | )) 29 | 30 | 31 | def parse(data): 32 | con = GlobalsData.parse(data) 33 | return merge_structures(con) 34 | 35 | 36 | def parse_stream(stream): 37 | con = GlobalsData.parse_stream(stream) 38 | return merge_structures(con) 39 | 40 | 41 | def merge_structures(con): 42 | new_cons = [] 43 | for sym in con: 44 | sym_dict = {'length': sym.length, 'leaf_type': sym.symbol.leaf_type} 45 | if sym.symbol.data: 46 | sym_dict.update({ 47 | 'symtype': sym.symbol.data.symtype, 48 | 'offset': sym.symbol.data.offset, 49 | 'segment': sym.symbol.data.segment, 50 | 'name': sym.symbol.data.name 51 | }) 52 | new_cons.append(Container(sym_dict)) 53 | result = ListContainer(new_cons) 54 | return result 55 | -------------------------------------------------------------------------------- /forklib/pdbparse/info.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | 3 | from construct import * 4 | 5 | _strarray = "names" / GreedyRange(CString(encoding = "utf8")) 6 | 7 | 8 | class StringArrayAdapter(Adapter): 9 | 10 | def _encode(self, obj, context, path): 11 | return _strarray._build(BytesIO(obj), context, path) 12 | 13 | def _decode(self, obj, context, path): 14 | return _strarray._parse(BytesIO(obj), context, path) 15 | 16 | 17 | def GUID(name): 18 | return name / Struct( 19 | "Data1" / Int32ul, 20 | "Data2" / Int16ul, 21 | "Data3" / Int16ul, 22 | "Data4" / Bytes(8), 23 | ) 24 | 25 | 26 | Info = "Info" / Struct( 27 | "Version" / Int32ul, 28 | "TimeDateStamp" / Int32ul, 29 | "Age" / Int32ul, 30 | GUID("GUID"), 31 | "cbNames" / Int32ul, 32 | "names" / StringArrayAdapter(Bytes(lambda ctx: ctx.cbNames)), 33 | ) 34 | 35 | 36 | def parse_stream(stream): 37 | return Info.parse_stream(stream) 38 | 39 | 40 | def parse(data): 41 | return Info.parse(data) 42 | -------------------------------------------------------------------------------- /forklib/pdbparse/omap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from construct import * 4 | from bisect import bisect 5 | 6 | OMAP_ENTRY = "OmapFromSrc" / Struct( 7 | "From" / Int32ul, 8 | "To" / Int32ul, 9 | ) 10 | 11 | OMAP_ENTRIES = GreedyRange(OMAP_ENTRY) 12 | 13 | 14 | class Omap(object): 15 | 16 | def __init__(self, omapstream): 17 | self.omap = OMAP_ENTRIES.parse(omapstream) 18 | 19 | self._froms = None 20 | 21 | def remap(self, address): 22 | if not self._froms: 23 | self._froms = [o.From for o in self.omap] 24 | 25 | pos = bisect(self._froms, address) 26 | if self._froms[pos] != address: 27 | pos = pos - 1 28 | 29 | if self.omap[pos].To == 0: 30 | return self.omap[pos].To 31 | else: 32 | return self.omap[pos].To + (address - self.omap[pos].From) 33 | -------------------------------------------------------------------------------- /forklib/pdbparse/pe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from construct import * 4 | 5 | IMAGE_SECTION_HEADER = "IMAGE_SECTION_HEADER" / Struct( 6 | "Name" / PaddedString(8, encoding = "utf8"), 7 | "Misc" / Union( 8 | 0, 9 | "PhysicalAddress" / Int32ul, 10 | "VirtualSize" / Int32ul, 11 | ), 12 | "VirtualAddress" / Int32ul, 13 | "SizeOfRawData" / Int32ul, 14 | "PointerToRawData" / Int32ul, 15 | "PointerToRelocations" / Int32ul, 16 | "PointerToLinenumbers" / Int32ul, 17 | "NumberOfRelocations" / Int16ul, 18 | "NumberOfLinenumbers" / Int16ul, 19 | "Characteristics" / Int32ul, 20 | ) 21 | 22 | Sections = GreedyRange(IMAGE_SECTION_HEADER) 23 | -------------------------------------------------------------------------------- /forklib/pdbparse/peinfo.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | import ntpath 3 | import sys 4 | 5 | from pefile import PE, DEBUG_TYPE, DIRECTORY_ENTRY 6 | 7 | from pdbparse.dbgold import CV_RSDS_HEADER, CV_NB10_HEADER 8 | 9 | 10 | class PENoDebugDirectoryEntriesError(Exception): 11 | pass 12 | 13 | 14 | def get_pe_debug_data(filename): 15 | pe = PE(filename, fast_load = True) 16 | # we prefer CodeView data to misc 17 | type = u'IMAGE_DEBUG_TYPE_CODEVIEW' 18 | dbgdata = get_debug_data(pe, DEBUG_TYPE[type]) 19 | if dbgdata is None: 20 | type = u'IMAGE_DEBUG_TYPE_MISC' 21 | dbgdata = get_debug_data(pe, DEBUG_TYPE[type]) 22 | if dbgdata is None: 23 | type = None 24 | return dbgdata, type 25 | 26 | 27 | def get_external_codeview(filename): 28 | """ 29 | Extract filename's debug CodeView information. 30 | Parameter: 31 | * (bytes) filename, path to input PE 32 | Return : 33 | * (str) the GUID 34 | * (str) the pdb filename 35 | """ 36 | pe = PE(filename, fast_load = True) 37 | dbgdata = get_debug_data(pe, DEBUG_TYPE[u'IMAGE_DEBUG_TYPE_CODEVIEW']) 38 | if dbgdata[:4] == b'RSDS': 39 | (guid, filename) = get_rsds(dbgdata) 40 | elif dbgdata[:4] == b'NB10': 41 | (guid, filename) = get_nb10(dbgdata) 42 | else: 43 | raise TypeError(u'Invalid CodeView signature: [%s]' % dbgdata[:4]) 44 | guid = guid.upper() 45 | return guid, filename 46 | 47 | 48 | def get_debug_data(pe, type = DEBUG_TYPE[u'IMAGE_DEBUG_TYPE_CODEVIEW']): 49 | retval = None 50 | if not hasattr(pe, u'DIRECTORY_ENTRY_DEBUG'): 51 | # fast loaded - load directory 52 | pe.parse_data_directories(DIRECTORY_ENTRY[u'IMAGE_DIRECTORY_ENTRY_DEBUG']) 53 | if not hasattr(pe, u'DIRECTORY_ENTRY_DEBUG'): 54 | raise PENoDebugDirectoryEntriesError() 55 | else: 56 | for entry in pe.DIRECTORY_ENTRY_DEBUG: 57 | off = entry.struct.PointerToRawData 58 | size = entry.struct.SizeOfData 59 | if entry.struct.Type == type: 60 | retval = pe.__data__[off:off + size] 61 | break 62 | return retval 63 | 64 | 65 | def get_dbg_fname(dbgdata): 66 | """ 67 | Parse the MSIC header using construct. 68 | Parameter: 69 | * (bytes) dbgdata, the raw bytes header 70 | Return : 71 | * (str) the .dbg filename 72 | """ 73 | from pdbparse.dbgold import IMAGE_DEBUG_MISC 74 | dbgstruct = IMAGE_DEBUG_MISC.parse(dbgdata) 75 | raw_filename = dbgstruct.Strings[0].decode('ascii') 76 | return ntpath.basename(raw_filename) 77 | 78 | 79 | def get_rsds(dbgdata): 80 | """ 81 | Parse the RSDS header using construct. 82 | Parameter: 83 | * (bytes) dbgdata, the raw bytes header 84 | Return : 85 | * (str) the GUID 86 | * (str) the pdb filename 87 | """ 88 | dbg = CV_RSDS_HEADER.parse(dbgdata) 89 | guidstr = u"%08x%04x%04x%s%x" % (dbg.GUID.Data1, dbg.GUID.Data2, dbg.GUID.Data3, binascii.hexlify( 90 | dbg.GUID.Data4).decode('ascii'), dbg.Age) 91 | filename = ntpath.basename(dbg.Filename) 92 | return guidstr, filename 93 | 94 | 95 | def get_nb10(dbgdata): 96 | """ 97 | Parse the NB10 header using construct. 98 | Parameter: 99 | * (bytes) dbgdata, the raw bytes header 100 | Return : 101 | * the GUID string (i.e. file timestamp) 102 | * the pdb filename str 103 | """ 104 | dbg = CV_NB10_HEADER.parse(dbgdata) 105 | guidstr = u"%x%x" % (dbg.Timestamp, dbg.Age) 106 | filename = ntpath.basename(dbg.Filename) 107 | return guidstr, filename 108 | 109 | 110 | def get_pe_guid(filename): 111 | """ 112 | Return the PE GUID based on TimeDateStamp and SizeOfImage. 113 | Parameter: 114 | * (str) PE filename 115 | Returns: 116 | * (str) PE GUID 117 | """ 118 | try: 119 | pe = PE(filename, fast_load = True) 120 | except IOError as e: 121 | print(e) 122 | sys.exit(-1) 123 | guidstr = "%x%x" % (pe.FILE_HEADER.TimeDateStamp, pe.OPTIONAL_HEADER.SizeOfImage) 124 | return guidstr 125 | -------------------------------------------------------------------------------- /forklib/pdbparse/symlookup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from bisect import bisect_right 3 | from operator import itemgetter, attrgetter 4 | 5 | import pdbparse 6 | 7 | 8 | class DummyOmap(object): 9 | 10 | def remap(self, addr): 11 | return addr 12 | 13 | 14 | class Lookup(object): 15 | 16 | def __init__(self, mods): 17 | self.addrs = {} 18 | self._cache = {} 19 | 20 | not_found = [] 21 | 22 | for pdbname, base in mods: 23 | pdbbase = ".".join(os.path.basename(pdbname).split('.')[:-1]) 24 | if not os.path.exists(pdbname): 25 | print("WARN: %s not found" % pdbname) 26 | not_found.append((base, pdbbase)) 27 | continue 28 | 29 | # print ("Loading symbols for %s..." % pdbbase) 30 | try: 31 | # Do this the hard way to avoid having to load 32 | # the types stream in mammoth PDB files 33 | pdb = pdbparse.parse(pdbname, fast_load = True) 34 | pdb.STREAM_DBI.load() 35 | pdb._update_names() 36 | pdb.STREAM_GSYM = pdb.STREAM_GSYM.reload() 37 | if pdb.STREAM_GSYM.size: 38 | pdb.STREAM_GSYM.load() 39 | pdb.STREAM_SECT_HDR = pdb.STREAM_SECT_HDR.reload() 40 | pdb.STREAM_SECT_HDR.load() 41 | # These are the dicey ones 42 | pdb.STREAM_OMAP_FROM_SRC = pdb.STREAM_OMAP_FROM_SRC.reload() 43 | pdb.STREAM_OMAP_FROM_SRC.load() 44 | pdb.STREAM_SECT_HDR_ORIG = pdb.STREAM_SECT_HDR_ORIG.reload() 45 | pdb.STREAM_SECT_HDR_ORIG.load() 46 | 47 | except AttributeError as e: 48 | pass 49 | # except Exception as e: 50 | # print ("WARN: error %s parsing %s, skipping" % (e,pdbbase)) 51 | # not_found.append( (base, pdbbase) ) 52 | # continue 53 | 54 | try: 55 | sects = pdb.STREAM_SECT_HDR_ORIG.sections 56 | omap = pdb.STREAM_OMAP_FROM_SRC 57 | except AttributeError as e: 58 | # In this case there is no OMAP, so we use the given section 59 | # headers and use the identity function for omap.remap 60 | sects = pdb.STREAM_SECT_HDR.sections 61 | omap = DummyOmap() 62 | gsyms = pdb.STREAM_GSYM 63 | if not hasattr(gsyms, 'globals'): 64 | gsyms.globals = [] 65 | 66 | last_sect = max(sects, key = attrgetter('VirtualAddress')) 67 | limit = base + last_sect.VirtualAddress + last_sect.Misc.VirtualSize 68 | 69 | self.addrs[base, limit] = {} 70 | self.addrs[base, limit]['name'] = pdbbase 71 | self.addrs[base, limit]['addrs'] = [] 72 | for sym in gsyms.globals: 73 | if not hasattr(sym, 'offset'): 74 | continue 75 | off = sym.offset 76 | try: 77 | virt_base = sects[sym.segment - 1].VirtualAddress 78 | except IndexError: 79 | continue 80 | 81 | mapped = omap.remap(off + virt_base) + base 82 | self.addrs[base, limit]['addrs'].append((mapped, sym.name)) 83 | 84 | self.addrs[base, limit]['addrs'].sort(key = itemgetter(0)) 85 | 86 | self.locs = {} 87 | self.names = {} 88 | for base, limit in self.addrs: 89 | mod = self.addrs[base, limit]['name'] 90 | symbols = self.addrs[base, limit]['addrs'] 91 | self.locs[base, limit] = [a[0] for a in symbols] 92 | self.names[base, limit] = [a[1] for a in symbols] 93 | 94 | def lookup(self, loc): 95 | if loc in self._cache: 96 | return self._cache[loc] 97 | 98 | for base, limit in self.addrs: 99 | if loc >= base and loc < limit: 100 | mod = self.addrs[base, limit]['name'] 101 | symbols = self.addrs[base, limit]['addrs'] 102 | locs = self.locs[base, limit] 103 | names = self.names[base, limit] 104 | idx = bisect_right(locs, loc) - 1 105 | diff = loc - locs[idx] 106 | if diff: 107 | ret = "%s!%s+%#x" % (mod, names[idx], diff) 108 | else: 109 | ret = "%s!%s" % (mod, names[idx]) 110 | self._cache[loc] = ret 111 | return ret 112 | return "unknown" 113 | -------------------------------------------------------------------------------- /forklib/pdbparse/undecorate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | prefixes = "__imp__", "__imp_@", "__imp_", "_", "@", "\x7F" 4 | 5 | 6 | def undecorate(name): 7 | stack = -1 8 | conv = "UNDEFINED" 9 | orig_name = name 10 | for p in prefixes: 11 | if name.startswith(p): 12 | name = name[len(p):] 13 | break 14 | 15 | if name.startswith("@@") or name.startswith("?"): 16 | name = orig_name 17 | else: 18 | name_parts = name.split("@") 19 | if len(name_parts) == 2: 20 | try: 21 | stack = int(name_parts[1]) 22 | name = name_parts[0] 23 | except ValueError: 24 | stack = -1 25 | name = orig_name 26 | 27 | if len(p) == 1: 28 | if p == "_": 29 | conv = "FASTCALL" 30 | elif p == "@": 31 | if stack == -1: conv = "CDECL" 32 | else: conv = "STDCALL" 33 | return (name, stack, conv) 34 | -------------------------------------------------------------------------------- /forklib/pdbparse/undname.py: -------------------------------------------------------------------------------- 1 | import os 2 | from . import _undname # automatically resolve and load shared library (_undame.pyd or _undame.so) 3 | 4 | UNDNAME_COMPLETE = 0x0000 5 | UNDNAME_NO_LEADING_UNDERSCORES = 0x0001 # Don't show __ in calling convention 6 | UNDNAME_NO_MS_KEYWORDS = 0x0002 # Don't show calling convention at all 7 | UNDNAME_NO_FUNCTION_RETURNS = 0x0004 # Don't show function/method return value 8 | UNDNAME_NO_ALLOCATION_MODEL = 0x0008 9 | UNDNAME_NO_ALLOCATION_LANGUAGE = 0x0010 10 | UNDNAME_NO_MS_THISTYPE = 0x0020 11 | UNDNAME_NO_CV_THISTYPE = 0x0040 12 | UNDNAME_NO_THISTYPE = 0x0060 13 | UNDNAME_NO_ACCESS_SPECIFIERS = 0x0080 # Don't show access specifier public/protected/private 14 | UNDNAME_NO_THROW_SIGNATURES = 0x0100 15 | UNDNAME_NO_MEMBER_TYPE = 0x0200 # Don't show static/virtual specifier 16 | UNDNAME_NO_RETURN_UDT_MODEL = 0x0400 17 | UNDNAME_32_BIT_DECODE = 0x0800 18 | UNDNAME_NAME_ONLY = 0x1000 # Only report the variable/method name 19 | UNDNAME_NO_ARGUMENTS = 0x2000 # Don't show method arguments 20 | UNDNAME_NO_SPECIAL_SYMS = 0x4000 21 | UNDNAME_NO_COMPLEX_TYPE = 0x8000 22 | 23 | 24 | def undname(name, flags = UNDNAME_NAME_ONLY): 25 | 26 | if name.startswith("?"): 27 | name = _undname.undname(name, flags) 28 | elif name.startswith("_") or name.startswith("@"): 29 | name = name.rsplit('@', 1)[0][1:] 30 | 31 | return name 32 | -------------------------------------------------------------------------------- /forklib/phnt/README.md: -------------------------------------------------------------------------------- 1 | This collection of Native API header files has been maintained since 2009 for the Process Hacker project, and is the most up-to-date set of Native API definitions that I know of. I have gathered these definitions from official Microsoft header files and symbol files, as well as a lot of reverse engineering and guessing. See `phnt.h` for more information. 2 | 3 | ## Usage 4 | 5 | First make sure that your program is using the latest Windows SDK. 6 | 7 | These header files are designed to be used by user-mode programs. Instead of `#include `, place 8 | 9 | ``` 10 | #include 11 | #include 12 | ``` 13 | 14 | at the top of your program. The first line provides access to the Win32 API as well as the `NTSTATUS` values. The second line provides access to the entire Native API. By default, only definitions present in Windows XP are included into your program. To change this, use one of the following: 15 | 16 | ``` 17 | #define PHNT_VERSION PHNT_WINXP // Windows XP 18 | #define PHNT_VERSION PHNT_WS03 // Windows Server 2003 19 | #define PHNT_VERSION PHNT_VISTA // Windows Vista 20 | #define PHNT_VERSION PHNT_WIN7 // Windows 7 21 | #define PHNT_VERSION PHNT_WIN8 // Windows 8 22 | #define PHNT_VERSION PHNT_WINBLUE // Windows 8.1 23 | #define PHNT_VERSION PHNT_THRESHOLD // Windows 10 24 | ``` 25 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntkeapi.h: -------------------------------------------------------------------------------- 1 | #ifndef _NTKEAPI_H 2 | #define _NTKEAPI_H 3 | 4 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 5 | #define LOW_PRIORITY 0 // Lowest thread priority level 6 | #define LOW_REALTIME_PRIORITY 16 // Lowest realtime priority level 7 | #define HIGH_PRIORITY 31 // Highest thread priority level 8 | #define MAXIMUM_PRIORITY 32 // Number of thread priority levels 9 | #endif 10 | 11 | typedef enum _KTHREAD_STATE 12 | { 13 | Initialized, 14 | Ready, 15 | Running, 16 | Standby, 17 | Terminated, 18 | Waiting, 19 | Transition, 20 | DeferredReady, 21 | GateWaitObsolete, 22 | WaitingForProcessInSwap, 23 | MaximumThreadState 24 | } KTHREAD_STATE, *PKTHREAD_STATE; 25 | 26 | // private 27 | typedef enum _KHETERO_CPU_POLICY 28 | { 29 | KHeteroCpuPolicyAll, 30 | KHeteroCpuPolicyLarge, 31 | KHeteroCpuPolicyLargeOrIdle, 32 | KHeteroCpuPolicySmall, 33 | KHeteroCpuPolicySmallOrIdle, 34 | KHeteroCpuPolicyDynamic, 35 | KHeteroCpuPolicyStaticMax, 36 | KHeteroCpuPolicyBiasedSmall, 37 | KHeteroCpuPolicyBiasedLarge, 38 | KHeteroCpuPolicyDefault, 39 | KHeteroCpuPolicyMax 40 | } KHETERO_CPU_POLICY, *PKHETERO_CPU_POLICY; 41 | 42 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 43 | 44 | typedef enum _KWAIT_REASON 45 | { 46 | Executive, 47 | FreePage, 48 | PageIn, 49 | PoolAllocation, 50 | DelayExecution, 51 | Suspended, 52 | UserRequest, 53 | WrExecutive, 54 | WrFreePage, 55 | WrPageIn, 56 | WrPoolAllocation, 57 | WrDelayExecution, 58 | WrSuspended, 59 | WrUserRequest, 60 | WrEventPair, 61 | WrQueue, 62 | WrLpcReceive, 63 | WrLpcReply, 64 | WrVirtualMemory, 65 | WrPageOut, 66 | WrRendezvous, 67 | WrKeyedEvent, 68 | WrTerminated, 69 | WrProcessInSwap, 70 | WrCpuRateControl, 71 | WrCalloutStack, 72 | WrKernel, 73 | WrResource, 74 | WrPushLock, 75 | WrMutex, 76 | WrQuantumEnd, 77 | WrDispatchInt, 78 | WrPreempted, 79 | WrYieldExecution, 80 | WrFastMutex, 81 | WrGuardedMutex, 82 | WrRundown, 83 | WrAlertByThreadId, 84 | WrDeferredPreempt, 85 | MaximumWaitReason 86 | } KWAIT_REASON, *PKWAIT_REASON; 87 | 88 | typedef enum _KPROFILE_SOURCE 89 | { 90 | ProfileTime, 91 | ProfileAlignmentFixup, 92 | ProfileTotalIssues, 93 | ProfilePipelineDry, 94 | ProfileLoadInstructions, 95 | ProfilePipelineFrozen, 96 | ProfileBranchInstructions, 97 | ProfileTotalNonissues, 98 | ProfileDcacheMisses, 99 | ProfileIcacheMisses, 100 | ProfileCacheMisses, 101 | ProfileBranchMispredictions, 102 | ProfileStoreInstructions, 103 | ProfileFpInstructions, 104 | ProfileIntegerInstructions, 105 | Profile2Issue, 106 | Profile3Issue, 107 | Profile4Issue, 108 | ProfileSpecialInstructions, 109 | ProfileTotalCycles, 110 | ProfileIcacheIssues, 111 | ProfileDcacheAccesses, 112 | ProfileMemoryBarrierCycles, 113 | ProfileLoadLinkedIssues, 114 | ProfileMaximum 115 | } KPROFILE_SOURCE; 116 | 117 | #endif 118 | 119 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 120 | 121 | NTSYSCALLAPI 122 | NTSTATUS 123 | NTAPI 124 | NtCallbackReturn( 125 | _In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer, 126 | _In_ ULONG OutputLength, 127 | _In_ NTSTATUS Status 128 | ); 129 | 130 | #if (PHNT_VERSION >= PHNT_VISTA) 131 | NTSYSCALLAPI 132 | VOID 133 | NTAPI 134 | NtFlushProcessWriteBuffers( 135 | VOID 136 | ); 137 | #endif 138 | 139 | NTSYSCALLAPI 140 | NTSTATUS 141 | NTAPI 142 | NtQueryDebugFilterState( 143 | _In_ ULONG ComponentId, 144 | _In_ ULONG Level 145 | ); 146 | 147 | NTSYSCALLAPI 148 | NTSTATUS 149 | NTAPI 150 | NtSetDebugFilterState( 151 | _In_ ULONG ComponentId, 152 | _In_ ULONG Level, 153 | _In_ BOOLEAN State 154 | ); 155 | 156 | NTSYSCALLAPI 157 | NTSTATUS 158 | NTAPI 159 | NtYieldExecution( 160 | VOID 161 | ); 162 | 163 | #endif 164 | 165 | #endif 166 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntmisc.h: -------------------------------------------------------------------------------- 1 | #ifndef _NTMISC_H 2 | #define _NTMISC_H 3 | 4 | // Filter manager 5 | 6 | #define FLT_PORT_CONNECT 0x0001 7 | #define FLT_PORT_ALL_ACCESS (FLT_PORT_CONNECT | STANDARD_RIGHTS_ALL) 8 | 9 | // VDM 10 | 11 | typedef enum _VDMSERVICECLASS 12 | { 13 | VdmStartExecution, 14 | VdmQueueInterrupt, 15 | VdmDelayInterrupt, 16 | VdmInitialize, 17 | VdmFeatures, 18 | VdmSetInt21Handler, 19 | VdmQueryDir, 20 | VdmPrinterDirectIoOpen, 21 | VdmPrinterDirectIoClose, 22 | VdmPrinterInitialize, 23 | VdmSetLdtEntries, 24 | VdmSetProcessLdtInfo, 25 | VdmAdlibEmulation, 26 | VdmPMCliControl, 27 | VdmQueryVdmProcess 28 | } VDMSERVICECLASS, *PVDMSERVICECLASS; 29 | 30 | NTSYSCALLAPI 31 | NTSTATUS 32 | NTAPI 33 | NtVdmControl( 34 | _In_ VDMSERVICECLASS Service, 35 | _Inout_ PVOID ServiceData 36 | ); 37 | 38 | // WMI/ETW 39 | 40 | NTSYSCALLAPI 41 | NTSTATUS 42 | NTAPI 43 | NtTraceEvent( 44 | _In_ HANDLE TraceHandle, 45 | _In_ ULONG Flags, 46 | _In_ ULONG FieldSize, 47 | _In_ PVOID Fields 48 | ); 49 | 50 | #if (PHNT_VERSION >= PHNT_VISTA) 51 | // private 52 | NTSYSCALLAPI 53 | NTSTATUS 54 | NTAPI 55 | NtTraceControl( 56 | _In_ ULONG FunctionCode, 57 | _In_reads_bytes_opt_(InBufferLen) PVOID InBuffer, 58 | _In_ ULONG InBufferLen, 59 | _Out_writes_bytes_opt_(OutBufferLen) PVOID OutBuffer, 60 | _In_ ULONG OutBufferLen, 61 | _Out_ PULONG ReturnLength 62 | ); 63 | #endif 64 | 65 | #endif 66 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntnls.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Process Hacker - 3 | * National Language Support functions 4 | * 5 | * This file is part of Process Hacker. 6 | * 7 | * Process Hacker is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * Process Hacker is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with Process Hacker. If not, see . 19 | */ 20 | 21 | #ifndef _NTNLS_H 22 | #define _NTNLS_H 23 | 24 | #define MAXIMUM_LEADBYTES 12 25 | 26 | typedef struct _CPTABLEINFO 27 | { 28 | USHORT CodePage; 29 | USHORT MaximumCharacterSize; 30 | USHORT DefaultChar; 31 | USHORT UniDefaultChar; 32 | USHORT TransDefaultChar; 33 | USHORT TransUniDefaultChar; 34 | USHORT DBCSCodePage; 35 | UCHAR LeadByte[MAXIMUM_LEADBYTES]; 36 | PUSHORT MultiByteTable; 37 | PVOID WideCharTable; 38 | PUSHORT DBCSRanges; 39 | PUSHORT DBCSOffsets; 40 | } CPTABLEINFO, *PCPTABLEINFO; 41 | 42 | typedef struct _NLSTABLEINFO 43 | { 44 | CPTABLEINFO OemTableInfo; 45 | CPTABLEINFO AnsiTableInfo; 46 | PUSHORT UpperCaseTable; 47 | PUSHORT LowerCaseTable; 48 | } NLSTABLEINFO, *PNLSTABLEINFO; 49 | 50 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 51 | NTSYSAPI USHORT NlsAnsiCodePage; 52 | NTSYSAPI BOOLEAN NlsMbCodePageTag; 53 | NTSYSAPI BOOLEAN NlsMbOemCodePageTag; 54 | #endif 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntpnpapi.h: -------------------------------------------------------------------------------- 1 | #ifndef _NTPNPAPI_H 2 | #define _NTPNPAPI_H 3 | 4 | typedef enum _PLUGPLAY_EVENT_CATEGORY 5 | { 6 | HardwareProfileChangeEvent, 7 | TargetDeviceChangeEvent, 8 | DeviceClassChangeEvent, 9 | CustomDeviceEvent, 10 | DeviceInstallEvent, 11 | DeviceArrivalEvent, 12 | PowerEvent, 13 | VetoEvent, 14 | BlockedDriverEvent, 15 | InvalidIDEvent, 16 | MaxPlugEventCategory 17 | } PLUGPLAY_EVENT_CATEGORY, *PPLUGPLAY_EVENT_CATEGORY; 18 | 19 | typedef struct _PLUGPLAY_EVENT_BLOCK 20 | { 21 | GUID EventGuid; 22 | PLUGPLAY_EVENT_CATEGORY EventCategory; 23 | PULONG Result; 24 | ULONG Flags; 25 | ULONG TotalSize; 26 | PVOID DeviceObject; 27 | 28 | union 29 | { 30 | struct 31 | { 32 | GUID ClassGuid; 33 | WCHAR SymbolicLinkName[1]; 34 | } DeviceClass; 35 | struct 36 | { 37 | WCHAR DeviceIds[1]; 38 | } TargetDevice; 39 | struct 40 | { 41 | WCHAR DeviceId[1]; 42 | } InstallDevice; 43 | struct 44 | { 45 | PVOID NotificationStructure; 46 | WCHAR DeviceIds[1]; 47 | } CustomNotification; 48 | struct 49 | { 50 | PVOID Notification; 51 | } ProfileNotification; 52 | struct 53 | { 54 | ULONG NotificationCode; 55 | ULONG NotificationData; 56 | } PowerNotification; 57 | struct 58 | { 59 | PNP_VETO_TYPE VetoType; 60 | WCHAR DeviceIdVetoNameBuffer[1]; // DeviceIdVetoName 61 | } VetoNotification; 62 | struct 63 | { 64 | GUID BlockedDriverGuid; 65 | } BlockedDriverNotification; 66 | struct 67 | { 68 | WCHAR ParentId[1]; 69 | } InvalidIDNotification; 70 | } u; 71 | } PLUGPLAY_EVENT_BLOCK, *PPLUGPLAY_EVENT_BLOCK; 72 | 73 | typedef enum _PLUGPLAY_CONTROL_CLASS 74 | { 75 | PlugPlayControlEnumerateDevice, 76 | PlugPlayControlRegisterNewDevice, 77 | PlugPlayControlDeregisterDevice, 78 | PlugPlayControlInitializeDevice, 79 | PlugPlayControlStartDevice, 80 | PlugPlayControlUnlockDevice, 81 | PlugPlayControlQueryAndRemoveDevice, 82 | PlugPlayControlUserResponse, 83 | PlugPlayControlGenerateLegacyDevice, 84 | PlugPlayControlGetInterfaceDeviceList, 85 | PlugPlayControlProperty, 86 | PlugPlayControlDeviceClassAssociation, 87 | PlugPlayControlGetRelatedDevice, 88 | PlugPlayControlGetInterfaceDeviceAlias, 89 | PlugPlayControlDeviceStatus, 90 | PlugPlayControlGetDeviceDepth, 91 | PlugPlayControlQueryDeviceRelations, 92 | PlugPlayControlTargetDeviceRelation, 93 | PlugPlayControlQueryConflictList, 94 | PlugPlayControlRetrieveDock, 95 | PlugPlayControlResetDevice, 96 | PlugPlayControlHaltDevice, 97 | PlugPlayControlGetBlockedDriverList, 98 | PlugPlayControlGetDeviceInterfaceEnabled, 99 | MaxPlugPlayControl 100 | } PLUGPLAY_CONTROL_CLASS, *PPLUGPLAY_CONTROL_CLASS; 101 | 102 | #if (PHNT_VERSION < PHNT_WIN8) 103 | NTSYSCALLAPI 104 | NTSTATUS 105 | NTAPI 106 | NtGetPlugPlayEvent( 107 | _In_ HANDLE EventHandle, 108 | _In_opt_ PVOID Context, 109 | _Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock, 110 | _In_ ULONG EventBufferSize 111 | ); 112 | #endif 113 | 114 | NTSYSCALLAPI 115 | NTSTATUS 116 | NTAPI 117 | NtPlugPlayControl( 118 | _In_ PLUGPLAY_CONTROL_CLASS PnPControlClass, 119 | _Inout_updates_bytes_(PnPControlDataLength) PVOID PnPControlData, 120 | _In_ ULONG PnPControlDataLength 121 | ); 122 | 123 | #if (PHNT_VERSION >= PHNT_WIN7) 124 | 125 | NTSYSCALLAPI 126 | NTSTATUS 127 | NTAPI 128 | NtSerializeBoot( 129 | VOID 130 | ); 131 | 132 | NTSYSCALLAPI 133 | NTSTATUS 134 | NTAPI 135 | NtEnableLastKnownGood( 136 | VOID 137 | ); 138 | 139 | NTSYSCALLAPI 140 | NTSTATUS 141 | NTAPI 142 | NtDisableLastKnownGood( 143 | VOID 144 | ); 145 | 146 | #endif 147 | 148 | #if (PHNT_VERSION >= PHNT_VISTA) 149 | NTSYSCALLAPI 150 | NTSTATUS 151 | NTAPI 152 | NtReplacePartitionUnit( 153 | _In_ PUNICODE_STRING TargetInstancePath, 154 | _In_ PUNICODE_STRING SpareInstancePath, 155 | _In_ ULONG Flags 156 | ); 157 | #endif 158 | 159 | #endif 160 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntsmss.h: -------------------------------------------------------------------------------- 1 | #ifndef _NTSMSS_H 2 | #define _NTSMSS_H 3 | 4 | NTSYSAPI 5 | NTSTATUS 6 | NTAPI 7 | RtlConnectToSm( 8 | _In_ PUNICODE_STRING ApiPortName, 9 | _In_ HANDLE ApiPortHandle, 10 | _In_ DWORD ProcessImageType, 11 | _Out_ PHANDLE SmssConnection 12 | ); 13 | 14 | NTSYSAPI 15 | NTSTATUS 16 | NTAPI 17 | RtlSendMsgToSm( 18 | _In_ HANDLE ApiPortHandle, 19 | _In_ PPORT_MESSAGE MessageData 20 | ); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /forklib/phnt/include/ntxcapi.h: -------------------------------------------------------------------------------- 1 | #ifndef _NTXCAPI_H 2 | #define _NTXCAPI_H 3 | 4 | NTSYSAPI 5 | BOOLEAN 6 | NTAPI 7 | RtlDispatchException( 8 | _In_ PEXCEPTION_RECORD ExceptionRecord, 9 | _In_ PCONTEXT ContextRecord 10 | ); 11 | 12 | NTSYSAPI 13 | DECLSPEC_NORETURN 14 | VOID 15 | NTAPI 16 | RtlRaiseStatus( 17 | _In_ NTSTATUS Status 18 | ); 19 | 20 | NTSYSAPI 21 | VOID 22 | NTAPI 23 | RtlRaiseException( 24 | _In_ PEXCEPTION_RECORD ExceptionRecord 25 | ); 26 | 27 | NTSYSCALLAPI 28 | NTSTATUS 29 | NTAPI 30 | NtContinue( 31 | _In_ PCONTEXT ContextRecord, 32 | _In_ BOOLEAN TestAlert 33 | ); 34 | 35 | NTSYSCALLAPI 36 | NTSTATUS 37 | NTAPI 38 | NtRaiseException( 39 | _In_ PEXCEPTION_RECORD ExceptionRecord, 40 | _In_ PCONTEXT ContextRecord, 41 | _In_ BOOLEAN FirstChance 42 | ); 43 | 44 | __analysis_noreturn 45 | NTSYSCALLAPI 46 | VOID 47 | NTAPI 48 | RtlAssert( 49 | _In_ PVOID VoidFailedAssertion, 50 | _In_ PVOID VoidFileName, 51 | _In_ ULONG LineNumber, 52 | _In_opt_ PSTR MutableMessage 53 | ); 54 | 55 | #define RTL_ASSERT(exp) \ 56 | ((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, NULL), FALSE) : TRUE) 57 | #define RTL_ASSERTMSG(msg, exp) \ 58 | ((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, msg), FALSE) : TRUE) 59 | #define RTL_SOFT_ASSERT(_exp) \ 60 | ((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n Expression: %s\n", __FILE__, __LINE__, #_exp), FALSE) : TRUE) 61 | #define RTL_SOFT_ASSERTMSG(_msg, _exp) \ 62 | ((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n Expression: %s\n Message: %s\n", __FILE__, __LINE__, #_exp, (_msg)), FALSE) : TRUE) 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /forklib/phnt/include/phnt.h: -------------------------------------------------------------------------------- 1 | #ifndef _PHNT_H 2 | #define _PHNT_H 3 | 4 | // This header file provides access to NT APIs. 5 | 6 | // Definitions are annotated to indicate their source. If a definition is not annotated, it has been 7 | // retrieved from an official Microsoft source (NT headers, DDK headers, winnt.h). 8 | 9 | // * "winbase" indicates that a definition has been reconstructed from a Win32-ized NT definition in 10 | // winbase.h. 11 | // * "rev" indicates that a definition has been reverse-engineered. 12 | // * "dbg" indicates that a definition has been obtained from a debug message or assertion in a 13 | // checked build of the kernel or file. 14 | 15 | // Reliability: 16 | // 1. No annotation. 17 | // 2. dbg. 18 | // 3. symbols, private. Types may be incorrect. 19 | // 4. winbase. Names and types may be incorrect. 20 | // 5. rev. 21 | 22 | // Mode 23 | #define PHNT_MODE_KERNEL 0 24 | #define PHNT_MODE_USER 1 25 | 26 | // Version 27 | #define PHNT_WIN2K 50 28 | #define PHNT_WINXP 51 29 | #define PHNT_WS03 52 30 | #define PHNT_VISTA 60 31 | #define PHNT_WIN7 61 32 | #define PHNT_WIN8 62 33 | #define PHNT_WINBLUE 63 34 | #define PHNT_THRESHOLD 100 35 | #define PHNT_THRESHOLD2 101 36 | #define PHNT_REDSTONE 102 37 | #define PHNT_REDSTONE2 103 38 | #define PHNT_REDSTONE3 104 39 | #define PHNT_REDSTONE4 105 40 | #define PHNT_REDSTONE5 106 41 | #define PHNT_REDSTONE6 107 42 | 43 | #ifndef PHNT_MODE 44 | #define PHNT_MODE PHNT_MODE_USER 45 | #endif 46 | 47 | #ifndef PHNT_VERSION 48 | #define PHNT_VERSION PHNT_WIN7 49 | #endif 50 | 51 | // Options 52 | 53 | //#define PHNT_NO_INLINE_INIT_STRING 54 | 55 | #ifdef __cplusplus 56 | extern "C" { 57 | #endif 58 | 59 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 60 | #include 61 | #include 62 | #include 63 | #endif 64 | 65 | #include 66 | #include 67 | 68 | #include 69 | #include 70 | #include 71 | 72 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | #include 81 | #include 82 | #endif 83 | 84 | #if (PHNT_MODE != PHNT_MODE_KERNEL) 85 | 86 | #include 87 | #include 88 | #include 89 | #include 90 | 91 | #include 92 | 93 | #include 94 | #include 95 | 96 | #include 97 | 98 | #include 99 | 100 | #endif 101 | 102 | #ifdef __cplusplus 103 | } 104 | #endif 105 | 106 | #endif 107 | -------------------------------------------------------------------------------- /forklib/phnt/include/phnt_windows.h: -------------------------------------------------------------------------------- 1 | #ifndef _PHNT_WINDOWS_H 2 | #define _PHNT_WINDOWS_H 3 | 4 | // This header file provides access to Win32, plus NTSTATUS values and some access mask values. 5 | 6 | #ifndef CINTERFACE 7 | #define CINTERFACE 8 | #endif 9 | 10 | #ifndef COBJMACROS 11 | #define COBJMACROS 12 | #endif 13 | 14 | #ifndef INITGUID 15 | #define INITGUID 16 | #endif 17 | 18 | #ifndef WIN32_LEAN_AND_MEAN 19 | #define WIN32_LEAN_AND_MEAN 20 | #endif 21 | 22 | #ifndef WIN32_NO_STATUS 23 | #define WIN32_NO_STATUS 24 | #endif 25 | 26 | #include 27 | #include 28 | #undef WIN32_NO_STATUS 29 | #include 30 | #include 31 | 32 | typedef double DOUBLE; 33 | typedef GUID *PGUID; 34 | 35 | // Desktop access rights 36 | #define DESKTOP_ALL_ACCESS \ 37 | (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | \ 38 | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | \ 39 | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_WRITEOBJECTS | \ 40 | STANDARD_RIGHTS_REQUIRED) 41 | #define DESKTOP_GENERIC_READ \ 42 | (DESKTOP_ENUMERATE | DESKTOP_READOBJECTS | STANDARD_RIGHTS_READ) 43 | #define DESKTOP_GENERIC_WRITE \ 44 | (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | \ 45 | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | DESKTOP_WRITEOBJECTS | \ 46 | STANDARD_RIGHTS_WRITE) 47 | #define DESKTOP_GENERIC_EXECUTE \ 48 | (DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_EXECUTE) 49 | 50 | // Window station access rights 51 | #define WINSTA_GENERIC_READ \ 52 | (WINSTA_ENUMDESKTOPS | WINSTA_ENUMERATE | WINSTA_READATTRIBUTES | \ 53 | WINSTA_READSCREEN | STANDARD_RIGHTS_READ) 54 | #define WINSTA_GENERIC_WRITE \ 55 | (WINSTA_ACCESSCLIPBOARD | WINSTA_CREATEDESKTOP | WINSTA_WRITEATTRIBUTES | \ 56 | STANDARD_RIGHTS_WRITE) 57 | #define WINSTA_GENERIC_EXECUTE \ 58 | (WINSTA_ACCESSGLOBALATOMS | WINSTA_EXITWINDOWS | STANDARD_RIGHTS_EXECUTE) 59 | 60 | // WMI access rights 61 | #define WMIGUID_GENERIC_READ \ 62 | (WMIGUID_QUERY | WMIGUID_NOTIFICATION | WMIGUID_READ_DESCRIPTION | \ 63 | STANDARD_RIGHTS_READ) 64 | #define WMIGUID_GENERIC_WRITE \ 65 | (WMIGUID_SET | TRACELOG_CREATE_REALTIME | TRACELOG_CREATE_ONDISK | \ 66 | STANDARD_RIGHTS_WRITE) 67 | #define WMIGUID_GENERIC_EXECUTE \ 68 | (WMIGUID_EXECUTE | TRACELOG_GUID_ENABLE | TRACELOG_LOG_EVENT | \ 69 | TRACELOG_ACCESS_REALTIME | TRACELOG_REGISTER_GUIDS | \ 70 | STANDARD_RIGHTS_EXECUTE) 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /forklib/phnt/include/subprocesstag.h: -------------------------------------------------------------------------------- 1 | #ifndef _SUBPROCESSTAG_H 2 | #define _SUBPROCESSTAG_H 3 | 4 | // Subprocess tag information 5 | 6 | typedef enum _TAG_INFO_LEVEL 7 | { 8 | eTagInfoLevelNameFromTag = 1, // TAG_INFO_NAME_FROM_TAG 9 | eTagInfoLevelNamesReferencingModule, // TAG_INFO_NAMES_REFERENCING_MODULE 10 | eTagInfoLevelNameTagMapping, // TAG_INFO_NAME_TAG_MAPPING 11 | eTagInfoLevelMax 12 | } TAG_INFO_LEVEL; 13 | 14 | typedef enum _TAG_TYPE 15 | { 16 | eTagTypeService = 1, 17 | eTagTypeMax 18 | } TAG_TYPE; 19 | 20 | typedef struct _TAG_INFO_NAME_FROM_TAG_IN_PARAMS 21 | { 22 | DWORD dwPid; 23 | DWORD dwTag; 24 | } TAG_INFO_NAME_FROM_TAG_IN_PARAMS, *PTAG_INFO_NAME_FROM_TAG_IN_PARAMS; 25 | 26 | typedef struct _TAG_INFO_NAME_FROM_TAG_OUT_PARAMS 27 | { 28 | DWORD eTagType; 29 | LPWSTR pszName; 30 | } TAG_INFO_NAME_FROM_TAG_OUT_PARAMS, *PTAG_INFO_NAME_FROM_TAG_OUT_PARAMS; 31 | 32 | typedef struct _TAG_INFO_NAME_FROM_TAG 33 | { 34 | TAG_INFO_NAME_FROM_TAG_IN_PARAMS InParams; 35 | TAG_INFO_NAME_FROM_TAG_OUT_PARAMS OutParams; 36 | } TAG_INFO_NAME_FROM_TAG, *PTAG_INFO_NAME_FROM_TAG; 37 | 38 | typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS 39 | { 40 | DWORD dwPid; 41 | LPWSTR pszModule; 42 | } TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS, *PTAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS; 43 | 44 | typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS 45 | { 46 | DWORD eTagType; 47 | LPWSTR pmszNames; 48 | } TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS, *PTAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS; 49 | 50 | typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE 51 | { 52 | TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS InParams; 53 | TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS OutParams; 54 | } TAG_INFO_NAMES_REFERENCING_MODULE, *PTAG_INFO_NAMES_REFERENCING_MODULE; 55 | 56 | typedef struct _TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS 57 | { 58 | DWORD dwPid; 59 | } TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS, *PTAG_INFO_NAME_TAG_MAPPING_IN_PARAMS; 60 | 61 | typedef struct _TAG_INFO_NAME_TAG_MAPPING_ELEMENT 62 | { 63 | DWORD eTagType; 64 | DWORD dwTag; 65 | LPWSTR pszName; 66 | LPWSTR pszGroupName; 67 | } TAG_INFO_NAME_TAG_MAPPING_ELEMENT, *PTAG_INFO_NAME_TAG_MAPPING_ELEMENT; 68 | 69 | typedef struct _TAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS 70 | { 71 | DWORD cElements; 72 | PTAG_INFO_NAME_TAG_MAPPING_ELEMENT pNameTagMappingElements; 73 | } TAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS, *PTAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS; 74 | 75 | typedef struct _TAG_INFO_NAME_TAG_MAPPING 76 | { 77 | TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS InParams; 78 | PTAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS pOutParams; 79 | } TAG_INFO_NAME_TAG_MAPPING, *PTAG_INFO_NAME_TAG_MAPPING; 80 | 81 | _Must_inspect_result_ 82 | DWORD 83 | WINAPI 84 | I_QueryTagInformation( 85 | _In_opt_ LPCWSTR pszMachineName, 86 | _In_ TAG_INFO_LEVEL eInfoLevel, 87 | _Inout_ PVOID pTagInfo 88 | ); 89 | 90 | typedef DWORD (WINAPI *PQUERY_TAG_INFORMATION)( 91 | _In_opt_ LPCWSTR pszMachineName, 92 | _In_ TAG_INFO_LEVEL eInfoLevel, 93 | _Inout_ PVOID pTagInfo 94 | ); 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /forklib/phnt/zw_options.txt: -------------------------------------------------------------------------------- 1 | base=include 2 | in=ntdbg.h;ntexapi.h;ntgdi.h;ntioapi.h;ntkeapi.h;ntldr.h;ntlpcapi.h;ntmisc.h;ntmmapi.h;ntnls.h;ntobapi.h;ntpebteb.h;ntpfapi.h;ntpnpapi.h;ntpoapi.h;ntpsapi.h;ntregapi.h;ntrtl.h;ntsam.h;ntseapi.h;nttmapi.h;nttp.h;ntwow64.h;ntxcapi.h 3 | out=ntzwapi.h 4 | header=#ifndef _NTZWAPI_H\r\n#define _NTZWAPI_H\r\n\r\n// This file was automatically generated. Do not edit.\r\n\r\n 5 | footer=#endif\r\n -------------------------------------------------------------------------------- /forklib/stdafx.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | static HMODULE ntdll = GetModuleHandleA("ntdll.dll"); 4 | #define CACHE_PROC(mod, name) name##_t name = (name##_t)GetProcAddress(mod, #name) 5 | 6 | CACHE_PROC(ntdll, NtQueryInformationProcess); 7 | CACHE_PROC(ntdll, NtCreateUserProcess); 8 | CACHE_PROC(ntdll, RtlRegisterThreadWithCsrss); 9 | CACHE_PROC(ntdll, NtQuerySystemInformation); 10 | CACHE_PROC(ntdll, NtQueryObject); 11 | -------------------------------------------------------------------------------- /forklib/stdafx.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "targetver.h" 4 | 5 | #define PHNT_VERSION PHNT_THRESHOLD // Windows 10 6 | #include 7 | #include 8 | -------------------------------------------------------------------------------- /forklib/targetver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // Including SDKDDKVer.h defines the highest available Windows platform. 4 | 5 | // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and 6 | // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. 7 | 8 | #include 9 | -------------------------------------------------------------------------------- /forklib/windows_phnt.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define PHNT_VERSION PHNT_THRESHOLD 4 | #include 5 | #include 6 | -------------------------------------------------------------------------------- /forklib/wow64ext.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | extern "C" 4 | { 5 | extern __declspec(dllimport) DWORD64 __cdecl X64Call(DWORD64 func, int argC, ...); 6 | extern __declspec(dllimport) DWORD64 __cdecl GetModuleHandle64(wchar_t* lpModuleName); 7 | extern __declspec(dllimport) void __cdecl getMem64(void* dstMem, DWORD64 srcMem, size_t sz); 8 | extern __declspec(dllimport) void __cdecl setMem64(DWORD64 dstMem, void* srcMem, size_t sz); 9 | } 10 | -------------------------------------------------------------------------------- /forkserver-proto.h: -------------------------------------------------------------------------------- 1 | // Forkserver Protocol 2 | // 3 | // This file defines structs and constants shared between the main fuzzer exe and the injected forkserver DLL. 4 | 5 | #pragma once 6 | 7 | #include 8 | 9 | // These structures are written directly into the forkserver's memory during initialization. 10 | // They hold fuzzer settings that we want to pass to the forkserver. 11 | 12 | typedef volatile struct _AFL_COVERAGE_INFO 13 | { 14 | size_t NumberOfBasicBlocks; 15 | struct AFL_BASIC_BLOCK 16 | { 17 | char* ModuleName; 18 | uintptr_t Rva; 19 | } BasicBlocks[]; 20 | } AFL_COVERAGE_INFO; 21 | 22 | typedef enum _INJECTION_MODE 23 | { 24 | DRYRUN = 0, 25 | FORK, 26 | PERSISTENT, 27 | } INJECTION_MODE; 28 | 29 | typedef volatile struct _AFL_SETTINGS 30 | { 31 | uint32_t timeout; 32 | INJECTION_MODE mode; 33 | AFL_COVERAGE_INFO* cov_info; // If NULL, coverage is not reported and external tracing is assumed 34 | BOOL enableWER; // Enable minidumps 35 | BOOL debug; // Enable debugging 36 | DWORD_PTR cpuAffinityMask; // Affinity mask for the forkserver. Never put the children on the same processor! 37 | char harness_name[MAX_PATH+1]; 38 | char minidump_path[MAX_PATH+1]; 39 | } AFL_SETTINGS; 40 | 41 | typedef enum _FORKSERVER_STATE 42 | { 43 | FORKSERVER_NOT_READY, 44 | FORKSERVER_READY, 45 | FORKSERVER_WAITING 46 | } FORKSERVER_STATE; 47 | 48 | // These structures define the API passed over the named pipe IPC 49 | 50 | #define AFL_FORKSERVER_SYNC "Global\\harness-sync" 51 | #define AFL_FORKSERVER_PIPE "\\\\.\\pipe\\afl-forkserver" 52 | 53 | enum AFL_FORKSERVER_REQUEST_METHOD 54 | { 55 | AFL_CREATE_NEW_CHILD = 0, // Please spawn a new child! 56 | AFL_RESUME_CHILD, // Please start the suspended child. 57 | AFL_TERMINATE_FORKSERVER, // Please kill yourself. 58 | }; 59 | 60 | typedef struct _AFL_FORKSERVER_REQUEST 61 | { 62 | enum AFL_FORKSERVER_REQUEST_METHOD Operation; //added enum 63 | union 64 | { 65 | struct 66 | { 67 | BYTE DoNotUseThisField; 68 | } 69 | CreateNewChildInfo; 70 | 71 | struct 72 | { 73 | BYTE DoNotUseThisField; 74 | } 75 | ResumeChildInfo; 76 | }; 77 | } AFL_FORKSERVER_REQUEST; 78 | 79 | enum AFL_FORKSERVER_RESULT_STATUS 80 | { 81 | AFL_CHILD_CREATED = 0, 82 | AFL_CHILD_SUCCESS, 83 | AFL_CHILD_CRASHED, 84 | AFL_CHILD_TIMEOUT, 85 | AFL_CHILD_COVERAGE, // new coverage event 86 | }; 87 | 88 | typedef struct _AFL_FORKSERVER_RESULT 89 | { 90 | enum AFL_FORKSERVER_RESULT_STATUS StatusCode; 91 | union 92 | { 93 | struct AFL_CHILD_INFO 94 | { 95 | DWORD ProcessId; 96 | DWORD ThreadId; 97 | } ChildInfo; 98 | struct 99 | { 100 | BYTE DoNotUseThisField; 101 | } SuccessInfo; 102 | struct 103 | { 104 | BYTE DoNotUseThisField; 105 | } CrashInfo; 106 | struct 107 | { 108 | BYTE DoNotUseThisField; 109 | } TimeoutInfo; 110 | struct AFL_COVERAGE_PACKET 111 | { 112 | char ModuleName[MAX_PATH]; 113 | uintptr_t Rva; 114 | } CoverageInfo; 115 | }; 116 | } AFL_FORKSERVER_RESULT, AFL_PERSISTENT_RESULT; 117 | 118 | enum CHILD_FATE 119 | { 120 | CHILD_UNKNOWN = -1, // error? 121 | CHILD_SUCCESS = 0, 122 | CHILD_CRASHED, 123 | CHILD_TIMEOUT, 124 | CHILD_COVERAGE, // new coverage 125 | }; 126 | -------------------------------------------------------------------------------- /harness-api.h: -------------------------------------------------------------------------------- 1 | // Harness API 2 | // 3 | // This file defines an interface fuzzing harnesses must expose for the injected forkserver. 4 | 5 | #pragma once 6 | 7 | #include 8 | #include 9 | 10 | // Unfortunately, no stdatomic without VS 2019. 11 | 12 | typedef volatile struct 13 | { 14 | LPVOID target_method; // Required. The function to hook. The injected component of fuzzer will hook this function and enter the fuzzing loop once it is hit. 15 | void (CALLBACK *fuzz_iter_func)(); // Required. Target function to fuzz. The injected forkserver will call this function repeatedly. The function should follow stdcall convention and return gracefully. 16 | const WCHAR* input_file; // Optional. The input filename that the fuzzer will mutate; for example, L"my_input.txt". If NULL, defaults to L".cur_input". 17 | void (CALLBACK *setup_func)(); // Optional. If not NULL, a function that will be called after the target process initializes, before entering the forkserver loop. 18 | // You might want to use setup_func for doing things like marking all of the handles as inheritable, killing other threads, closing problematic handles, etc. 19 | BOOL network; // Optional. If true, apply de-socket techniques (redirects Winsock APIs) 20 | volatile CHAR ready; // Required. Set this to true only when all the other struct members are populated and ready. 21 | } HARNESS_INFO, *PHARNESS_INFO; 22 | 23 | #define HARNESS_INFO_PROC "HarnessInfo" 24 | 25 | #define EXPOSE_HARNESS(target_method, fuzz_iter_func, preload, input_file, setup_func, network) \ 26 | extern "C" { \ 27 | __declspec(dllexport) HARNESS_INFO HarnessInfo = { \ 28 | target_method, \ 29 | fuzz_iter_func, \ 30 | input_file, \ 31 | setup_func, \ 32 | network, \ 33 | }; \ 34 | }; 35 | -------------------------------------------------------------------------------- /harnessgen/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.bak 4 | temptrace* 5 | domitrace* 6 | .vscode 7 | 8 | # exclude pin binaries 9 | lib/META-INF 10 | lib/pin 11 | lib/pin*zip 12 | 13 | # exclude cache directory 14 | cache/ -------------------------------------------------------------------------------- /harnessgen/harconf.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | 4 | # for functype manager; it invokes an IDAPython script 5 | # TODO: edit this if it doesn't work 6 | ROOT = os.path.dirname(__file__) 7 | IDA_PATH = glob.glob(r'C:\Program Files\IDA *\idat.exe')[0] 8 | IDA_SCRIPT = os.path.join(ROOT, 'util/ida_func_type.py') 9 | FUNCTYPE_CACHE_PATH = os.path.join(ROOT, 'cache') 10 | 11 | if not os.path.isdir(FUNCTYPE_CACHE_PATH): 12 | os.mkdir(FUNCTYPE_CACHE_PATH) 13 | 14 | if not os.path.exists(IDA_SCRIPT): 15 | print("Check if the following file exists:", IDA_SCRIPT) 16 | exit(1) 17 | 18 | # for harnesor 19 | TRACE_PN = "trace" 20 | FUNCTYPE = "functype" 21 | NORMAL_POSTFIX = "normal" 22 | TRACE_PREFIX = ["DC", "RET", "IC", "IJ"] 23 | 24 | THRESHOLD = 0x20 25 | TRACE_MAX = 20 26 | INPUT = "QQQQ" 27 | 28 | NAMEDIC = {} 29 | NAMEDIC['CP'] = "Code Pointer" 30 | NAMEDIC['DP'] = "Data Pointer" 31 | 32 | # for synthesizer 33 | BINREAD = 0x1000 34 | POINTER_SEARCH_LIMIT = 100 35 | INPUT_COMP_LENGTH = 10 -------------------------------------------------------------------------------- /harnessgen/lib/Tracer/Tracer.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29306.81 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tracer", "Tracer.vcxproj", "{639EF517-FCFC-408E-9500-71F0DC0458DB}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.ActiveCfg = Debug|x64 17 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.Build.0 = Debug|x64 18 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.ActiveCfg = Debug|Win32 19 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.Build.0 = Debug|Win32 20 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.ActiveCfg = Release|x64 21 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.Build.0 = Release|x64 22 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.ActiveCfg = Release|Win32 23 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {07CB9EAD-D3D1-4D13-96E3-68BBB515F7B7} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /harnessgen/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | class CuteHandler(logging.StreamHandler): 4 | def emit(self, record): 5 | color = hash(record.name) % 7 + 31 6 | try: 7 | record.name = ("\x1b[%dm" % color) + record.name + "\x1b[0m" 8 | except Exception: 9 | pass 10 | 11 | try: 12 | record.msg = ("\x1b[%dm" % color) + record.msg + "\x1b[0m" 13 | except Exception: 14 | pass 15 | 16 | super(CuteHandler, self).emit(record) 17 | 18 | def getlogger(name): 19 | logger = logging.getLogger(name) 20 | logger.setLevel(logging.INFO) 21 | stream_handler = CuteHandler() 22 | stream_handler.setFormatter(logging.Formatter('%(levelname)-7s | %(asctime)-23s | %(name)-8s | %(message)s')) 23 | logger.addHandler(stream_handler) 24 | 25 | return logger 26 | -------------------------------------------------------------------------------- /harnessgen/requirements.txt: -------------------------------------------------------------------------------- 1 | tqdm 2 | networkx 3 | matplotlib -------------------------------------------------------------------------------- /harnessgen/template.py: -------------------------------------------------------------------------------- 1 | 2 | ASCII_BYTE = ' !"#\\$%&\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\~\t' 3 | 4 | # Directory structure 5 | MAIN_TRACE = 'cor1_1' 6 | SECOND_TRACE = 'cor1_2' 7 | DIFF_TRACE = 'cor2_1' 8 | INPUT1 = 'input1' 9 | INPUT2 = 'input2' 10 | FUNCTYPE = 'functype' 11 | 12 | HEADER = """ 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #define dbg_printf (void)printf 22 | 23 | // Macro to help to loading functions 24 | #define LOAD_FUNC(h, n) \\ 25 | n##_func = (n##_func_t)GetProcAddress(h, #n); \\ 26 | if (!n##_func) { \\ 27 | dbg_printf("failed to load function " #n "\\n"); \\ 28 | exit(1); \\ 29 | } 30 | 31 | // Macro help creating unique nop functions 32 | #define NOP(x) \\ 33 | int nop##x() { \\ 34 | dbg_printf("==> nop%d called, %p\\n", ##x, _ReturnAddress());\\ 35 | return (DWORD)x; \\ 36 | } 37 | 38 | HMODULE dlllib; 39 | 40 | {typedef} 41 | 42 | """ 43 | 44 | FUZZME = """ 45 | void fuzz_me(char* filename){ 46 | 47 | {funcdef} 48 | 49 | {harness} 50 | 51 | } 52 | """ 53 | 54 | MAIN = """ 55 | int main(int argc, char ** argv) 56 | { 57 | if (argc < 2) { 58 | printf("Usage %s: \\n", argv[0]); 59 | printf(" e.g., harness.exe input\\n"); 60 | exit(1); 61 | } 62 | 63 | dlllib = LoadLibraryA("%s"); 64 | if (dlllib == NULL){ 65 | dbg_printf("failed to load library, gle = %d\\n", GetLastError()); 66 | exit(1); 67 | } 68 | 69 | char * filename = argv[1]; 70 | fuzz_me(filename); 71 | return 0; 72 | } 73 | """ 74 | 75 | """ 76 | LOAD_FUNC(dlllib, avformat_open_input); 77 | int ret_avformat_open_input = avformat_open_input_func(&ctx_org, filename, 0, &avformat_open_input_arg3); // zeros: if pointer one page ==> copy original page to that page ==> if error 78 | dbg_printf("avformat_open_input: ret = %d\n", ret_avformat_open_input); // @jinho: check crash / progress 79 | """ 80 | 81 | FUNC = """ 82 | {print_cid} 83 | LOAD_FUNC(dlllib, {funcname}); 84 | {ret_statement}{funcname}_func({arguments}); 85 | {dbg_printf} """ 86 | 87 | FUNC_WO = """ 88 | {print_cid} 89 | {ret_statement}{funcname}_func({arguments}); 90 | {dbg_printf} """ -------------------------------------------------------------------------------- /harnessgen/util.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import struct 3 | import string 4 | import signal 5 | 6 | printable = set(string.printable.encode()) 7 | 8 | 9 | def strings(data: bytes): 10 | found_str = b"" 11 | while True: 12 | if not data: 13 | break 14 | for char in data: 15 | if char in printable: 16 | found_str += bytes([char]) 17 | elif len(found_str) >= 4: 18 | yield found_str 19 | break 20 | break 21 | yield b'' 22 | 23 | 24 | def u32(b, off=0): 25 | return struct.unpack(" ").lower().startswith('y'): 41 | sys.exit(1) 42 | 43 | except KeyboardInterrupt: 44 | print("Ok ok, quitting") 45 | sys.exit(1) 46 | 47 | # restore the exit gracefully handler here 48 | signal.signal(signal.SIGINT, _exit_gracefully) 49 | return _exit_gracefully 50 | -------------------------------------------------------------------------------- /harnessgen/util/ida_func_type.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import typing 4 | 5 | from idautils import Segments, Functions 6 | from idc import get_segm_start, get_segm_end, get_func_name 7 | import idaapi 8 | 9 | 10 | def serialize(tif: idaapi.tinfo_t) -> typing.Union[dict, None]: 11 | fi = idaapi.func_type_data_t() 12 | if not tif.get_func_details(fi): 13 | return None 14 | 15 | args = [{"type": str(arg.type), "name": arg.name} for arg in fi] 16 | 17 | return ({ 18 | 'args': args, 19 | 'ret_type': str(fi.rettype), 20 | 'cc': '__stdcall' if fi.cc == idaapi.CM_CC_STDCALL else '__cdecl' 21 | }) 22 | 23 | 24 | def main(): 25 | idaapi.auto_wait() 26 | base = idaapi.get_imagebase() 27 | tif = idaapi.tinfo_t() 28 | 29 | f = open(os.environ.get("DESTPATH", "functype_"), 'w') 30 | 31 | for ea in Segments(): 32 | # only code segment 33 | if idaapi.segtype(ea) != idaapi.SEG_CODE: 34 | continue 35 | 36 | for fva in Functions(get_segm_start(ea), get_segm_end(ea)): 37 | func_name = get_func_name(fva) 38 | has_type = idaapi.get_tinfo(tif, fva) or idaapi.guess_tinfo(tif, fva) 39 | 40 | if not has_type: 41 | continue 42 | 43 | info = serialize(tif) 44 | if info is None: 45 | continue 46 | 47 | print(hex(fva-base)[:-1], "|", func_name, "|", tif, "|", len(info['args'])) 48 | f.write("0x%x|%s|%s\n" % (fva-base, func_name, json.dumps(info))) 49 | 50 | f.close() 51 | idaapi.qexit(0) 52 | 53 | 54 | main() 55 | -------------------------------------------------------------------------------- /injected-harness/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/injected-harness/README.md -------------------------------------------------------------------------------- /injected-harness/Source.def: -------------------------------------------------------------------------------- 1 | LIBRARY 2 | EXPORTS 3 | EnumerateProcessHandles 4 | MarkAllHandles -------------------------------------------------------------------------------- /injected-harness/exports.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../forkserver-proto.h" 4 | 5 | extern "C" { 6 | extern __declspec(dllexport) AFL_SETTINGS fuzzer_settings; 7 | extern __declspec(dllexport) volatile FORKSERVER_STATE forkserver_state; 8 | extern __declspec(noreturn dllexport) void call_target(); 9 | }; 10 | -------------------------------------------------------------------------------- /injected-harness/hookcallback.asm: -------------------------------------------------------------------------------- 1 | include ksamd64.inc 2 | 3 | EXTERNDEF __imp_RtlCaptureContext:QWORD 4 | extern harness_main:proc 5 | extern report_end:QWORD 6 | extern savedContext:QWORD 7 | 8 | .code 9 | 10 | FuzzingHarness PROC 11 | add rsp, 8 ; discard return address 12 | push qword ptr [report_end] ; new retaddr 13 | 14 | push rcx ; preserve rcx 15 | lea rcx, qword ptr [savedContext] 16 | call __imp_RtlCaptureContext 17 | 18 | pop [rcx+CxRcx] ; 0x80 = offset of rcx 19 | 20 | lea rax, [rsp] ; calculate original rsp 21 | mov [rcx+CxRsp], rax ; 0x98 = offset of rsp 22 | 23 | sub rsp, 1020h ; allocate a ton of space on the stack incl. shadow space 24 | 25 | jmp harness_main 26 | FuzzingHarness ENDP 27 | 28 | end 29 | -------------------------------------------------------------------------------- /injected-harness/injected-harness.cpp: -------------------------------------------------------------------------------- 1 | // injected-harness.cpp : Defines the exported functions for the DLL application. 2 | // 3 | 4 | #include "stdafx.h" 5 | #include "exports.h" 6 | 7 | __declspec(dllexport) AFL_SETTINGS fuzzer_settings; 8 | __declspec(dllexport) volatile FORKSERVER_STATE forkserver_state = FORKSERVER_NOT_READY; 9 | -------------------------------------------------------------------------------- /injected-harness/injected-harness.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | Header Files 32 | 33 | 34 | 35 | 36 | Source Files 37 | 38 | 39 | Source Files 40 | 41 | 42 | Source Files 43 | 44 | 45 | 46 | 47 | Source Files 48 | 49 | 50 | -------------------------------------------------------------------------------- /injected-harness/stdafx.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | -------------------------------------------------------------------------------- /injected-harness/stdafx.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "targetver.h" 4 | 5 | #include 6 | #include 7 | -------------------------------------------------------------------------------- /injected-harness/targetver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // Including SDKDDKVer.h defines the highest available Windows platform. 4 | 5 | // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and 6 | // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. 7 | 8 | #include 9 | -------------------------------------------------------------------------------- /intel-libipt/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013-2019, Intel Corporation 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | * Redistributions of source code must retain the above copyright notice, 6 | this list of conditions and the following disclaimer. 7 | * Redistributions in binary form must reproduce the above copyright notice, 8 | this list of conditions and the following disclaimer in the documentation 9 | and/or other materials provided with the distribution. 10 | * Neither the name of Intel Corporation nor the names of its contributors 11 | may be used to endorse or promote products derived from this software 12 | without specific prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 18 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /intel-libipt/README.txt: -------------------------------------------------------------------------------- 1 | This directory contains prebuilt binaries for Intel's libipt 2 | 3 | Built from these sources: https://github.com/intel/libipt 4 | -------------------------------------------------------------------------------- /intel-libipt/Win32/libipt.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/intel-libipt/Win32/libipt.dll -------------------------------------------------------------------------------- /intel-libipt/Win32/libipt.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/intel-libipt/Win32/libipt.lib -------------------------------------------------------------------------------- /intel-libipt/include/internal/posix/pt_section_posix.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_SECTION_POSIX_H 30 | #define PT_SECTION_POSIX_H 31 | 32 | #include 33 | #include 34 | 35 | struct pt_section; 36 | 37 | 38 | /* Fstat-based file status. */ 39 | struct pt_sec_posix_status { 40 | /* The file status. */ 41 | struct stat stat; 42 | }; 43 | 44 | /* MMAP-based section mapping information. */ 45 | struct pt_sec_posix_mapping { 46 | /* The mmap base address. */ 47 | uint8_t *base; 48 | 49 | /* The mapped memory size. */ 50 | uint64_t size; 51 | 52 | /* The begin and end of the mapped memory. */ 53 | const uint8_t *begin, *end; 54 | }; 55 | 56 | 57 | /* Map a section. 58 | * 59 | * On success, sets @section's mapping, unmap, and read pointers. 60 | * 61 | * Returns zero on success, a negative error code otherwise. 62 | * Returns -pte_internal if @section or @file are NULL. 63 | * Returns -pte_invalid if @section can't be mapped. 64 | */ 65 | extern int pt_sec_posix_map(struct pt_section *section, int fd); 66 | 67 | /* Unmap a section. 68 | * 69 | * On success, clears @section's mapping, unmap, and read pointers. 70 | * 71 | * Returns zero on success, a negative error code otherwise. 72 | * Returns -pte_internal if @section is NULL. 73 | * Returns -pte_internal if @section has not been mapped. 74 | */ 75 | extern int pt_sec_posix_unmap(struct pt_section *section); 76 | 77 | /* Read memory from an mmaped section. 78 | * 79 | * Reads at most @size bytes from @section at @offset into @buffer. 80 | * 81 | * Returns the number of bytes read on success, a negative error code otherwise. 82 | * Returns -pte_invalid if @section or @buffer are NULL. 83 | * Returns -pte_nomap if @offset is beyond the end of the section. 84 | */ 85 | extern int pt_sec_posix_read(const struct pt_section *section, uint8_t *buffer, 86 | uint16_t size, uint64_t offset); 87 | 88 | /* Compute the memory size of a section. 89 | * 90 | * On success, provides the amount of memory used for mapping @section in bytes 91 | * in @size. 92 | * 93 | * Returns zero on success, a negative error code otherwise. 94 | * Returns -pte_internal if @section or @size is NULL. 95 | * Returns -pte_internal if @section has not been mapped. 96 | */ 97 | extern int pt_sec_posix_memsize(const struct pt_section *section, 98 | uint64_t *size); 99 | 100 | #endif /* PT_SECTION_POSIX_H */ 101 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_asid.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_ASID_H 30 | #define PT_ASID_H 31 | 32 | #include 33 | 34 | struct pt_asid; 35 | 36 | 37 | /* Read an asid provided by our user. 38 | * 39 | * Translate a user-provided asid in @user into @asid. This uses default values 40 | * for fields that are not provided by the user and for all fields, if @user is 41 | * NULL. 42 | * 43 | * Fields set in @user that are not known (i.e. from a newer version of this 44 | * library) will be ignored. 45 | * 46 | * Returns zero on success, a negative error code otherwise. 47 | * Returns -pte_internal, if @asid is NULL. 48 | */ 49 | extern int pt_asid_from_user(struct pt_asid *asid, const struct pt_asid *user); 50 | 51 | /* Provide an asid to the user. 52 | * 53 | * Translate @asid into a potentially older or newer version in @user. 54 | * 55 | * Returns zero on success, a negative error code otherwise. 56 | * Returns -pte_internal, if @user or @asid is NULL. 57 | * Returns -pte_invalid, if @size is too small. 58 | */ 59 | extern int pt_asid_to_user(struct pt_asid *user, const struct pt_asid *asid, 60 | size_t size); 61 | 62 | /* Match two asids. 63 | * 64 | * Asids match if all fields provide either default values or are identical. 65 | * 66 | * Returns a positive number if @lhs matches @rhs. 67 | * Returns zero if @lhs does not match @rhs. 68 | * Returns a negative error code otherwise. 69 | * 70 | * Returns -pte_internal if @lhs or @rhs are NULL. 71 | */ 72 | extern int pt_asid_match(const struct pt_asid *lhs, const struct pt_asid *rhs); 73 | 74 | #endif /* PT_ASID_H */ 75 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #include "intel-pt.h" 30 | 31 | 32 | /* Read the configuration provided by a library user and zero-initialize 33 | * missing fields. 34 | * 35 | * We keep the user's size value if it is smaller than sizeof(*@config) to 36 | * allow decoders to detect missing configuration bits. 37 | * 38 | * Returns zero on success, a negative error code otherwise. 39 | * Returns -pte_internal if @config is NULL. 40 | * Returns -pte_invalid if @uconfig is NULL. 41 | * Returns -pte_bad_config if @config is too small to be useful. 42 | */ 43 | extern int pt_config_from_user(struct pt_config *config, 44 | const struct pt_config *uconfig); 45 | 46 | /* Get the configuration for the n'th address filter. 47 | * 48 | * Returns zero if @filter is NULL or @n is out of bounds. 49 | * 50 | * This corresponds to IA32_RTIT_CTL.ADDRn_CFG. 51 | */ 52 | extern uint32_t pt_filter_addr_cfg(const struct pt_conf_addr_filter *filter, 53 | uint8_t n); 54 | 55 | /* Get the lower bound (inclusive) of the n'th address filter. 56 | * 57 | * Returns zero if @filter is NULL or @n is out of bounds. 58 | * 59 | * This corresponds to IA32_RTIT_ADDRn_A. 60 | */ 61 | extern uint64_t pt_filter_addr_a(const struct pt_conf_addr_filter *filter, 62 | uint8_t n); 63 | 64 | /* Get the upper bound (inclusive) of the n'th address filter. 65 | * 66 | * Returns zero if @filter is NULL or @n is out of bounds. 67 | * 68 | * This corresponds to IA32_RTIT_ADDRn_B. 69 | */ 70 | extern uint64_t pt_filter_addr_b(const struct pt_conf_addr_filter *filter, 71 | uint8_t n); 72 | 73 | /* Check address filters. 74 | * 75 | * Checks @addr against @filter. 76 | * 77 | * Returns a positive number if @addr lies in a tracing-enabled region. 78 | * Returns zero if @addr lies in a tracing-disabled region. 79 | * Returns a negative pt_error_code otherwise. 80 | */ 81 | extern int pt_filter_addr_check(const struct pt_conf_addr_filter *filter, 82 | uint64_t addr); 83 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_cpu.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_CPU_H 30 | #define PT_CPU_H 31 | 32 | struct pt_cpu; 33 | 34 | /* Parses @s which should be of format family/model[/stepping] and 35 | * stores the value in @cpu on success. 36 | * The optional stepping defaults to 0 if omitted. 37 | * 38 | * Returns 0 on success. 39 | * Returns -pte_invalid if @cpu or @s is NULL. 40 | * Returns -pte_invalid if @s could not be parsed. 41 | */ 42 | extern int pt_cpu_parse(struct pt_cpu *cpu, const char *s); 43 | 44 | /* Get the cpu we're running on. 45 | * 46 | * Reads the family/model/stepping of the processor on which this function 47 | * is executed and stores the value in @cpu. 48 | * 49 | * Returns zero on success, a negative error code otherwise. 50 | * Returns -pte_invalid if @cpu is NULL. 51 | */ 52 | extern int pt_cpu_read(struct pt_cpu *cpu); 53 | 54 | #endif /* PT_CPU_H */ 55 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_cpuid.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_CPUID_H 30 | #define PT_CPUID_H 31 | 32 | #include 33 | 34 | /* Execute cpuid with @leaf set in the eax register. 35 | * The result is stored in @eax, @ebx, @ecx and @edx. 36 | */ 37 | extern void pt_cpuid(uint32_t leaf, uint32_t *eax, uint32_t *ebx, 38 | uint32_t *ecx, uint32_t *edx); 39 | 40 | #endif /* PT_CPUID_H */ 41 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_ild.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #if !defined(PT_ILD_H) 30 | #define PT_ILD_H 31 | 32 | #include "pt_insn.h" 33 | 34 | #include "intel-pt.h" 35 | 36 | 37 | typedef enum { 38 | PTI_MAP_0, /* 1-byte opcodes. may have modrm */ 39 | PTI_MAP_1, /* 2-byte opcodes (0x0f). may have modrm */ 40 | PTI_MAP_2, /* 3-byte opcodes (0x0f38). has modrm */ 41 | PTI_MAP_3, /* 3-byte opcodes (0x0f3a). has modrm */ 42 | PTI_MAP_AMD3DNOW, /* 3d-now opcodes (0x0f0f). has modrm */ 43 | PTI_MAP_INVALID 44 | } pti_map_enum_t; 45 | 46 | struct pt_ild { 47 | /* inputs */ 48 | uint8_t const *itext; 49 | uint8_t max_bytes; /*1..15 bytes */ 50 | enum pt_exec_mode mode; 51 | 52 | union { 53 | struct { 54 | uint32_t osz:1; 55 | uint32_t asz:1; 56 | uint32_t lock:1; 57 | uint32_t f3:1; 58 | uint32_t f2:1; 59 | uint32_t last_f2f3:2; /* 2 or 3 */ 60 | /* The vex bit is set for c4/c5 VEX and EVEX. */ 61 | uint32_t vex:1; 62 | /* The REX.R and REX.W bits in REX, VEX, or EVEX. */ 63 | uint32_t rex_r:1; 64 | uint32_t rex_w:1; 65 | } s; 66 | uint32_t i; 67 | } u; 68 | uint8_t imm1_bytes; /* # of bytes in 1st immediate */ 69 | uint8_t imm2_bytes; /* # of bytes in 2nd immediate */ 70 | uint8_t disp_bytes; /* # of displacement bytes */ 71 | uint8_t modrm_byte; 72 | /* 5b but valid values= 0,1,2,3 could be in bit union */ 73 | uint8_t map; 74 | uint8_t rex; /* 0b0100wrxb */ 75 | uint8_t nominal_opcode; 76 | uint8_t disp_pos; 77 | /* imm_pos can be derived from disp_pos + disp_bytes. */ 78 | }; 79 | 80 | static inline pti_map_enum_t pti_get_map(const struct pt_ild *ild) 81 | { 82 | return (pti_map_enum_t) ild->map; 83 | } 84 | 85 | static inline uint8_t pti_get_modrm_mod(const struct pt_ild *ild) 86 | { 87 | return ild->modrm_byte >> 6; 88 | } 89 | 90 | static inline uint8_t pti_get_modrm_reg(const struct pt_ild *ild) 91 | { 92 | return (ild->modrm_byte >> 3) & 7; 93 | } 94 | 95 | static inline uint8_t pti_get_modrm_rm(const struct pt_ild *ild) 96 | { 97 | return ild->modrm_byte & 7; 98 | } 99 | 100 | /* all decoding is multithread safe. */ 101 | 102 | /* Decode one instruction. 103 | * 104 | * Input: 105 | * 106 | * @insn->ip: the virtual address of the instruction 107 | * @insn->raw: the memory at that virtual address 108 | * @insn->size: the maximal size of the instruction 109 | * @insn->mode: the execution mode 110 | * 111 | * Output: 112 | * 113 | * @insn->size: the actual size of the instruction 114 | * @insn->iclass: a coarse classification 115 | * 116 | * @iext->iclass: a finer grain classification 117 | * @iext->variant: instruction class dependent information 118 | * 119 | * Returns zero on success, a negative error code otherwise. 120 | */ 121 | extern int pt_ild_decode(struct pt_insn *insn, struct pt_insn_ext *iext); 122 | 123 | #endif /* PT_ILD_H */ 124 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_last_ip.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_LAST_IP_H 30 | #define PT_LAST_IP_H 31 | 32 | #include 33 | 34 | struct pt_packet_ip; 35 | struct pt_config; 36 | 37 | 38 | /* Keeping track of the last-ip in Intel PT packets. */ 39 | struct pt_last_ip { 40 | /* The last IP. */ 41 | uint64_t ip; 42 | 43 | /* Flags governing the handling of IP updates and queries: 44 | * 45 | * - we have seen an IP update. 46 | */ 47 | uint32_t have_ip:1; 48 | /* - the IP has been suppressed in the last update. */ 49 | uint32_t suppressed:1; 50 | }; 51 | 52 | 53 | /* Initialize (or reset) the last-ip. */ 54 | extern void pt_last_ip_init(struct pt_last_ip *last_ip); 55 | 56 | /* Query the last-ip. 57 | * 58 | * If @ip is not NULL, provides the last-ip in @ip on success. 59 | * 60 | * Returns zero on success. 61 | * Returns -pte_internal if @last_ip is NULL. 62 | * Returns -pte_noip if there is no last-ip. 63 | * Returns -pte_ip_suppressed if the last-ip has been suppressed. 64 | */ 65 | extern int pt_last_ip_query(uint64_t *ip, const struct pt_last_ip *last_ip); 66 | 67 | /* Update last-ip. 68 | * 69 | * Updates @last_ip based on @packet and, if non-null, @config. 70 | * 71 | * Returns zero on success. 72 | * Returns -pte_internal if @last_ip or @packet is NULL. 73 | * Returns -pte_bad_packet if @packet appears to be corrupted. 74 | */ 75 | extern int pt_last_ip_update_ip(struct pt_last_ip *last_ip, 76 | const struct pt_packet_ip *packet, 77 | const struct pt_config *config); 78 | 79 | #endif /* PT_LAST_IP_H */ 80 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_msec_cache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_MSEC_CACHE_H 30 | #define PT_MSEC_CACHE_H 31 | 32 | #include "pt_mapped_section.h" 33 | 34 | #include "intel-pt.h" 35 | 36 | 37 | /* A single-entry mapped section cache. 38 | * 39 | * The cached section is implicitly mapped and unmapped. The cache is not 40 | * thread-safe. 41 | */ 42 | struct pt_msec_cache { 43 | /* The cached section. 44 | * 45 | * The cache is valid if and only if @msec.section is not NULL. 46 | * 47 | * It needs to be unmapped and put. Use pt_blk_scache_invalidate() to 48 | * release the cached section and to invalidate the cache. 49 | */ 50 | struct pt_mapped_section msec; 51 | 52 | /* The section identifier. */ 53 | int isid; 54 | }; 55 | 56 | /* Initialize the cache. */ 57 | extern int pt_msec_cache_init(struct pt_msec_cache *cache); 58 | 59 | /* Finalize the cache. */ 60 | extern void pt_msec_cache_fini(struct pt_msec_cache *cache); 61 | 62 | /* Invalidate the cache. */ 63 | extern int pt_msec_cache_invalidate(struct pt_msec_cache *cache); 64 | 65 | /* Read the cached section. 66 | * 67 | * If @cache is not empty and @image would find it when looking up @vaddr in 68 | * @*pmsec->asid, provide a pointer to the cached section in @pmsec and return 69 | * its image section identifier. 70 | * 71 | * The provided pointer remains valid until @cache is invalidated. 72 | * 73 | * Returns @*pmsec's isid on success, a negative pt_error_code otherwise. 74 | */ 75 | extern int pt_msec_cache_read(struct pt_msec_cache *cache, 76 | const struct pt_mapped_section **pmsec, 77 | struct pt_image *image, uint64_t vaddr); 78 | 79 | /* Fill the cache. 80 | * 81 | * Look up @vaddr in @asid in @image and cache as well as provide the found 82 | * section in @pmsec and return its image section identifier. 83 | * 84 | * Invalidates @cache. 85 | * 86 | * The provided pointer remains valid until @cache is invalidated. 87 | * 88 | * Returns @*pmsec's isid on success, a negative pt_error_code otherwise. 89 | */ 90 | extern int pt_msec_cache_fill(struct pt_msec_cache *cache, 91 | const struct pt_mapped_section **pmsec, 92 | struct pt_image *image, 93 | const struct pt_asid *asid, uint64_t vaddr); 94 | 95 | #endif /* PT_MSEC_CACHE_H */ 96 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_packet_decoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_PACKET_DECODER_H 30 | #define PT_PACKET_DECODER_H 31 | 32 | #include "intel-pt.h" 33 | 34 | 35 | /* An Intel PT packet decoder. */ 36 | struct pt_packet_decoder { 37 | /* The decoder configuration. */ 38 | struct pt_config config; 39 | 40 | /* The current position in the trace buffer. */ 41 | const uint8_t *pos; 42 | 43 | /* The position of the last PSB packet. */ 44 | const uint8_t *sync; 45 | }; 46 | 47 | 48 | /* Initialize the packet decoder. 49 | * 50 | * Returns zero on success, a negative error code otherwise. 51 | */ 52 | extern int pt_pkt_decoder_init(struct pt_packet_decoder *, 53 | const struct pt_config *); 54 | 55 | /* Finalize the packet decoder. */ 56 | extern void pt_pkt_decoder_fini(struct pt_packet_decoder *); 57 | 58 | 59 | /* Decoder functions for the packet decoder. */ 60 | extern int pt_pkt_decode_unknown(struct pt_packet_decoder *, 61 | struct pt_packet *); 62 | extern int pt_pkt_decode_pad(struct pt_packet_decoder *, struct pt_packet *); 63 | extern int pt_pkt_decode_psb(struct pt_packet_decoder *, struct pt_packet *); 64 | extern int pt_pkt_decode_tip(struct pt_packet_decoder *, struct pt_packet *); 65 | extern int pt_pkt_decode_tnt_8(struct pt_packet_decoder *, struct pt_packet *); 66 | extern int pt_pkt_decode_tnt_64(struct pt_packet_decoder *, 67 | struct pt_packet *); 68 | extern int pt_pkt_decode_tip_pge(struct pt_packet_decoder *, 69 | struct pt_packet *); 70 | extern int pt_pkt_decode_tip_pgd(struct pt_packet_decoder *, 71 | struct pt_packet *); 72 | extern int pt_pkt_decode_fup(struct pt_packet_decoder *, struct pt_packet *); 73 | extern int pt_pkt_decode_pip(struct pt_packet_decoder *, struct pt_packet *); 74 | extern int pt_pkt_decode_ovf(struct pt_packet_decoder *, struct pt_packet *); 75 | extern int pt_pkt_decode_mode(struct pt_packet_decoder *, struct pt_packet *); 76 | extern int pt_pkt_decode_psbend(struct pt_packet_decoder *, 77 | struct pt_packet *); 78 | extern int pt_pkt_decode_tsc(struct pt_packet_decoder *, struct pt_packet *); 79 | extern int pt_pkt_decode_cbr(struct pt_packet_decoder *, struct pt_packet *); 80 | extern int pt_pkt_decode_tma(struct pt_packet_decoder *, struct pt_packet *); 81 | extern int pt_pkt_decode_mtc(struct pt_packet_decoder *, struct pt_packet *); 82 | extern int pt_pkt_decode_cyc(struct pt_packet_decoder *, struct pt_packet *); 83 | extern int pt_pkt_decode_stop(struct pt_packet_decoder *, struct pt_packet *); 84 | extern int pt_pkt_decode_vmcs(struct pt_packet_decoder *, struct pt_packet *); 85 | extern int pt_pkt_decode_mnt(struct pt_packet_decoder *, struct pt_packet *); 86 | extern int pt_pkt_decode_exstop(struct pt_packet_decoder *, struct pt_packet *); 87 | extern int pt_pkt_decode_mwait(struct pt_packet_decoder *, struct pt_packet *); 88 | extern int pt_pkt_decode_pwre(struct pt_packet_decoder *, struct pt_packet *); 89 | extern int pt_pkt_decode_pwrx(struct pt_packet_decoder *, struct pt_packet *); 90 | extern int pt_pkt_decode_ptw(struct pt_packet_decoder *, struct pt_packet *); 91 | 92 | #endif /* PT_PACKET_DECODER_H */ 93 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_retstack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_RETSTACK_H 30 | #define PT_RETSTACK_H 31 | 32 | #include 33 | 34 | 35 | /* The size of the call/return stack in number of entries. */ 36 | enum { 37 | pt_retstack_size = 64 38 | }; 39 | 40 | /* A stack of return addresses used for return compression. */ 41 | struct pt_retstack { 42 | /* The stack of return addresses. 43 | * 44 | * We use one additional entry in order to distinguish a full from 45 | * an empty stack. 46 | */ 47 | uint64_t stack[pt_retstack_size + 1]; 48 | 49 | /* The top of the stack. */ 50 | uint8_t top; 51 | 52 | /* The bottom of the stack. */ 53 | uint8_t bottom; 54 | }; 55 | 56 | /* Initialize (or reset) a call/return stack. */ 57 | extern void pt_retstack_init(struct pt_retstack *); 58 | 59 | /* Test a call/return stack for emptiness. 60 | * 61 | * Returns zero if @retstack contains at least one element. 62 | * Returns a positive integer if @retstack is empty. 63 | * Returns -pte_invalid if @retstack is NULL. 64 | */ 65 | extern int pt_retstack_is_empty(const struct pt_retstack *retstack); 66 | 67 | /* Pop and return the topmost IP. 68 | * 69 | * If @ip is not NULL, provides the topmost return address on success. 70 | * If @retstack is not empty, pops the topmost return address on success. 71 | * 72 | * Returns zero on success. 73 | * Returns -pte_invalid if @retstack is NULL. 74 | * Returns -pte_noip if @retstack is empty. 75 | */ 76 | extern int pt_retstack_pop(struct pt_retstack *retstack, uint64_t *ip); 77 | 78 | /* Push a return address onto the stack. 79 | * 80 | * Pushes @ip onto @retstack. 81 | * If @retstack is full, drops the oldest return address. 82 | * 83 | * Returns zero on success. 84 | */ 85 | extern int pt_retstack_push(struct pt_retstack *retstack, uint64_t ip); 86 | 87 | #endif /* PT_RETSTACK_H */ 88 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_section_file.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_SECTION_FILE_H 30 | #define PT_SECTION_FILE_H 31 | 32 | #include 33 | #include 34 | 35 | #if defined(FEATURE_THREADS) 36 | # include 37 | #endif /* defined(FEATURE_THREADS) */ 38 | 39 | struct pt_section; 40 | 41 | 42 | /* File-based section mapping information. */ 43 | struct pt_sec_file_mapping { 44 | /* The FILE pointer. */ 45 | FILE *file; 46 | 47 | /* The begin and end of the section as offset into @file. */ 48 | long begin, end; 49 | 50 | #if defined(FEATURE_THREADS) 51 | /* A lock protecting read access to this file. 52 | * 53 | * Since we need to first set the file position indication before 54 | * we can read, there's a race on the file position. 55 | */ 56 | mtx_t lock; 57 | #endif /* defined(FEATURE_THREADS) */ 58 | }; 59 | 60 | 61 | /* Map a section based on file operations. 62 | * 63 | * The caller has already opened the file for reading. 64 | * 65 | * On success, sets @section's mapping, unmap, and read pointers. 66 | * 67 | * Returns zero on success, a negative error code otherwise. 68 | * Returns -pte_internal if @section or @file are NULL. 69 | * Returns -pte_invalid if @section can't be mapped. 70 | */ 71 | extern int pt_sec_file_map(struct pt_section *section, FILE *file); 72 | 73 | /* Unmap a section based on file operations. 74 | * 75 | * On success, clears @section's mapping, unmap, and read pointers. 76 | * 77 | * Returns zero on success, a negative error code otherwise. 78 | * Returns -pte_internal if @section is NULL. 79 | * Returns -pte_internal if @section has not been mapped. 80 | */ 81 | extern int pt_sec_file_unmap(struct pt_section *section); 82 | 83 | /* Read memory from a file based section. 84 | * 85 | * Reads at most @size bytes from @section at @offset into @buffer. 86 | * 87 | * Returns the number of bytes read on success, a negative error code otherwise. 88 | * Returns -pte_invalid if @section or @buffer are NULL. 89 | * Returns -pte_nomap if @offset is beyond the end of the section. 90 | */ 91 | extern int pt_sec_file_read(const struct pt_section *section, uint8_t *buffer, 92 | uint16_t size, uint64_t offset); 93 | 94 | /* Compute the memory size of a section based on file operations. 95 | * 96 | * On success, provides the amount of memory used for mapping @section in bytes 97 | * in @size. 98 | * 99 | * Returns zero on success, a negative error code otherwise. 100 | * Returns -pte_internal if @section or @size is NULL. 101 | * Returns -pte_internal if @section has not been mapped. 102 | */ 103 | extern int pt_sec_file_memsize(const struct pt_section *section, 104 | uint64_t *size); 105 | 106 | #endif /* PT_SECTION_FILE_H */ 107 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_sync.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_SYNC_H 30 | #define PT_SYNC_H 31 | 32 | #include 33 | 34 | struct pt_config; 35 | 36 | 37 | /* Synchronize onto the trace stream. 38 | * 39 | * Search for the next synchronization point in forward or backward direction 40 | * starting at @pos using the trace configuration @config. 41 | * 42 | * On success, stores a pointer to the next synchronization point in @sync. 43 | * 44 | * Returns zero on success, a negative error code otherwise. 45 | * 46 | * Returns -pte_internal if @sync, @pos, or @config is NULL. 47 | * Returns -pte_nosync if @pos lies outside of @config's buffer. 48 | * Returns -pte_eos if no further synchronization point is found. 49 | */ 50 | extern int pt_sync_forward(const uint8_t **sync, const uint8_t *pos, 51 | const struct pt_config *config); 52 | extern int pt_sync_backward(const uint8_t **sync, const uint8_t *pos, 53 | const struct pt_config *config); 54 | 55 | /* Manually synchronize onto the trace stream. 56 | * 57 | * Validate that @pos is within the bounds of @config's trace buffer and that 58 | * there is a synchronization point at @pos. 59 | * 60 | * On success, stores @pos in @sync. 61 | * 62 | * Returns zero on success, a negative error code otherwise. 63 | * 64 | * Returns -pte_eos if @pos is outside of @config's trace buffer. 65 | * Returns -pte_internal if @sync, @pos, or @config is NULL. 66 | * Returns -pte_bad_packet if there is no PSB at @pos. 67 | */ 68 | extern int pt_sync_set(const uint8_t **sync, const uint8_t *pos, 69 | const struct pt_config *config); 70 | 71 | #endif /* PT_SYNC_H */ 72 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pt_tnt_cache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_TNT_CACHE_H 30 | #define PT_TNT_CACHE_H 31 | 32 | #include 33 | 34 | struct pt_packet_tnt; 35 | struct pt_config; 36 | 37 | 38 | /* Keeping track of tnt indicators. */ 39 | struct pt_tnt_cache { 40 | /* The last tnt. */ 41 | uint64_t tnt; 42 | 43 | /* The index into the above tnt. 44 | * 45 | * (tnt & index) gives the current tnt entry. 46 | * (index >>= 1) moves the index to the next tnt entry. 47 | * (index == 0) means that the current tnt is empty. 48 | */ 49 | uint64_t index; 50 | }; 51 | 52 | 53 | /* Initialize (or reset) the tnt cache. */ 54 | extern void pt_tnt_cache_init(struct pt_tnt_cache *cache); 55 | 56 | /* Check if the tnt cache is empty. 57 | * 58 | * Returns 0 if the tnt cache is not empty. 59 | * Returns > 0 if the tnt cache is empty. 60 | * Returns -pte_invalid if @cache is NULL. 61 | */ 62 | extern int pt_tnt_cache_is_empty(const struct pt_tnt_cache *cache); 63 | 64 | /* Query the next tnt indicator. 65 | * 66 | * This consumes the returned tnt indicator in the cache. 67 | * 68 | * Returns 0 if the next branch is not taken. 69 | * Returns > 0 if the next branch is taken. 70 | * Returns -pte_invalid if @cache is NULL. 71 | * Returns -pte_bad_query if there is no tnt cached. 72 | */ 73 | extern int pt_tnt_cache_query(struct pt_tnt_cache *cache); 74 | 75 | /* Update the tnt cache based on Intel PT packets. 76 | * 77 | * Updates @cache based on @packet and, if non-null, @config. 78 | * 79 | * Returns zero on success. 80 | * Returns -pte_invalid if @cache or @packet is NULL. 81 | * Returns -pte_bad_packet if @packet appears to be corrupted. 82 | * Returns -pte_bad_context if the tnt cache is not empty. 83 | */ 84 | extern int pt_tnt_cache_update_tnt(struct pt_tnt_cache *cache, 85 | const struct pt_packet_tnt *packet, 86 | const struct pt_config *config); 87 | 88 | #endif /* PT_TNT_CACHE_H */ 89 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pti-disp-defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #if !defined(PTI_DISP_DEFS_H) 30 | #define PTI_DISP_DEFS_H 31 | 32 | #define PTI_DISP_NONE 0 33 | #define PTI_PRESERVE_DEFAULT 1 34 | #define PTI_BRDISP8 2 35 | #define PTI_DISP_BUCKET_0_l1 3 36 | #define PTI_MEMDISPv_DISP_WIDTH_ASZ_NONTERM_EASZ_l2 4 37 | #define PTI_BRDISPz_BRDISP_WIDTH_OSZ_NONTERM_EOSZ_l2 5 38 | #define PTI_RESOLVE_BYREG_DISP_map0x0_op0xc7_l1 6 39 | #endif 40 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pti-imm-defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #if !defined(PTI_IMM_DEFS_H) 30 | #define PTI_IMM_DEFS_H 31 | 32 | #define PTI_IMM_NONE 0 33 | #define PTI_0_IMM_WIDTH_CONST_l2 1 34 | #define PTI_UIMM8_IMM_WIDTH_CONST_l2 2 35 | #define PTI_SIMM8_IMM_WIDTH_CONST_l2 3 36 | #define PTI_SIMMz_IMM_WIDTH_OSZ_NONTERM_EOSZ_l2 4 37 | #define PTI_UIMMv_IMM_WIDTH_OSZ_NONTERM_EOSZ_l2 5 38 | #define PTI_UIMM16_IMM_WIDTH_CONST_l2 6 39 | #define PTI_RESOLVE_BYREG_IMM_WIDTH_map0x0_op0xf7_l1 7 40 | #define PTI_RESOLVE_BYREG_IMM_WIDTH_map0x0_op0xc7_l1 8 41 | #define PTI_SIMMz_IMM_WIDTH_OSZ_NONTERM_DF64_EOSZ_l2 9 42 | #define PTI_RESOLVE_BYREG_IMM_WIDTH_map0x0_op0xf6_l1 10 43 | #define PTI_IMM_hasimm_map0x0_op0xc8_l1 11 44 | #define PTI_IMM_hasimm_map0x0F_op0x78_l1 12 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/pti-modrm-defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #if !defined(PTI_MODRM_DEFS_H) 30 | #define PTI_MODRM_DEFS_H 31 | 32 | 33 | #define PTI_MODRM_FALSE 0 34 | #define PTI_MODRM_TRUE 1 35 | #define PTI_MODRM_IGNORE_MOD 2 36 | #define PTI_MODRM_UNDEF 3 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /intel-libipt/include/internal/windows/pt_section_windows.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015-2019, Intel Corporation 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright notice, 10 | * this list of conditions and the following disclaimer in the documentation 11 | * and/or other materials provided with the distribution. 12 | * * Neither the name of Intel Corporation nor the names of its contributors 13 | * may be used to endorse or promote products derived from this software 14 | * without specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #ifndef PT_SECTION_WINDOWS_H 30 | #define PT_SECTION_WINDOWS_H 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | struct pt_section; 37 | 38 | 39 | /* Fstat-based file status. */ 40 | struct pt_sec_windows_status { 41 | /* The file status. */ 42 | struct _stat stat; 43 | }; 44 | 45 | /* FileView-based section mapping information. */ 46 | struct pt_sec_windows_mapping { 47 | /* The file descriptor. */ 48 | int fd; 49 | 50 | /* The FileMapping handle. */ 51 | HANDLE mh; 52 | 53 | /* The mmap base address. */ 54 | uint8_t *base; 55 | 56 | /* The begin and end of the mapped memory. */ 57 | const uint8_t *begin, *end; 58 | }; 59 | 60 | 61 | /* Map a section. 62 | * 63 | * The caller has already opened the file for reading. 64 | * 65 | * On success, sets @section's mapping, unmap, and read pointers. 66 | * 67 | * Returns zero on success, a negative error code otherwise. 68 | * Returns -pte_internal if @section is NULL. 69 | * Returns -pte_invalid if @section can't be mapped. 70 | */ 71 | extern int pt_sec_windows_map(struct pt_section *section, int fd); 72 | 73 | /* Unmap a section. 74 | * 75 | * On success, clears @section's mapping, unmap, and read pointers. 76 | * 77 | * This function should not be called directly; call @section->unmap() instead. 78 | * 79 | * Returns zero on success, a negative error code otherwise. 80 | * Returns -pte_internal if @section is NULL. 81 | * Returns -pte_internal if @section has not been mapped. 82 | */ 83 | extern int pt_sec_windows_unmap(struct pt_section *section); 84 | 85 | /* Read memory from an mmaped section. 86 | * 87 | * Reads at most @size bytes from @section at @offset into @buffer. 88 | * 89 | * This function should not be called directly; call @section->read() instead. 90 | * 91 | * Returns the number of bytes read on success, a negative error code otherwise. 92 | * Returns -pte_invalid if @section or @buffer are NULL. 93 | * Returns -pte_nomap if @offset is beyond the end of the section. 94 | */ 95 | extern int pt_sec_windows_read(const struct pt_section *section, 96 | uint8_t *buffer, uint16_t size, 97 | uint64_t offset); 98 | 99 | /* Compute the memory size of a section. 100 | * 101 | * On success, provides the amount of memory used for mapping @section in bytes 102 | * in @size. 103 | * 104 | * Returns zero on success, a negative error code otherwise. 105 | * Returns -pte_internal if @section or @size is NULL. 106 | * Returns -pte_internal if @section has not been mapped. 107 | */ 108 | extern int pt_sec_windows_memsize(const struct pt_section *section, 109 | uint64_t *size); 110 | 111 | #endif /* PT_SECTION_WINDOWS_H */ 112 | -------------------------------------------------------------------------------- /intel-libipt/libipt.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/intel-libipt/libipt.dll -------------------------------------------------------------------------------- /intel-libipt/libipt.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/intel-libipt/libipt.lib -------------------------------------------------------------------------------- /ipttool/LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2018, Alex Ionescu 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /ipttool/README.txt: -------------------------------------------------------------------------------- 1 | This directory contains code forked from winipt. 2 | 3 | Upstream subtree: https://github.com/ionescu007/winipt/tree/master/ipttool 4 | -------------------------------------------------------------------------------- /ipttool/include/ipttool.h: -------------------------------------------------------------------------------- 1 | BOOL EnableAndValidateIptServices(VOID); 2 | BOOL ConfigureBufferSize(_In_ DWORD dwSize, _Inout_ PIPT_OPTIONS pOptions); 3 | BOOL ConfigureTraceFlags(_In_ DWORD dwFlags, _Inout_ PIPT_OPTIONS pOptions); 4 | PIPT_TRACE_DATA GetIptTrace(HANDLE hProcess); 5 | -------------------------------------------------------------------------------- /libipt/LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2018, Alex Ionescu 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /libipt/README.txt: -------------------------------------------------------------------------------- 1 | This directory contains code forked from winipt. 2 | 3 | Upstream subtree: https://github.com/ionescu007/winipt/tree/master/libipt 4 | -------------------------------------------------------------------------------- /libipt/include/ipt.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning(disable:4214) 3 | #pragma warning(disable:4201) 4 | 5 | // 6 | // Requests that can be sent with IOCTL_IPT_REQUEST or IOCTL_IPT_READ_TRACE 7 | // 8 | typedef enum _IPT_INPUT_TYPE 9 | { 10 | IptGetTraceVersion, 11 | IptGetProcessTraceSize, 12 | IptGetProcessTrace, // Use IOCTL_IPT_READ_TRACE 13 | IptStartCoreTracing, 14 | IptRegisterExtendedImageForTracing, 15 | IptStartProcessTrace, 16 | IptStopProcessTrace, 17 | IptPauseThreadTrace, 18 | IptResumeThreadTrace, 19 | IptQueryProcessTrace, 20 | IptQueryCoreTrace 21 | } IPT_INPUT_TYPE, *PIPT_INPUT_TYPE; 22 | 23 | // 24 | // Header on top of any IOCTL Input Request 25 | // 26 | typedef struct _IPT_BUFFER_VERSION 27 | { 28 | ULONG BufferMajorVersion; 29 | ULONG BufferMinorVersion; 30 | } IPT_BUFFER_VERSION, *PIPT_BUFFER_VERSION; 31 | 32 | // 33 | // IOCTL Input Request Buffer 34 | // 35 | typedef struct _IPT_INPUT_BUFFER 36 | { 37 | IPT_BUFFER_VERSION; 38 | IPT_INPUT_TYPE InputType; 39 | union 40 | { 41 | struct 42 | { 43 | USHORT TraceVersion; 44 | ULONG64 ProcessHandle; 45 | } GetProcessIptTraceSize; 46 | struct 47 | { 48 | USHORT TraceVersion; 49 | ULONG64 ProcessHandle; 50 | } GetProcessIptTrace; 51 | struct 52 | { 53 | IPT_OPTIONS Options; 54 | ULONG NumberOfTries; 55 | ULONG TraceDurationInSeconds; 56 | } StartCoreIptTracing; 57 | struct 58 | { 59 | IPT_OPTIONS Options; 60 | ULONG NumberOfTries; 61 | ULONG TraceDurationInSeconds; 62 | USHORT ImagePathLength; 63 | USHORT FilteredPathLength; 64 | WCHAR ImageName[ANYSIZE_ARRAY]; 65 | } RegisterExtendedImageForIptTracing; 66 | struct 67 | { 68 | ULONG64 ProcessHandle; 69 | IPT_OPTIONS Options; 70 | } StartProcessIptTrace; 71 | struct 72 | { 73 | ULONG64 ProcessHandle; 74 | } StopProcessIptTrace; 75 | struct 76 | { 77 | ULONG64 ThreadHandle; 78 | } PauseThreadIptTrace; 79 | struct 80 | { 81 | ULONG64 ThreadHandle; 82 | } ResumeThreadIptTrace; 83 | struct 84 | { 85 | ULONG64 ProcessHandle; 86 | } QueryProcessIptTrace; 87 | }; 88 | } IPT_INPUT_BUFFER, *PIPT_INPUT_BUFFER; 89 | C_ASSERT(sizeof(IPT_INPUT_BUFFER) == 0x28); 90 | 91 | // 92 | // IOCTL Output Request Buffer 93 | // 94 | typedef struct _IPT_OUTPUT_BUFFER 95 | { 96 | union 97 | { 98 | struct 99 | { 100 | IPT_BUFFER_VERSION; 101 | } GetBufferMajorVersion; 102 | struct 103 | { 104 | USHORT TraceVersion; 105 | } GetTraceVersion; 106 | struct 107 | { 108 | USHORT TraceVersion; 109 | ULONGLONG TraceSize; 110 | } GetTraceSize; 111 | struct 112 | { 113 | IPT_TRACE_DATA; 114 | } GetTrace; 115 | struct 116 | { 117 | BOOLEAN OldState; 118 | } PauseTrace; 119 | struct 120 | { 121 | BOOLEAN OldState; 122 | } ResumeTrace; 123 | struct 124 | { 125 | IPT_OPTIONS Options; 126 | } QueryProcessTrace; 127 | struct 128 | { 129 | IPT_OPTIONS Options; 130 | } QueryCoreTrace; 131 | }; 132 | } IPT_OUTPUT_BUFFER, *PIPT_OUTPUT_BUFFER; 133 | C_ASSERT(sizeof(IPT_OUTPUT_BUFFER) == 0x10); 134 | 135 | // 136 | // IOCTLs that the IPT Driver Handles 137 | // 138 | #define IOCTL_IPT_REQUEST \ 139 | CTL_CODE(FILE_DEVICE_UNKNOWN, 1, METHOD_BUFFERED, FILE_ANY_ACCESS) 140 | #define IOCTL_IPT_READ_TRACE \ 141 | CTL_CODE(FILE_DEVICE_UNKNOWN, 1, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) 142 | 143 | -------------------------------------------------------------------------------- /libipt/include/libiptnt.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning(disable:4214) 3 | #pragma warning(disable:4201) 4 | 5 | // 6 | // Version number of IPT Service IOCTL buffers 7 | // 8 | #define IPT_BUFFER_MAJOR_VERSION_V1 1 9 | #define IPT_BUFFER_MAJOR_VERSION_CURRENT IPT_BUFFER_MAJOR_VERSION_V1 10 | #define IPT_BUFFER_MINOR_VERSION_V0 0 11 | #define IPT_BUFFER_MINOR_VERSION_CURRENT IPT_BUFFER_MINOR_VERSION_V0 12 | 13 | // 14 | // Version numbers of trace formats 15 | // 16 | #define IPT_TRACE_VERSION_V1 1 17 | #define IPT_TRACE_VERSION_CURRENT IPT_TRACE_VERSION_V1 18 | 19 | // 20 | // See OnProcessCreate 21 | // 22 | typedef enum _IPT_MATCH_SETTINGS 23 | { 24 | IptMatchByAnyApp, 25 | IptMatchByImageFileName, 26 | IptMatchByAnyPackage, 27 | IptMatchByPackageName, 28 | } IPT_MATCH_SETTINGS; 29 | 30 | // 31 | // See GetIptOptionForTracingThreads vs GetIptOptionForTracingCores 32 | // 33 | typedef enum _IPT_MODE_SETTINGS 34 | { 35 | // 36 | // Set through IOCTL (IptStartCoreIptTracing) 37 | // 38 | IptCtlUserModeOnly, // Sets BranchEn[2000], ToPA[100], User[8] 39 | IptCtlKernelModeOnly, // Sets BranchEn[2000], ToPA[100], OS[4] 40 | IptCtlUserAndKernelMode, // Sets BranchEn[2000], ToPA[100], User[8], OS[4] 41 | 42 | // 43 | // Set through registry (IptOptions) 44 | // 45 | IptRegUserModeOnly, // Sets BranchEn[2000], ToPA[100], User[8] 46 | IptRegKernelModeOnly, // Sets BranchEn[2000], ToPA[100], OS[4] 47 | IptRegUserAndKernelMode, // Sets BranchEn[2000], ToPA[100], User[8], OS[4] 48 | } IPT_MODE_SETTINGS; 49 | 50 | typedef enum IPT_TIMING_SETTINGS 51 | { 52 | IptNoTimingPackets, // No additional IA32_RTIT_CTL bits enabled 53 | IptEnableMtcPackets, // Sets MTCEn[400], TSCEn[200]. Requires CPUID.(EAX=014H,ECX=0H):EBX[3]= 1 54 | IptEnableCycPackets // Sets MTCEn[400], TSCEn[200], CYCEn[2]. Requires CPUID.(EAX=014H,ECX=0H):EBX[1]= 1 55 | } IPT_TIMING_SETTINGS; 56 | 57 | // 58 | // See CheckIptOption 59 | // 60 | typedef union _IPT_OPTIONS 61 | { 62 | struct 63 | { 64 | ULONGLONG OptionVersion : 4; // Must be set to 1 65 | ULONGLONG TimingSettings : 4; // IPT_TIMING_SETTINGS 66 | 67 | ULONGLONG MtcFrequency : 4; // Bits 14:17 in IA32_RTIT_CTL 68 | ULONGLONG CycThreshold : 4; // Bits 19:22 in IA32_RTIT_CTL 69 | 70 | ULONGLONG TopaPagesPow2 : 4; // Size of buffer in ToPA, as 4KB powers of 2 (4KB->128MB). Multiple buffers will be used if CPUID.(EAX=014H,ECX=0H):ECX[1]= 1 71 | ULONGLONG MatchSettings: 3; // IPT_MATCH_SETTINGS 72 | ULONGLONG Inherit : 1; // Children will be automatically added to the trace 73 | 74 | ULONGLONG ModeSettings : 4; // IPT_MODE_SETTINGS 75 | ULONGLONG Reserved : 36; 76 | }; 77 | ULONGLONG AsULonglong; 78 | } IPT_OPTIONS, *PIPT_OPTIONS; 79 | C_ASSERT(sizeof(IPT_OPTIONS) == 8); 80 | 81 | typedef struct _IPT_TRACE_DATA 82 | { 83 | USHORT TraceVersion; 84 | USHORT ValidTrace; 85 | ULONG TraceSize; 86 | UCHAR TraceData[ANYSIZE_ARRAY]; 87 | } IPT_TRACE_DATA, *PIPT_TRACE_DATA; 88 | 89 | typedef struct _IPT_TRACE_HEADER 90 | { 91 | ULONG64 ThreadId; 92 | IPT_TIMING_SETTINGS TimingSettings; 93 | ULONG MtcFrequency; 94 | ULONG FrequencyToTscRatio; 95 | ULONG RingBufferOffset; 96 | ULONG TraceSize; 97 | UCHAR Trace[ANYSIZE_ARRAY]; 98 | } IPT_TRACE_HEADER, *PIPT_TRACE_HEADER; 99 | 100 | NTSTATUS 101 | GetIptBufferVersion ( 102 | _Out_ PULONG BufferMajorVersion 103 | ); 104 | 105 | NTSTATUS 106 | GetIptTraceVersion ( 107 | _Out_ PUSHORT TraceVersion 108 | ); 109 | 110 | NTSTATUS 111 | GetProcessIptTraceSize ( 112 | _In_ HANDLE ProcessHandle, 113 | _Out_ PULONG TraceSize 114 | ); 115 | 116 | NTSTATUS 117 | GetProcessIptTrace ( 118 | _In_ HANDLE ProcessHandle, 119 | _In_ PVOID Trace, 120 | _In_ ULONG TraceSize 121 | ); 122 | 123 | NTSTATUS 124 | StartProcessIptTrace ( 125 | _In_ HANDLE ProcessHandle, 126 | _In_ IPT_OPTIONS Options 127 | ); 128 | 129 | NTSTATUS 130 | StopProcessIptTrace ( 131 | _In_ HANDLE ProcessHandle 132 | ); 133 | 134 | NTSTATUS 135 | StartCoreIptTracing ( 136 | _In_ IPT_OPTIONS Options, 137 | _In_ ULONG NumberOfTries, 138 | _In_ ULONG TraceDurationInSeconds 139 | ); 140 | 141 | NTSTATUS 142 | RegisterExtendedImageForIptTracing ( 143 | _In_ PWCHAR ImagePath, 144 | _In_opt_ PWCHAR FilteredPath, 145 | _In_ IPT_OPTIONS Options, 146 | _In_ ULONG NumberOfTries, 147 | _In_ ULONG TraceDurationInSeconds 148 | ); 149 | -------------------------------------------------------------------------------- /libipt/libipt.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 23 | CompileAsC 24 | CompileAsC 25 | CompileAsC 26 | CompileAsC 27 | 28 | 29 | 30 | 15.0 31 | {051DE316-C76C-4CFC-82DA-46C0B04CFAD8} 32 | Win32Proj 33 | winipt 34 | 10.0.17763.0 35 | libipt 36 | 37 | 38 | 39 | StaticLibrary 40 | false 41 | v141 42 | true 43 | Unicode 44 | 45 | 46 | 47 | include;$(VC_IncludePath);$(WindowsSDK_IncludePath); 48 | 49 | 50 | $(SolutionDir)$(Platform)\$(Configuration)\ 51 | $(Platform)\$(Configuration)\ 52 | 53 | 54 | $(SolutionDir)$(Platform)\$(Configuration)\ 55 | $(Platform)\$(Configuration)\ 56 | 57 | 58 | 59 | Level4 60 | Full 61 | true 62 | true 63 | true 64 | true 65 | AnySuitable 66 | Speed 67 | true 68 | 69 | 70 | Windows 71 | true 72 | true 73 | true 74 | Source.def 75 | Source.def 76 | Source.def 77 | Source.def 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /minidump_config.reg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/minidump_config.reg -------------------------------------------------------------------------------- /samples/desrubi_harness/DerusbiWrap.cpp: -------------------------------------------------------------------------------- 1 | // cl.exe /D_USERDLL /D_WINDLL DerusbiWrap.cpp /MT /link /DLL /OUT:DerusbiWrap.dll 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #pragma comment (lib, "Ws2_32.lib") 10 | 11 | #include 12 | 13 | EXPOSE_HARNESS( 14 | NULL, // target method, we will fill this in dynamically at DllMain 15 | NULL, // fuzz iter func, we will fill this in dynamically at DllMain 16 | NULL, // default input file (.cur_input) 17 | NULL, // no setup func needed 18 | TRUE, // use de-socket features 19 | FALSE // Not ready yet, we initialize dynamically in DllMain. 20 | ); 21 | 22 | HMODULE hMod; 23 | 24 | extern "C" __declspec(dllexport) 25 | void fuzz_me(void){ 26 | FARPROC pFun; 27 | DWORD dwRet=0; 28 | 29 | uint32_t v11[4]; 30 | v11[0] = 0x5e58186c; 31 | v11[1] = 0xbaadf00d; 32 | v11[2] = 0; 33 | v11[3] = 0; 34 | v11[4] = 0; 35 | 36 | WSADATA wsa; 37 | if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) 38 | { 39 | printf("Failed. Error Code : %d",WSAGetLastError()); 40 | return; 41 | } 42 | uint32_t* v12 = v11; 43 | 44 | typedef void func(void); 45 | func* f = (func*)((uint32_t)hMod + 0x5de0); 46 | __asm { 47 | mov edi, v12 48 | } 49 | f(); 50 | 51 | printf("Finished\n"); 52 | } 53 | 54 | int WINAPI DoSetup(void* param) { 55 | hMod = LoadLibraryA("dfb8.dll"); 56 | 57 | HarnessInfo.target_method = (LPVOID) GetProcAddress(GetModuleHandle(NULL), "target"); 58 | HarnessInfo.fuzz_iter_func = (void(CALLBACK *)(void)) fuzz_me; 59 | 60 | MemoryBarrier(); // Prevent the compiler from messing things up by reordering. 61 | InterlockedExchange8(&HarnessInfo.ready, TRUE); // Signal to forkserver that we're ready to go. 62 | 63 | return 0; 64 | } 65 | 66 | BOOL APIENTRY DllMain(HMODULE hModule, 67 | DWORD ul_reason_for_call, 68 | LPVOID lpReserved 69 | ) { 70 | switch (ul_reason_for_call) 71 | { 72 | case DLL_PROCESS_ATTACH: 73 | DoSetup(NULL); 74 | break; 75 | case DLL_THREAD_ATTACH: 76 | case DLL_THREAD_DETACH: 77 | case DLL_PROCESS_DETACH: 78 | break; 79 | } 80 | return TRUE; 81 | } 82 | -------------------------------------------------------------------------------- /samples/desrubi_harness/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern "C" __declspec(dllexport) void target(void) 6 | { 7 | 8 | } 9 | 10 | int main(void) 11 | { 12 | target(); 13 | return 0; 14 | } -------------------------------------------------------------------------------- /samples/toy_example/Harness.cpp: -------------------------------------------------------------------------------- 1 | // cl.exe /D_USERDLL /D_WINDLL Harness.cpp /MT /link /DLL /OUT:Harness.dll 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // This macro exports the HARNESS_INFO struct expected by fuzzer. The injected forkserver (injected-harness) will LoadLibrary the harness, and then use this. 9 | EXPOSE_HARNESS( 10 | NULL, // target method, we will fill this in dynamically at DllMain 11 | NULL, // fuzz iter func, we will fill this in dynamically at DllMain 12 | NULL, // default input file (.cur_input) 13 | NULL, // no setup func needed 14 | FALSE, // don't need desocket 15 | FALSE // Not ready yet, we initialize dynamically in DllMain. 16 | ); 17 | 18 | HMODULE hMainModule; 19 | LPVOID fuzzMe; 20 | 21 | BOOL APIENTRY DllMain(HMODULE hModule, 22 | DWORD ul_reason_for_call, 23 | LPVOID lpReserved 24 | ) 25 | { 26 | switch (ul_reason_for_call) 27 | { 28 | case DLL_PROCESS_ATTACH: 29 | hMainModule = GetModuleHandle(NULL); 30 | fuzzMe = GetProcAddress(hMainModule, "fuzz_me"); 31 | printf("fuzz_me at %p\n", fuzzMe); 32 | HarnessInfo.target_method = fuzzMe; 33 | HarnessInfo.fuzz_iter_func = (void (CALLBACK *)(void)) fuzzMe; 34 | 35 | MemoryBarrier(); // Prevent the compiler from messing things up by reordering. 36 | InterlockedExchange8(&HarnessInfo.ready, TRUE); // Signal to forkserver that we're ready to go. 37 | 38 | break; 39 | case DLL_THREAD_ATTACH: 40 | case DLL_THREAD_DETACH: 41 | case DLL_PROCESS_DETACH: 42 | break; 43 | } 44 | return TRUE; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /samples/toy_example/README.md: -------------------------------------------------------------------------------- 1 | # Toy example target program for fuzzing 2 | 3 | ``` 4 | afl-fuzz -i in -o out -t 1000 -F basicblock.bb -- -fork -debug -harness harness.dll -init_time 1000 -- toy_example.exe @@ 5 | ``` 6 | -------------------------------------------------------------------------------- /samples/toy_example/example.cc: -------------------------------------------------------------------------------- 1 | // fuzz_me will typically be at 0x401000 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #define DEBUG_LOG_FILE "toy_example.log" 8 | 9 | #define dbg_printf (void)printf 10 | 11 | typedef int (*test_func_t)(char*); 12 | HMODULE hMathlib; 13 | 14 | void check_fwrite() 15 | { 16 | static int counter = 0; 17 | FILE *fp; 18 | fp = fopen(DEBUG_LOG_FILE, "a"); 19 | fprintf(fp, "hello from toy example! counter value: %d\n", counter); 20 | fclose(fp); 21 | counter++; 22 | } 23 | 24 | __declspec(noinline) void __stdcall fuzz_me(char* filename) 25 | { 26 | char buf[201]; 27 | ZeroMemory(&buf, 201); 28 | FILE *fp = fopen(filename, "rb"); 29 | fread(buf, 1, 200, fp); 30 | 31 | test_func_t test_func = (test_func_t) GetProcAddress(hMathlib, "test"); // index 32 | int result = test_func(buf); 33 | printf("Result: %d\n", result); 34 | fclose(fp); 35 | 36 | check_fwrite(); 37 | 38 | TerminateProcess(INVALID_HANDLE_VALUE, 0); // Won't do anything 39 | printf("Bye"); 40 | TerminateProcess(GetCurrentProcess(), 0); // Should get reported as exit 41 | printf("We should never get here"); 42 | } 43 | 44 | int main(int argc, char ** argv) 45 | { 46 | system("del " DEBUG_LOG_FILE); 47 | 48 | hMathlib = LoadLibraryA("example_library.dll"); 49 | if (hMathlib == NULL) { 50 | dbg_printf("failed to load example_library , GLE = %d\n", GetLastError()); 51 | exit(1); 52 | } 53 | printf("example_library loaded at %p\n", hMathlib); 54 | 55 | //_getch(); 56 | 57 | fuzz_me(argv[1]); 58 | 59 | printf("main() ends\n"); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /samples/toy_example/example.def: -------------------------------------------------------------------------------- 1 | EXPORTS 2 | main @1 3 | fuzz_me @2 -------------------------------------------------------------------------------- /samples/toy_example/example_library.cpp: -------------------------------------------------------------------------------- 1 | // cl.exe /D_USERDLL /D_WINDLL example_library.cpp /MT /link /DLL /OUT:example_library.dll 2 | #include 3 | #include 4 | #include 5 | 6 | extern "C" __declspec(dllexport) int test(char *input) 7 | { 8 | char v2; 9 | signed int v3; 10 | unsigned int v4; 11 | char *v5; 12 | char v6; 13 | char v7; 14 | char v8; 15 | int v9; 16 | 17 | printf("msg:%s\n", input); 18 | if ( input[0] != 't' ) 19 | { 20 | printf("Error 1\n"); 21 | return 0; 22 | } 23 | if ( input[1] != 'e' ) 24 | { 25 | printf("Error 2\n"); 26 | return 0; 27 | } 28 | if ( input[2] != 's' ) 29 | { 30 | printf("Error 3\n"); 31 | return 0; 32 | } 33 | if (input[3] == '*' ) 34 | { 35 | // simple nullptr deref 36 | *(volatile char*)0 = 1; 37 | return 0; 38 | } 39 | else if (input[3] == '!') 40 | { 41 | // trigger a timeout 42 | Sleep(5000); 43 | return 0; 44 | } 45 | else if (input[3] != 't' ) 46 | { 47 | printf("Error 4\n"); 48 | return 0; 49 | } 50 | 51 | // buffer overflow 52 | v8 = 0; 53 | v3 = 5; 54 | v9 = 0; 55 | do 56 | { 57 | v4 = strlen(input) + 1; 58 | v5 = &v7; 59 | do 60 | v6 = (v5++)[1]; 61 | while ( v6 ); 62 | memcpy(v5, input, v4); 63 | --v3; 64 | } 65 | while ( v3 ); 66 | printf("buffer: %s\n", &v8); 67 | return 0; 68 | } 69 | 70 | BOOL APIENTRY DllMain(HMODULE hModule, 71 | DWORD ul_reason_for_call, 72 | LPVOID lpReserved 73 | ) 74 | { 75 | switch (ul_reason_for_call) 76 | { 77 | case DLL_PROCESS_ATTACH: 78 | case DLL_THREAD_ATTACH: 79 | case DLL_THREAD_DETACH: 80 | case DLL_PROCESS_DETACH: 81 | break; 82 | } 83 | return TRUE; 84 | } 85 | -------------------------------------------------------------------------------- /samples/toy_example/example_library.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /samples/toy_example/harness.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /samples/toy_example/in/input: -------------------------------------------------------------------------------- 1 | tet -------------------------------------------------------------------------------- /samples/toy_example/toy_example.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.1062 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "toy_example", "toy_example.vcxproj", "{59A3F671-1D99-41B0-B996-347D7A00D6F2}" 7 | ProjectSection(ProjectDependencies) = postProject 8 | {CDBB3666-471C-4125-913B-013B726F0265} = {CDBB3666-471C-4125-913B-013B726F0265} 9 | EndProjectSection 10 | EndProject 11 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "harness", "harness.vcxproj", "{44205441-1284-45A4-A064-E8BCF3C66CB4}" 12 | ProjectSection(ProjectDependencies) = postProject 13 | {59A3F671-1D99-41B0-B996-347D7A00D6F2} = {59A3F671-1D99-41B0-B996-347D7A00D6F2} 14 | EndProjectSection 15 | EndProject 16 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_library", "example_library.vcxproj", "{CDBB3666-471C-4125-913B-013B726F0265}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|x64 = Debug|x64 21 | Debug|x86 = Debug|x86 22 | Release|x64 = Release|x64 23 | Release|x86 = Release|x86 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Debug|x64.ActiveCfg = Debug|x64 27 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Debug|x64.Build.0 = Debug|x64 28 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Debug|x86.ActiveCfg = Debug|Win32 29 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Debug|x86.Build.0 = Debug|Win32 30 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Release|x64.ActiveCfg = Release|x64 31 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Release|x64.Build.0 = Release|x64 32 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Release|x86.ActiveCfg = Release|Win32 33 | {59A3F671-1D99-41B0-B996-347D7A00D6F2}.Release|x86.Build.0 = Release|Win32 34 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Debug|x64.ActiveCfg = Debug|x64 35 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Debug|x64.Build.0 = Debug|x64 36 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Debug|x86.ActiveCfg = Debug|Win32 37 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Debug|x86.Build.0 = Debug|Win32 38 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Release|x64.ActiveCfg = Release|x64 39 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Release|x64.Build.0 = Release|x64 40 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Release|x86.ActiveCfg = Release|Win32 41 | {44205441-1284-45A4-A064-E8BCF3C66CB4}.Release|x86.Build.0 = Release|Win32 42 | {CDBB3666-471C-4125-913B-013B726F0265}.Debug|x64.ActiveCfg = Debug|x64 43 | {CDBB3666-471C-4125-913B-013B726F0265}.Debug|x64.Build.0 = Debug|x64 44 | {CDBB3666-471C-4125-913B-013B726F0265}.Debug|x86.ActiveCfg = Debug|Win32 45 | {CDBB3666-471C-4125-913B-013B726F0265}.Debug|x86.Build.0 = Debug|Win32 46 | {CDBB3666-471C-4125-913B-013B726F0265}.Release|x64.ActiveCfg = Release|x64 47 | {CDBB3666-471C-4125-913B-013B726F0265}.Release|x64.Build.0 = Release|x64 48 | {CDBB3666-471C-4125-913B-013B726F0265}.Release|x86.ActiveCfg = Release|Win32 49 | {CDBB3666-471C-4125-913B-013B726F0265}.Release|x86.Build.0 = Release|Win32 50 | EndGlobalSection 51 | GlobalSection(SolutionProperties) = preSolution 52 | HideSolutionNode = FALSE 53 | EndGlobalSection 54 | GlobalSection(ExtensibilityGlobals) = postSolution 55 | SolutionGuid = {B78E4E18-CD8A-4472-B0BC-BE726E8C1DA9} 56 | EndGlobalSection 57 | EndGlobal 58 | -------------------------------------------------------------------------------- /samples/toy_example/toy_example.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | 23 | 24 | Source Files 25 | 26 | 27 | -------------------------------------------------------------------------------- /scripts/ghidra_basic_blocks.py: -------------------------------------------------------------------------------- 1 | # Output basic block addresses for a binary in the format Winnie-AFL expects: 2 | # [module_name.exe/.dll] 3 | # relative virtual address,file offset 4 | # ... 5 | # [module #2] 6 | # rva,file offset 7 | # ... 8 | # 9 | from ghidra.program.model.block import BasicBlockModel 10 | from ghidra.util.task import TaskMonitor 11 | from ghidra.program.flatapi import FlatProgramAPI 12 | from datetime import datetime 13 | import os 14 | 15 | def main(): 16 | # File to write output to 17 | output_path = "{}/{}".format(os.getcwd(), datetime.now().strftime("bblist_{}_%d_%m_%y_%H_%M_%S.bb".format(currentProgram.getName()))) 18 | output_file = open(output_path, "w") 19 | 20 | bbm = BasicBlockModel(currentProgram) 21 | blocks = bbm.getCodeBlocks(TaskMonitor.DUMMY) 22 | flat_api = FlatProgramAPI(currentProgram) 23 | 24 | # Write module name - for now, just the current program's executable module 25 | output_file.write("[{}]\n".format(currentProgram.getName())) 26 | 27 | # Add up size of sections preceding executable section to get file offsets 28 | # We assume that the sum of the sizes of each block before the executable 29 | # block is equal to the file offset of the executable block 30 | # (this script only works for the first executable section) 31 | sections = currentProgram.getMemory().getBlocks() 32 | precedingSectionSize = 0 33 | exeSectionStart = 0 34 | for s in sections: 35 | if s.isExecute(): 36 | exeSectionStart = s.getStart().getOffset() 37 | break 38 | precedingSectionSize += s.getSize() 39 | print "Size of section {}:{}".format(s.getName(), s.getSize()) 40 | 41 | blocks_skipped = 0 42 | while True: 43 | block = blocks.next() 44 | if not block: 45 | break 46 | # Skip BBs that already have breakpoints 47 | if flat_api.getByte(block.minAddress) == -52: 48 | blocks_skipped += 1 49 | continue 50 | rva = block.minAddress.subtract(currentProgram.getImageBase().getOffset()).getOffset() 51 | file_offset = block.minAddress.subtract(exeSectionStart - precedingSectionSize).getOffset() 52 | cur_line = "0x{:x},0x{:x}\n".format(rva, file_offset) 53 | output_file.write(cur_line) 54 | 55 | print "Skipped {} BBs that already had breakpoints".format(blocks_skipped) 56 | print "Output written to {}".format(output_path) 57 | 58 | if __name__ == "__main__": 59 | main() 60 | 61 | -------------------------------------------------------------------------------- /scripts/ida_basic_blocks.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import idaapi 4 | import idautils 5 | import ida_kernwin 6 | import idc 7 | 8 | import os 9 | 10 | baseaddr = idaapi.get_imagebase() 11 | dumped = set() 12 | module_name = idaapi.get_root_filename() 13 | SIZE_LIMIT = 0 14 | 15 | def main(): 16 | out_file_name = ida_kernwin.ask_file(True, 'basicblocks.bb', 'Select output file') 17 | 18 | print('Will save to %s' % out_file_name) 19 | 20 | if os.path.isfile(out_file_name): 21 | # validate existing file before appending to it 22 | with open(out_file_name, 'r') as f: 23 | for line in f: 24 | if line.startswith('[') and module_name in line: 25 | warning('Module %s already exists in %s' % (module_name, os.path.basename(out_file_name))) 26 | return 27 | 28 | with open (out_file_name, 'a') as f: 29 | f.write('[%s]\n' % (module_name,)) 30 | for fva in idautils.Functions(): 31 | dump_bbs(fva, f) 32 | f.close() 33 | 34 | print('OK, done. Found %d basic blocks' % (len(dumped),)) 35 | ida_kernwin.info('Saved to %s' % (out_file_name,)) 36 | 37 | def dump_bbs(fva, outfile): 38 | func = idaapi.get_func(fva) 39 | cfg = idaapi.FlowChart(func) 40 | for bb in cfg: 41 | if bb.start_ea not in dumped and bb.end_ea - bb.start_ea > SIZE_LIMIT: 42 | dumped.add(bb.start_ea) 43 | result = format_bb(bb) 44 | # print (result) 45 | outfile.write(result + '\n') 46 | 47 | def format_bb(bb): 48 | return ("0x%x,0x%x" % (bb.start_ea - baseaddr, idaapi.get_fileregion_offset(bb.start_ea))) 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /wow64ext/CMemPtr.h: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * WOW64Ext Library 4 | * 5 | * Copyright (c) 2014 ReWolf 6 | * http://blog.rewolf.pl/ 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU Lesser General Public License as published 10 | * by the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU Lesser General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU Lesser General Public License 19 | * along with this program. If not, see . 20 | * 21 | */ 22 | #pragma once 23 | 24 | class CMemPtr 25 | { 26 | private: 27 | void** m_ptr; 28 | bool watchActive; 29 | 30 | public: 31 | CMemPtr(void** ptr) : m_ptr(ptr), watchActive(true) {} 32 | 33 | ~CMemPtr() 34 | { 35 | if (*m_ptr && watchActive) 36 | { 37 | free(*m_ptr); 38 | *m_ptr = 0; 39 | } 40 | } 41 | 42 | void disableWatch() { watchActive = false; } 43 | }; 44 | 45 | #define WATCH(ptr) \ 46 | CMemPtr watch_##ptr((void**)&ptr) 47 | 48 | #define DISABLE_WATCH(ptr) \ 49 | watch_##ptr.disableWatch() 50 | -------------------------------------------------------------------------------- /wow64ext/README.md: -------------------------------------------------------------------------------- 1 | # rewolf-wow64ext 2 | This directory contains a fork of [wow64ext](https://github.com/rwfpl/rewolf-wow64ext). 3 | 4 | WOW64Ext is a helper library for x86 programs that runs under WOW64 layer on x64 versions of Microsoft Windows operating systems. It enables x86 applications to read, write and enumerate memory of a native x64 applications. There is also possibility to call any x64 function from 64-bits version of NTDLL through a special function called X64Call(). As a bonus, wow64ext.h contains definitions of some structures that might be useful for programs that want to access PEB, TEB, TIB etc. 5 | -------------------------------------------------------------------------------- /wow64ext/internal.h: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * WOW64Ext Library 4 | * 5 | * Copyright (c) 2014 ReWolf 6 | * http://blog.rewolf.pl/ 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU Lesser General Public License as published 10 | * by the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU Lesser General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU Lesser General Public License 19 | * along with this program. If not, see . 20 | * 21 | */ 22 | #pragma once 23 | 24 | #define EMIT(a) __asm __emit (a) 25 | 26 | #define X64_Start_with_CS(_cs) \ 27 | { \ 28 | EMIT(0x6A) EMIT(_cs) /* push _cs */ \ 29 | EMIT(0xE8) EMIT(0) EMIT(0) EMIT(0) EMIT(0) /* call $+5 */ \ 30 | EMIT(0x83) EMIT(4) EMIT(0x24) EMIT(5) /* add dword [esp], 5 */ \ 31 | EMIT(0xCB) /* retf */ \ 32 | } 33 | 34 | #define X64_End_with_CS(_cs) \ 35 | { \ 36 | EMIT(0xE8) EMIT(0) EMIT(0) EMIT(0) EMIT(0) /* call $+5 */ \ 37 | EMIT(0xC7) EMIT(0x44) EMIT(0x24) EMIT(4) EMIT(_cs) EMIT(0) EMIT(0) EMIT(0) /* mov dword [rsp + 4], _cs */ \ 38 | EMIT(0x83) EMIT(4) EMIT(0x24) EMIT(0xD) /* add dword [rsp], 0xD */ \ 39 | EMIT(0xCB) /* retf */ \ 40 | } 41 | 42 | #define X64_Start() X64_Start_with_CS(0x33) 43 | #define X64_End() X64_End_with_CS(0x23) 44 | 45 | #define _RAX 0 46 | #define _RCX 1 47 | #define _RDX 2 48 | #define _RBX 3 49 | #define _RSP 4 50 | #define _RBP 5 51 | #define _RSI 6 52 | #define _RDI 7 53 | #define _R8 8 54 | #define _R9 9 55 | #define _R10 10 56 | #define _R11 11 57 | #define _R12 12 58 | #define _R13 13 59 | #define _R14 14 60 | #define _R15 15 61 | 62 | #define X64_Push(r) EMIT(0x48 | ((r) >> 3)) EMIT(0x50 | ((r) & 7)) 63 | #define X64_Pop(r) EMIT(0x48 | ((r) >> 3)) EMIT(0x58 | ((r) & 7)) 64 | 65 | #define REX_W EMIT(0x48) __asm 66 | 67 | //to fool M$ inline asm compiler I'm using 2 DWORDs instead of DWORD64 68 | //use of DWORD64 will generate wrong 'pop word ptr[]' and it will break stack 69 | union reg64 70 | { 71 | DWORD64 v; 72 | DWORD dw[2]; 73 | }; 74 | -------------------------------------------------------------------------------- /wow64ext/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by wow64ext.rc 4 | 5 | // Next default values for new objects 6 | // 7 | #ifdef APSTUDIO_INVOKED 8 | #ifndef APSTUDIO_READONLY_SYMBOLS 9 | #define _APS_NEXT_RESOURCE_VALUE 101 10 | #define _APS_NEXT_COMMAND_VALUE 40001 11 | #define _APS_NEXT_CONTROL_VALUE 1001 12 | #define _APS_NEXT_SYMED_VALUE 101 13 | #endif 14 | #endif 15 | -------------------------------------------------------------------------------- /wow64ext/wow64ext.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sslab-gatech/winnie/117cab9d77952bfa6c565e794c6fbd1f7dc50abc/wow64ext/wow64ext.rc --------------------------------------------------------------------------------