From e84418aee8b527780227daa8c392a11ec5614f97 Mon Sep 17 00:00:00 2001 From: John Chadwick Date: Sat, 3 Aug 2019 10:53:47 -0700 Subject: [PATCH] Initial commit! --- .gitignore | 3 + LICENSE.md | 28 ++ Makefile | 60 ++++ README.md | 72 ++++ export.def | 18 + src/common-fnptr.h | 93 +++++ src/common.c | 170 +++++++++ src/common.h | 38 ++ src/hooks/hooks.c | 13 + src/hooks/hooks.h | 8 + src/hooks/kernel32/inject.c | 83 +++++ src/hooks/kernel32/inject.h | 8 + src/hooks/user32/window.c | 17 + src/hooks/user32/window.h | 8 + src/hooks/wininet/netredir.c | 53 +++ src/hooks/wininet/netredir.h | 8 + src/hooks/ws2_32/redir.c | 25 ++ src/hooks/ws2_32/redir.h | 8 + src/ijlfwd.c | 38 ++ src/ijlfwd.h | 15 + src/inject.c | 285 +++++++++++++++ src/inject.h | 10 + src/main.c | 134 +++++++ src/ntdll.c | 28 ++ src/ntdll.h | 26 ++ src/patch.c | 158 ++++++++ src/patch.h | 13 + src/third_party/lend/COPYING | 674 +++++++++++++++++++++++++++++++++++ src/third_party/lend/ld32.c | 80 +++++ src/third_party/lend/ld32.h | 254 +++++++++++++ 30 files changed, 2428 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.md create mode 100644 Makefile create mode 100644 README.md create mode 100644 export.def create mode 100644 src/common-fnptr.h create mode 100644 src/common.c create mode 100644 src/common.h create mode 100644 src/hooks/hooks.c create mode 100644 src/hooks/hooks.h create mode 100644 src/hooks/kernel32/inject.c create mode 100644 src/hooks/kernel32/inject.h create mode 100644 src/hooks/user32/window.c create mode 100644 src/hooks/user32/window.h create mode 100644 src/hooks/wininet/netredir.c create mode 100644 src/hooks/wininet/netredir.h create mode 100644 src/hooks/ws2_32/redir.c create mode 100644 src/hooks/ws2_32/redir.h create mode 100644 src/ijlfwd.c create mode 100644 src/ijlfwd.h create mode 100644 src/inject.c create mode 100644 src/inject.h create mode 100644 src/main.c create mode 100644 src/ntdll.c create mode 100644 src/ntdll.h create mode 100644 src/patch.c create mode 100644 src/patch.h create mode 100644 src/third_party/lend/COPYING create mode 100644 src/third_party/lend/ld32.c create mode 100644 src/third_party/lend/ld32.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40902d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/obj/ +/out/ +/.vscode/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..0aa0977 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,28 @@ +# GPLv3 License + +The following files, part of an x86 Length Disassembler written by Byron Platt, +are licensed under GPLv3: + +* [src/third_party/lend/ld32.c](./src/third_party/lend/ld32.c) +* [src/third_party/lend/ld32.h](./src/third_party/lend/ld32.h) + +Please see the respective [COPYING](./src/third_party/lend/COPYING) for the full +license content of the GPLv3. + +# ISC License + +All other files are licensed under the ISC license: + +Pangbox © 2018-2019, John Chadwick + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a1ff2a4 --- /dev/null +++ b/Makefile @@ -0,0 +1,60 @@ +WATCOM := $(HOME)/Programs/watcom +WCC := $(WATCOM)/binl/wcc386 +WLINK := $(WATCOM)/binl/wlink +MKDIR := mkdir +CP := cp + +CFLAGS := \ + -i$(WATCOM)/h \ + -i$(WATCOM)/h/nt \ + -i$(WATCOM)/h/nt/ddk \ + -zl \ + -s \ + -bd \ + -os \ + -d0 \ + -fr= \ + -zq + +LDFLAGS := \ + LIBPATH $(WATCOM)/lib386 \ + LIBPATH $(WATCOM)/lib386/nt + +OBJS := \ + obj/hooks/kernel32/inject.o \ + obj/hooks/user32/window.o \ + obj/hooks/ws2_32/redir.o \ + obj/hooks/wininet/netredir.o \ + obj/hooks/hooks.o \ + obj/third_party/lend/ld32.o \ + obj/common.o \ + obj/ijlfwd.o \ + obj/inject.o \ + obj/main.o \ + obj/ntdll.o \ + obj/patch.o + +OUT := out/ijl15.dll + +all: $(OUT) + +.PHONY: clean + +obj/%.o: src/%.c + @$(MKDIR) -p $(dir $@) + $(WCC) $(CFLAGS) $< -fo=$@ + +$(OUT): $(OBJS) + @$(MKDIR) -p $(dir $@) + $(WLINK) $(LDFLAGS) NAME $@ @export.def FILE {$(OBJS)} + +clean: + $(RM) $(OBJS) $(OUT) + +shared: $(OUT) + $(RM) "${HOME}/Shared/ijl15.dll" + $(CP) "$(OUT)" "${HOME}/Shared/ijl15.dll" + $(RM) "${HOME}/Pangya/Clients/PangYa Japan/ijl15.dll" + $(CP) "$(OUT)" "${HOME}/Pangya/Clients/PangYa Japan/ijl15.dll" + $(RM) "${HOME}/Pangya/Clients/PangYa US 852.00/ijl15.dll" + $(CP) "$(OUT)" "${HOME}/Pangya/Clients/PangYa US 852.00/ijl15.dll" diff --git a/README.md b/README.md new file mode 100644 index 0000000..1bd8b38 --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# rugburn + +`rugburn` is an unobtrusive and small shim for `ijl15.dll` that allows you to +run unmodified Pangya without GameGuard. + +This also allows you to run PangYa under Wine :) + +Features: + + * Redirects network traffic to localhost. (You can modify this to redirect + wherever you want; see [src/hooks/ws2_32/redir.c](./src/hooks/ws2_32/redir.c) + and [src/hooks/wininet/netredir.c](./src/hooks/wininet/netredir.c).) + + * Patches GameGuard's check routines. + + * Prevents PangYa from creating annoying topmost windows. + + * Sets PANGYA_ARG when possible to avoid the updater check. + + * Implements the IJL15 API and forwards it to `ijl15_real.dll`, + no need for tricky patching. + + * **This program is not suitable for cheating. It does not support the only + active region of PangYa and does not offer GameGuard emulation that would + be needed to stay connected to an official server.** This program is + designed for unofficial servers and educational use! + +## Compiling + +`rugburn` is compiled with OpenWatcom, a simple compiler with few dependencies. +It was chosen because it offered an easy path to cross-compilation while also +allowing for tiny binaries that did not depend on libc. + +You can modify the Make variables `WATCOM`, `WCC`, and `WLINK` to match your +environment, then run `make`. An `ijl15.dll` should appear in the `out` folder. + +## Installation + + 1. Move the original ijl15.dll binary in the PangYa folder to ijl15_real.dll. + The exact name is important. + + 2. Copy the rugburn ijl15.dll into the PangYa folder. + +Do not use update.exe anymore. Just run ProjectG directly. The update servers +are still active in US, so if you run the updater you may accidentally patch +over your files. + +## Usage + +Once installed, you can run ProjectG directly. Enjoy! + +## Troubleshooting + +If you have any issues, I can **not** guarantee that I can help you. However, please feel free to create a GitHub issue. Please describe your problem and if applicable, attach a copy of the `ijllog.txt` file. + +## Contributing + +I would be overjoyed if anyone wanted to contribute to this project! However, the project is considered _nearly_ feature complete and therefore new features may not always be accepted. Well-tested, well-written improvements to the patching routines would definitely be welcome. + +Please note that I may take a while to get to your pull request. This project is not my fulltime job. Sorry! + +## Why the name? +I went through a lot of names during development. I wanted something catchy but not too lame. The initial codename for the project was 'ggtfo', a portmanteau of 'gg' for 'GameGuard' and 'gtfo' for... yeah. This was mostly out of anger, and seemed a bit too edgy. + +Another codename it had was 'ijlshim' reflecting the nature of how it works. However, this seemed way too boring. As far as literal names go, it also did not really describe _what_ the software did. + +Inspiration came for this name when trying to find anagrams for the word 'GameGuard' and the phrase 'Damage Rug' showed up. 'Damage Rug' was pretty amusing, but it isn't exactly catchy, so I decided to drop the anagram idea and just go with the virtually non-sense name 'rugburn.' + +So as is often the case with open source projects, the name is meaningless. + +## License +Most of the code of rugburn is licensed under the ISC license. Some portions are licensed differently. See [LICENSE.md](./LICENSE.md) for complete licensing information. \ No newline at end of file diff --git a/export.def b/export.def new file mode 100644 index 0000000..6da385d --- /dev/null +++ b/export.def @@ -0,0 +1,18 @@ +FORMAT windows dll +RUNTIME windows = 4.0 +ALIAS __DLLstart_ = '_DllMain@12' +LIBRARY {kernel32.lib user32.lib shlwapi.lib} + +OPTION START = '_DllMain@12' +OPTION STACK = 8k +OPTION ALIGN = 512 +OPTION NODEFAULTLIBS +OPTION ELIMINATE +OPTION QUIET + +EXPORT ijlGetLibVersion.1 = '_ijlGetLibVersion@0' +EXPORT ijlInit.2 = '_ijlInit@4' +EXPORT ijlFree.3 = '_ijlFree@4' +EXPORT ijlRead.4 = '_ijlRead@8' +EXPORT ijlWrite.5 = '_ijlWrite@8' +EXPORT ijlErrorStr.6 = '_ijlErrorStr@4' diff --git a/src/common-fnptr.h b/src/common-fnptr.h new file mode 100644 index 0000000..007ac6f --- /dev/null +++ b/src/common-fnptr.h @@ -0,0 +1,93 @@ +/* + * This file contains many function pointer types and structures for Windows + * APIs. Many of these structures are not actually needed for this patcher, + * but were used in the process of developing it. These types make it easy to + * hook various APIs to manipulate or inspect behavior. + */ + +#ifndef COMMON_FNPTR_H +#define COMMON_FNPTR_H + +#include + +typedef struct _DNS_QUERY_REQUEST { + ULONG Version; + PCWSTR QueryName; + WORD QueryType; + ULONG64 QueryOptions; + PVOID pDnsServerList; + ULONG InterfaceIndex; + PVOID pQueryCompletionCallback; + PVOID pQueryContext; +} DNS_QUERY_REQUEST, *PDNS_QUERY_REQUEST; + +typedef struct _DNS_QUERY_RESULT { + ULONG Version; + DNS_STATUS QueryStatus; + ULONG64 QueryOptions; + PDNS_RECORD pQueryRecords; + PVOID Reserved; +} DNS_QUERY_RESULT, *PDNS_QUERY_RESULT; + +typedef struct _DNS_QUERY_CANCEL { + CHAR Reserved[32]; +} DNS_QUERY_CANCEL, *PDNS_QUERY_CANCEL; + +// general +typedef BOOL (WINAPI *PFNDLLMAINPROC)(HMODULE, DWORD, PVOID); + +// ws2_32.dll +typedef int (STDCALL *PFNCONNECTPROC)(SOCKET, const struct sockaddr *, int); +typedef BOOL (STDCALL *PFNCONNECTEXPROC)(SOCKET, const struct sockaddr *, int, PVOID, DWORD, LPDWORD, LPOVERLAPPED); +typedef int (STDCALL *PFNWSACONNECTPROC)(SOCKET, const struct sockaddr *, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS); + +// dnsapi.dll +typedef DNS_STATUS (STDCALL *PFNDNSQUERYEXPROC)(PDNS_QUERY_REQUEST pQueryRequest, PDNS_QUERY_RESULT pQueryResults, PDNS_QUERY_CANCEL pCancelHandle); + +// advapi32.dll +typedef BOOL (STDCALL *PFNCRYPTDECRYPTPROC)(HCRYPTKEY, HCRYPTHASH, BOOL, DWORD, BYTE *, DWORD *); +typedef BOOL (STDCALL *PFNCRYPTGETHASHPARAMPROC)(HCRYPTHASH, DWORD, BYTE*, DWORD*, DWORD); +typedef BOOL (STDCALL *PFNCRYPTVERIFYSIGNATUREAPROC)(HCRYPTHASH, CONST BYTE *, DWORD, HCRYPTKEY, LPCSTR, DWORD); +typedef BOOL (STDCALL *PFNCRYPTIMPORTKEYPROC)(HCRYPTPROV, CONST BYTE *, DWORD, HCRYPTKEY, DWORD, HCRYPTKEY *); + +// user32.dll +typedef int (STDCALL *PFNMESSAGEBOXAPROC)(HWND, LPCSTR, LPCSTR, UINT); +typedef HWND (STDCALL *PFNCREATEWINDOWEXAPROC)(DWORD, LPCSTR, LPCSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID); +typedef LRESULT (STDCALL *PFNSENDMESSAGEPROC)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +typedef int (STDCALL *PFNMESSAGEBOXAPROC)(HWND, LPCSTR, LPCSTR, UINT); +typedef BOOL (STDCALL *PFNPEEKMESSAGEAPROC)(LPMSG, HWND, UINT, UINT, UINT); +typedef BOOL (STDCALL *PFNGETMESSAGEAPROC)(LPMSG, HWND, UINT, UINT); +typedef UINT_PTR (STDCALL *PFNSETTIMERPROC)(HWND, UINT_PTR, UINT, TIMERPROC); + +// kernel32.dll +typedef HMODULE (STDCALL *PFNLOADLIBRARYAPROC)(LPCSTR); +typedef FARPROC (STDCALL *PFNGETPROCADDRESSPROC)(HMODULE, LPCSTR); +typedef DWORD (STDCALL *PFNGETENVIRONMENTVARIABLEAPROC)(LPCSTR, LPSTR, DWORD); +typedef BOOL (STDCALL *PFNCREATEPROCESSAPROC)(LPCSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCSTR, LPSTARTUPINFOA, LPPROCESS_INFORMATION); +typedef BOOL (STDCALL *PFNISWOW64PROCESSPROC) (HANDLE, PBOOL); +typedef HANDLE (STDCALL *PFNCREATEFILEAPROC)(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); +typedef HANDLE (STDCALL *PFNCREATEFILEMAPPINGAPROC)(HANDLE, LPSECURITY_ATTRIBUTES, DWORD, DWORD, DWORD, LPCSTR); +typedef HANDLE (STDCALL *PFNOPENMUTEXAPROC)(DWORD, BOOL, LPCSTR); +typedef VOID (STDCALL *PFNEXITPROCESSPROC)(UINT); +typedef HANDLE (STDCALL *PFNCREATEMUTEXAPROC)(LPSECURITY_ATTRIBUTES, BOOL, LPCSTR); +typedef DWORD (STDCALL *PFNGETCURRENTTHREADIDPROC)(); +typedef VOID (STDCALL *PFNSLEEPPROC)(DWORD); +typedef DWORD (STDCALL *PFNSLEEPEXPROC)(DWORD, BOOL); +typedef DWORD (STDCALL *PFNWAITFORSINGLEOBJECTPROC)(HANDLE, DWORD); +typedef HANDLE (STDCALL *PFNOPENEVENTAPROC)(DWORD, BOOL, LPCSTR); +typedef HANDLE (STDCALL *PFNCREATEEVENTAPROC)(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName); + +// ntdll.dll +typedef NTSTATUS (NTAPI *PFNNTQUERYINFORMATIONPROCESSPROC)(HANDLE, DWORD, PVOID, ULONG, PULONG); +typedef NTSTATUS (NTAPI *PFNZWTERMINATEPROCESSPROC)(HANDLE, NTSTATUS); +typedef DWORD (STDCALL *PFNRTLEXITUSERPROCESSPROC)(NTSTATUS ExitStatus); +typedef LONG (NTAPI *PFNNTSUSPENDPROCESSPROC)(IN HANDLE ProcessHandle); + +// wininet.dll +typedef void (STDCALL *PFNINTERNETCONNECTAPROC)(HINTERNET, LPCSTR, INTERNET_PORT, LPCSTR, LPCSTR, DWORD, DWORD, DWORD_PTR); +typedef HINTERNET (STDCALL *PFNINTERNETOPENURLAPROC)(HINTERNET, LPCSTR, LPCSTR, DWORD, DWORD, DWORD_PTR); + +// winmm.dll +typedef DWORD (STDCALL *PFNTIMEGETTIMEPROC)(); + +#endif diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..c838b88 --- /dev/null +++ b/src/common.c @@ -0,0 +1,170 @@ +#include "common.h" + +#define LOG_FILENAME "gglog.txt" + +PSTR pszSelfPath = NULL; +PSTR pszSelfName = NULL; +PSTR pszLogPrefix = NULL; + +PVOID memcpy(PVOID dest, VOID const *src, size_t size) { + BYTE *bdest = (BYTE *)dest; + BYTE const *bsrc = (BYTE const *)src; + while (size > 0) { + *bdest++ = *bsrc++; + --size; + } + return dest; +} + +PVOID memset(PVOID p, INT c, UINT size) { + PCHAR data = (PCHAR)p; + while (size > 0) { + *data++ = c; + --size; + } + return p; +} + +PSTR GetSelfPath() { + if (pszSelfPath != NULL) { + return pszSelfPath; + } + + pszSelfPath = LocalAlloc(0, 4096); + + GetModuleFileNameA(GetModuleHandleA("ijl15"), pszSelfPath, 4096); + + return pszSelfPath; +} + +BOOL FileExists(LPCTSTR szPath) { + return GetFileAttributes(szPath) != INVALID_FILE_ATTRIBUTES; +} + +VOID FatalError(PCHAR fmt, ...) { + PCHAR buffer = LocalAlloc(0, 4096); + + va_list args; + va_start(args, fmt); + wvsprintfA(buffer, fmt, args); + va_end(args); + + MessageBoxA(HWND_DESKTOP, buffer, "ijlshim", MB_OK|MB_ICONERROR); + LocalFree(buffer); + ExitProcess(1); +} + +VOID Warning(PCHAR fmt, ...) { + va_list args; + PCHAR buffer = LocalAlloc(0, 4096); + + va_start(args, fmt); + wvsprintfA(buffer, fmt, args); + va_end(args); + + MessageBoxA(HWND_DESKTOP, buffer, "ijlshim", MB_OK|MB_ICONWARNING); + LocalFree(buffer); +} + +extern PFNCREATEFILEAPROC pCreateFileA; + +VOID Log(PCHAR fmt, ...) { + va_list args; + HANDLE hAppend; + PCHAR buffer = LocalAlloc(0, 4096); + PCHAR pfxbuffer = LocalAlloc(0, 128); + PCHAR logmsg = buffer; + DWORD cb = 0; + + if (pszLogPrefix != NULL) { + StrCpyA(logmsg, pszLogPrefix); + while (*logmsg != '\0') logmsg++; + } + + wsprintfA(pfxbuffer, "T:%d] ", GetCurrentThreadId()); + StrCpyA(logmsg, pfxbuffer); + while (*logmsg != '\0') logmsg++; + + cb = logmsg - buffer; + + va_start(args, fmt); + cb += wvsprintfA(logmsg, fmt, args); + va_end(args); + + hAppend = CreateFileA(LOG_FILENAME, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + WriteFile(hAppend, buffer, cb, &cb, NULL); + CloseHandle(hAppend); + LocalFree(buffer); +} + +VOID LogInit() { + PCHAR szPfxBuf = LocalAlloc(0, 4096); + PCHAR szFileName = LocalAlloc(0, 4096); + PCHAR szBaseName; + DWORD cbFileName; + + cbFileName = GetModuleFileNameA(NULL, szFileName, 4096); + szBaseName = szFileName + cbFileName; + + while (szBaseName > szFileName) { + if (*szBaseName == '\\') { + szBaseName++; + break; + } + szBaseName--; + } + + pszSelfName = szBaseName; + wsprintfA(szPfxBuf, "%s:%d] ", szBaseName, GetCurrentProcessId()); + pszLogPrefix = szPfxBuf; +} + +HMODULE LoadLib(LPCSTR szName) { + HMODULE hModule; + + hModule = LoadLibraryA(szName); + if (hModule == NULL) { + FatalError("Could not load module %s (%08x)", szName, GetLastError()); + } + + return hModule; +} + +PVOID GetProc(HMODULE hModule, LPCSTR szName) { + PVOID pvProc; + + pvProc = (PVOID)GetProcAddress(hModule, szName); + if (pvProc == NULL) { + FatalError("Could not load proc %s (%08x)", szName, GetLastError()); + } + + return pvProc; +} + +PANGYAVER DetectPangyaVersion() { + if (FileExists("PangyaUS.ini")) { + return PANGYA_US; + } else if (FileExists("PangyaJP.ini")) { + return PANGYA_JP; + } else if (FileExists("PangyaTH.ini")) { + // TODO: Detect actual PangyaTH separately. + return PANGYA_BR; + } + return PANGYA_US; +} + +PSTR GetPangyaArg(PANGYAVER pangyaVersion) { + switch (pangyaVersion) { + case PANGYA_US: + return StrDupA("{2D0FA24B-336B-4e99-9D30-3116331EFDA0}"); + + case PANGYA_JP: + return StrDupA("{E69B65A2-7A7E-4977-85E5-B19516D885CB}"); + + case PANGYA_BR: + return StrDupA("{E69B65A2-7A7E-4977-85E5-B19516D885CB}"); + + default: + return NULL; + } +} diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..0f193f3 --- /dev/null +++ b/src/common.h @@ -0,0 +1,38 @@ +#ifndef COMMON_H +#define COMMON_H + +#define STDCALL __stdcall +#define EXPORT __export + +#include +#include +#include +#include +#include +#include +#include + +#include "common-fnptr.h" + +typedef enum _PANGYAVER { + PANGYA_US, + PANGYA_JP, + PANGYA_BR, +} PANGYAVER; + +extern PCHAR pszSelfName; + +PVOID memcpy(PVOID dest, VOID const *src, size_t size); +PVOID memset(PVOID p, INT c, UINT size); +BOOL FileExists(LPCSTR szPath); +VOID FatalError(PCHAR fmt, ...); +VOID Warning(PCHAR fmt, ...); +VOID Log(PCHAR fmt, ...); +VOID LogInit(); +HMODULE LoadLib(LPCSTR szName); +PVOID GetProc(HMODULE hModule, LPCSTR szName); +PANGYAVER DetectPangyaVersion(); +PSTR GetPangyaArg(PANGYAVER pangyaVersion); +PSTR GetSelfPath(); + +#endif diff --git a/src/hooks/hooks.c b/src/hooks/hooks.c new file mode 100644 index 0000000..95a74bf --- /dev/null +++ b/src/hooks/hooks.c @@ -0,0 +1,13 @@ +#include "hooks.h" + +#include "kernel32/inject.h" +#include "user32/window.h" +#include "wininet/netredir.h" +#include "ws2_32/redir.h" + +VOID InitHooks() { + InitInjectHook(); + InitWindowHook(); + InitNetRedirHook(); + InitRedirHook(); +} diff --git a/src/hooks/hooks.h b/src/hooks/hooks.h new file mode 100644 index 0000000..b7ecac5 --- /dev/null +++ b/src/hooks/hooks.h @@ -0,0 +1,8 @@ +#ifndef HOOKS_HOOKS_H +#define HOOKS_HOOKS_H + +#include "../common.h" + +VOID InitHooks(); + +#endif diff --git a/src/hooks/kernel32/inject.c b/src/hooks/kernel32/inject.c new file mode 100644 index 0000000..a6557c0 --- /dev/null +++ b/src/hooks/kernel32/inject.c @@ -0,0 +1,83 @@ +#include "inject.h" +#include "../../patch.h" +#include "../../inject.h" +#include "../../ntdll.h" + +HMODULE hKernel32Module = NULL; +PFNISWOW64PROCESSPROC pIsWow64Process = NULL; +PFNCREATEPROCESSAPROC pCreateProcessA = NULL; + +/** + * CreateProcessAHook creates a process and hooks it with our library. This is + * mainly used to kill GameGuard.des, but we can use it for all kinds of + * shenanigans. + */ +BOOL STDCALL CreateProcessAHook(LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation) { + BOOL result; + BOOL injectAtEntry = FALSE; + BOOL needResume = FALSE; + BOOL weAreWow = FALSE, theyAreWow = FALSE; + + // Kills off a weird GameGuard call that makes the game more annoying in + // Wine (because it crashes.) For some reason, GameGuard tries to run: + // cmd /c "dxdiag /whql:off /x ./gameguard/npsys.des" + if (lpCommandLine && lpCommandLine[0] == 'c' && lpCommandLine[1] == 'm' && lpCommandLine[2] == 'd' && lpCommandLine[3] == ' ') { + return FALSE; + } + + Log("CreateProcessA(%s, %s, %08x, %08x, %d, %08x, %p, %s, %p, %p);\r\n", lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation); + + // We may need to keep the process suspended if that is requested. + needResume = (dwCreationFlags & CREATE_SUSPENDED) == 0; + + // We always need to create suspended. + dwCreationFlags &= CREATE_SUSPENDED; + + if (needResume && LoadNTDLL()) { + // Inject the DLL after the process hits its original entrypoint. + // More reliable but more complicated and needs internal undocumented + // APIs. We can't do this for suspended createprocess because it would + // muck with the state of the main thread too much. + + injectAtEntry = TRUE; + } + + // Run original CreateProcessA. If it fails, we can just return early. + result = pCreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation); + if (!result) { + return result; + } + + if (pIsWow64Process) { + pIsWow64Process(GetCurrentProcess(), &weAreWow); + pIsWow64Process(lpProcessInformation->hProcess, &theyAreWow); + } + + // Be careful: We can't inject ourselves if our WoW status differs. + // This stops Internet Explorer from being injected and crashing. + // If you want to inject into a 64-bit process, you will need a 64-bit + // DLL to inject. + if (weAreWow == theyAreWow) { + if (injectAtEntry) { + // This is more complicated, but more reliable. If we don't want for + // the entrypoint, the process space will be nearly entirely + // uninitialized, meaning nothing is guaranteed to work. If we inject + // in this state, it may not work (It doesn't work on Windows XP.) + JumpToEntrypoint(lpProcessInformation->hProcess, lpProcessInformation->hThread); + } + + InjectProcess(lpProcessInformation->hProcess, GetSelfPath()); + } + + if (needResume) { + ResumeThread(lpProcessInformation->hThread); + } + + return result; +} + +VOID InitInjectHook() { + hKernel32Module = LoadLib("kernel32"); + pIsWow64Process = GetProc(hKernel32Module, "IsWow64Process"); + pCreateProcessA = HookFunc(CreateProcessA, CreateProcessAHook); +} diff --git a/src/hooks/kernel32/inject.h b/src/hooks/kernel32/inject.h new file mode 100644 index 0000000..c3dafc8 --- /dev/null +++ b/src/hooks/kernel32/inject.h @@ -0,0 +1,8 @@ +#ifndef HOOKS_KERNEL32_INJECT_H +#define HOOKS_KERNEL32_INJECT_H + +#include "../../common.h" + +VOID InitInjectHook(); + +#endif diff --git a/src/hooks/user32/window.c b/src/hooks/user32/window.c new file mode 100644 index 0000000..6525955 --- /dev/null +++ b/src/hooks/user32/window.c @@ -0,0 +1,17 @@ +#include "window.h" +#include "../../patch.h" + +PFNCREATEWINDOWEXAPROC pCreateWindowExA = NULL; + +/** + * CreateWindowExAHook is a convenience patch that prevents PangYa from + * creating topmost windows. + */ +HWND STDCALL CreateWindowExAHook(DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam) { + dwExStyle &= (~WS_EX_TOPMOST); + return pCreateWindowExA(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam); +} + +VOID InitWindowHook() { + pCreateWindowExA = HookFunc(CreateWindowExA, CreateWindowExAHook); +} diff --git a/src/hooks/user32/window.h b/src/hooks/user32/window.h new file mode 100644 index 0000000..1a997cb --- /dev/null +++ b/src/hooks/user32/window.h @@ -0,0 +1,8 @@ +#ifndef HOOKS_USER32_WINDOW_H +#define HOOKS_USER32_WINDOW_H + +#include "../../common.h" + +VOID InitWindowHook(); + +#endif diff --git a/src/hooks/wininet/netredir.c b/src/hooks/wininet/netredir.c new file mode 100644 index 0000000..33f0460 --- /dev/null +++ b/src/hooks/wininet/netredir.c @@ -0,0 +1,53 @@ +#include "netredir.h" +#include "../../patch.h" + +HMODULE hWinINet = NULL; +PFNINTERNETOPENURLAPROC pInternetOpenUrlA = NULL; + +VOID RewriteURLHost(LPCSTR url, LPSTR buffer, LPCSTR host) { + // TODO(john): should implement bounds checking or dynamic buffer. + + // Copy scheme + while (*url && *url != '/') { + *buffer++ = *url++; + } + + // Copy slashes + if (!*url) return; + *buffer++ = *url++; + if (!*url) return; + *buffer++ = *url++; + + // Insert new hostname + while (*host) *buffer++ = *host++; + + // Skip hostname + while (*url && *url != ':' && *url != '/') url++; + + // Override port 80 -> 8080 for convenience. + if (*url != ':') { + *buffer++ = ':'; + *buffer++ = '8'; + *buffer++ = '0'; + *buffer++ = '8'; + *buffer++ = '0'; + } + + // Copy remainder + while (*url) *buffer++ = *url++; +} + +/** + * InternetOpenUrlAHook redirects HTTP calls to localhost. + */ +HINTERNET STDCALL InternetOpenUrlAHook(HINTERNET hInternet, LPCSTR lpszUrl, LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext) { + CHAR newURL[256] = {0}; + RewriteURLHost(lpszUrl, newURL, "127.0.0.1"); + Log("InternetOpenUrlA(%s -> %s)\r\n", lpszUrl, newURL); + return pInternetOpenUrlA(hInternet, newURL, lpszHeaders, dwHeadersLength, dwFlags, dwContext); +} + +VOID InitNetRedirHook() { + hWinINet = LoadLib("wininet"); + pInternetOpenUrlA = HookProc(hWinINet, "InternetOpenUrlA", InternetOpenUrlAHook); +} diff --git a/src/hooks/wininet/netredir.h b/src/hooks/wininet/netredir.h new file mode 100644 index 0000000..4d9403a --- /dev/null +++ b/src/hooks/wininet/netredir.h @@ -0,0 +1,8 @@ +#ifndef HOOKS_WININET_NETREDIR_H +#define HOOKS_WININET_NETREDIR_H + +#include "../../common.h" + +VOID InitNetRedirHook(); + +#endif diff --git a/src/hooks/ws2_32/redir.c b/src/hooks/ws2_32/redir.c new file mode 100644 index 0000000..9a329fa --- /dev/null +++ b/src/hooks/ws2_32/redir.c @@ -0,0 +1,25 @@ +#include "redir.h" +#include "../../patch.h" + +HMODULE hWinsock = NULL; +PFNCONNECTPROC pConnect = NULL; +struct in_addr connectAddr = {127, 0, 0, 1}; + +/** + * ConnectHook redirects Winsock TCP sockets to localhost. + */ +int STDCALL ConnectHook(SOCKET s, const struct sockaddr *name, int namelen) { + struct sockaddr_in name_in = *(struct sockaddr_in*)name; + struct sockaddr_in override_in = {0}; + char *addr = (char*)&override_in.sin_addr; + override_in.sin_family = AF_INET; + override_in.sin_port = name_in.sin_port; + override_in.sin_addr = connectAddr; + Log("connect(0x%08x, %d.%d.%d.%d:%d)\r\n", s, addr[0], addr[1], addr[2], addr[3], name_in.sin_port); + return pConnect(s, (struct sockaddr*)&override_in, sizeof(struct sockaddr_in)); +} + +VOID InitRedirHook() { + hWinsock = LoadLib("ws2_32"); + pConnect = HookProc(hWinsock, "connect", ConnectHook); +} diff --git a/src/hooks/ws2_32/redir.h b/src/hooks/ws2_32/redir.h new file mode 100644 index 0000000..f3449ce --- /dev/null +++ b/src/hooks/ws2_32/redir.h @@ -0,0 +1,8 @@ +#ifndef HOOKS_WS2_32_REDIR_H +#define HOOKS_WS2_32_REDIR_H + +#include "../../common.h" + +VOID InitRedirHook(); + +#endif diff --git a/src/ijlfwd.c b/src/ijlfwd.c new file mode 100644 index 0000000..5c59025 --- /dev/null +++ b/src/ijlfwd.c @@ -0,0 +1,38 @@ +/* + * Forwards ijl15 API calls down to ijl15_real, allowing this library to be + * a drop-in replacement for ijl15. + * + * TODO(john): Instead, we should probably just patch our code into the + * existing ijl15 DLL... but that takes a bit more work. + */ + +#include "ijlfwd.h" + +HMODULE hIJL15Module = NULL; +PFNIJLGETLIBVERSIONPROC pIJLGetLibVersion = NULL; +PFNIJLINITPROC pIJLInit = NULL; +PFNIJLFREEPROC pIJLFree = NULL; +PFNIJLREADPROC pIJLRead = NULL; +PFNIJLWRITEPROC pIJLWrite = NULL; +PFNIJLERRORSTRPROC pIJLErrorStr = NULL; + +int STDCALL ijlGetLibVersion() { return pIJLGetLibVersion(); } +int STDCALL ijlInit (int a) { return pIJLInit (a); } +int STDCALL ijlFree (int a) { return pIJLFree (a); } +int STDCALL ijlRead (int a, int b) { return pIJLRead (a, b); } +int STDCALL ijlWrite (int a, int b) { return pIJLWrite (a, b); } +int STDCALL ijlErrorStr (int err) { return pIJLErrorStr (err); } + +VOID InitIJL15() { + if (hIJL15Module != NULL) { + FatalError("Error: ijl15 is already initialized!"); + } + + hIJL15Module = LoadLib("ijl15_real"); + pIJLGetLibVersion = (PFNIJLGETLIBVERSIONPROC)GetProc(hIJL15Module, "ijlGetLibVersion"); + pIJLInit = (PFNIJLINITPROC )GetProc(hIJL15Module, "ijlInit"); + pIJLFree = (PFNIJLFREEPROC )GetProc(hIJL15Module, "ijlFree"); + pIJLRead = (PFNIJLREADPROC )GetProc(hIJL15Module, "ijlRead"); + pIJLWrite = (PFNIJLWRITEPROC )GetProc(hIJL15Module, "ijlWrite"); + pIJLErrorStr = (PFNIJLERRORSTRPROC )GetProc(hIJL15Module, "ijlErrorStr"); +} diff --git a/src/ijlfwd.h b/src/ijlfwd.h new file mode 100644 index 0000000..cd3ca35 --- /dev/null +++ b/src/ijlfwd.h @@ -0,0 +1,15 @@ +#ifndef IJL15_H +#define IJL15_H + +#include "common.h" + +typedef int(STDCALL *PFNIJLGETLIBVERSIONPROC)(); +typedef int(STDCALL *PFNIJLINITPROC )(int); +typedef int(STDCALL *PFNIJLFREEPROC )(int); +typedef int(STDCALL *PFNIJLREADPROC )(int, int); +typedef int(STDCALL *PFNIJLWRITEPROC )(int, int); +typedef int(STDCALL *PFNIJLERRORSTRPROC )(int); + +VOID InitIJL15(); + +#endif diff --git a/src/inject.c b/src/inject.c new file mode 100644 index 0000000..61b6e5a --- /dev/null +++ b/src/inject.c @@ -0,0 +1,285 @@ +/* + * This file contains code used for injecting + */ + +#include "inject.h" +#include "ntdll.h" +#include "patch.h" +#include + +const IMAGE_ORDINAL_FLAG32 = 0x80000000; + +typedef struct _DLL_INJECT { + PVOID ImageBase; + PIMAGE_NT_HEADERS NtHeaders; + PIMAGE_BASE_RELOCATION BaseRelocation; + PIMAGE_IMPORT_DESCRIPTOR ImportDirectory; + PFNLOADLIBRARYAPROC LoadLibraryA; + PFNGETPROCADDRESSPROC GetProcAddress; +} DLL_INJECT, *PDLL_INJECT; + +/** + * Routine loads a DLL manually. The general algorithm is based on a + * Stack Overflow answer by user SSpoke: + * https://stackoverflow.com/a/55779290 + */ +DWORD WINAPI LoadDll(PVOID p) { + PDLL_INJECT injectData; + HMODULE hModule, hKernel32; + DWORD dwBaseDelta; + PIMAGE_BASE_RELOCATION pIBR; + PIMAGE_IMPORT_DESCRIPTOR pIID; + PIMAGE_IMPORT_BY_NAME pIBN; + PFNDLLMAINPROC pfnEntryPoint; + + injectData = (PDLL_INJECT)p; + pIBR = injectData->BaseRelocation; + dwBaseDelta = (DWORD)((LPBYTE)injectData->ImageBase - injectData->NtHeaders->OptionalHeader.ImageBase); + + // Relocate the image + while (pIBR->VirtualAddress) { + if (pIBR->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION)) { + DWORD i = 0; + DWORD dwCount = (pIBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD); + PWORD pwList = (PWORD)(pIBR + 1); + PDWORD pdwPtr; + + for (i = 0; i < dwCount; i++) { + if (pwList[i]) { + pdwPtr = (PDWORD)((LPBYTE)injectData->ImageBase + (pIBR->VirtualAddress+(pwList[i] & 0xFFF))); + *pdwPtr += dwBaseDelta; + } + } + } + + pIBR = (PIMAGE_BASE_RELOCATION)((LPBYTE)pIBR + pIBR->SizeOfBlock); + } + + // Perform runtime linking. + pIID = injectData->ImportDirectory; + while (pIID->Characteristics) { + PIMAGE_THUNK_DATA FirstThunk, OrigFirstThunk; + DWORD dwFnPtrAddr; + + OrigFirstThunk = (PIMAGE_THUNK_DATA)((LPBYTE)injectData->ImageBase + pIID->OriginalFirstThunk); + FirstThunk = (PIMAGE_THUNK_DATA)((LPBYTE)injectData->ImageBase + pIID->FirstThunk); + + hModule = injectData->LoadLibraryA((LPCSTR)injectData->ImageBase + pIID->Name); + if (!hModule) { + return FALSE; + } + + while (OrigFirstThunk->u1.AddressOfData) { + if (OrigFirstThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32) { + // Function should be imported using ordinals. + dwFnPtrAddr = (DWORD)injectData->GetProcAddress(hModule, (LPCSTR)(OrigFirstThunk->u1.Ordinal & 0xFFFF)); + if (!dwFnPtrAddr) { + return FALSE; + } + FirstThunk->u1.Function = dwFnPtrAddr; + } else { + // Function should be imported using name. + pIBN = (PIMAGE_IMPORT_BY_NAME)((LPBYTE)injectData->ImageBase + OrigFirstThunk->u1.AddressOfData); + dwFnPtrAddr = (DWORD)injectData->GetProcAddress(hModule, (LPCSTR)pIBN->Name); + if (!dwFnPtrAddr) { + return FALSE; + } + FirstThunk->u1.Function = dwFnPtrAddr; + } + OrigFirstThunk++; + FirstThunk++; + } + pIID++; + } + + if (injectData->NtHeaders->OptionalHeader.AddressOfEntryPoint) { + pfnEntryPoint = (PFNDLLMAINPROC)((LPBYTE)injectData->ImageBase + injectData->NtHeaders->OptionalHeader.AddressOfEntryPoint); + return pfnEntryPoint((HMODULE)injectData->ImageBase,DLL_PROCESS_ATTACH,NULL); + } + + return TRUE; +} + +DWORD WINAPI LoadDllEnd() { + return 0; +} + +/** + * Routine injects the DLL loading routine and runs it in a remote process. + * The general algorithm is based on a Stack Overflow answer by user SSpoke: + * https://stackoverflow.com/a/55779290 + */ +VOID InjectProcess(HANDLE hProcess, LPCSTR dllName) { + PIMAGE_DOS_HEADER pIDH; + PIMAGE_NT_HEADERS pINH; + PIMAGE_SECTION_HEADER pISH; + HANDLE hThread, hFile; + PVOID pvBuffer, pvImage, pvMem; + DWORD dwFileSize, dwExitCode, dwRead, i; + DLL_INJECT injectData = { 0 }; + + hFile = CreateFile(dllName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + FatalError("Failed to open the DLL (%08x)", GetLastError()); + } + + dwFileSize = GetFileSize(hFile, NULL); + pvBuffer = VirtualAlloc(NULL, dwFileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + + if (!pvBuffer) { + FatalError("Failed to allocate memory for DLL data (%08x)", GetLastError()); + } + + // Read the DLL + if (!ReadFile(hFile, pvBuffer, dwFileSize, &dwRead, NULL)) { + FatalError("Failed to read the DLL (%08x)", GetLastError()); + } + + CloseHandle(hFile); + + pIDH = (PIMAGE_DOS_HEADER)pvBuffer; + + if (pIDH->e_magic != IMAGE_DOS_SIGNATURE) { + FatalError("Error: Invalid executable image."); + } + + pINH = (PIMAGE_NT_HEADERS)((LPBYTE)pvBuffer+pIDH->e_lfanew); + if (pINH->Signature != IMAGE_NT_SIGNATURE) { + FatalError("Error: Invalid PE header."); + } + if ((pINH->FileHeader.Characteristics & IMAGE_FILE_DLL) != IMAGE_FILE_DLL) { + FatalError("Error: The image is not DLL."); + } + + // Allocate memory for the DLL. + pvImage = VirtualAllocEx(hProcess, NULL, pINH->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (!pvImage) { + FatalError("Error: Unable to allocate memory for the DLL (%d)", GetLastError()); + } + + // Copy the header to target process + if (!WriteProcessMemory(hProcess, pvImage, pvBuffer, pINH->OptionalHeader.SizeOfHeaders, NULL)) { + FatalError("Error: Unable to copy headers to target process (%d)", GetLastError()); + } + + pISH = (PIMAGE_SECTION_HEADER)(pINH + 1); + + // Copy the DLL to target process + for (i = 0; i < pINH->FileHeader.NumberOfSections; i++) { + WriteProcessMemory(hProcess, (PVOID)((LPBYTE)pvImage + pISH[i].VirtualAddress), (PVOID)((LPBYTE)pvBuffer + pISH[i].PointerToRawData), pISH[i].SizeOfRawData, NULL); + } + + // Allocate memory for the loader code + pvMem = VirtualAllocEx(hProcess, NULL, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + + if (!pvMem) { + FatalError("Error: Unable to allocate memory for the loader code (%d)", GetLastError()); + } + + injectData.ImageBase = pvImage; + injectData.NtHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)pvImage + pIDH->e_lfanew); + injectData.BaseRelocation = (PIMAGE_BASE_RELOCATION)((LPBYTE)pvImage + pINH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); + injectData.ImportDirectory = (PIMAGE_IMPORT_DESCRIPTOR)((LPBYTE)pvImage + pINH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); + injectData.LoadLibraryA = LoadLibraryA; + injectData.GetProcAddress = GetProcAddress; + + // Write the injection data to the target process. + WriteProcessMemory(hProcess, pvMem, &injectData, sizeof(DLL_INJECT), NULL); + + // Write the loading routine to the target process. + WriteProcessMemory(hProcess, (PVOID)((PDLL_INJECT)pvMem + 1), LoadDll, (DWORD)LoadDllEnd - (DWORD)LoadDll, NULL); + + // Create a remote thread to execute the loader code. + hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)((PDLL_INJECT)pvMem + 1), pvMem, 0, NULL); + if (!hThread) { + FatalError("Error: Unable to execute loader code (%d)", GetLastError()); + } + + WaitForSingleObject(hThread, INFINITE); + GetExitCodeThread(hThread, &dwExitCode); + if (!dwExitCode) { + FatalError("Error: Loader returned error (%d)", GetLastError()); + } + + CloseHandle(hThread); + VirtualFreeEx(hProcess,pvMem, 0, MEM_RELEASE); + VirtualFree(pvBuffer, 0, MEM_RELEASE); +} + +/** + * GetPeb finds the PEB address of a remote process. + */ +PPEB GetPeb(HANDLE ProcessHandle) { + PROCESS_BASIC_INFORMATION processInfo = {0}; + NTSTATUS status; + PPEB pPeb; + + status = NtQueryInformationProcess(ProcessHandle, 0x0, &processInfo, sizeof(processInfo), NULL); + if (!NT_SUCCESS(status)) { + return NULL; + } + + return processInfo.PebBaseAddress; +} + +/** + * FindEntrypoint finds the entrypoint of a remote process. This works even if + * the process is newly created and most things are not initialized yet. + */ +DWORD FindEntrypoint(HANDLE hProcess) { + const bPeHeaderAddrOff = offsetof(IMAGE_DOS_HEADER, e_lfanew); + const bPeEntryPointOff = offsetof(IMAGE_NT_HEADERS, OptionalHeader.AddressOfEntryPoint); + + PPEB pPeb; + PVOID pImage, pEntry; + PIMAGE_NT_HEADERS pNtHeaders; + LONG peHeaderAddr; + SIZE_T NumberOfBytesRead; + + pPeb = GetPeb(hProcess); + + if (!ReadProcessMemory(hProcess, &pPeb->Reserved3[1], &pImage, sizeof(pImage), NULL)) { + FatalError("ReadProcessMemory failed (%08x)", GetLastError()); + } + + if (!ReadProcessMemory(hProcess, (PCHAR)pImage + bPeHeaderAddrOff, &peHeaderAddr, sizeof(peHeaderAddr), NULL)) { + FatalError("ReadProcessMemory failed (%08x)", GetLastError()); + } + + pNtHeaders = (PIMAGE_NT_HEADERS)((PCHAR)pImage + peHeaderAddr); + if (!ReadProcessMemory(hProcess, (PCHAR)pNtHeaders + bPeEntryPointOff, &pEntry, sizeof(pEntry), NULL)) { + FatalError("ReadProcessMemory failed (%08x)", GetLastError()); + } + + pEntry = (PVOID)((PCHAR)pImage + (SIZE_T)pEntry); + + return (DWORD)pEntry; +} + +/** + * JumpToEntrypoint attempts to resume a process until it hits the breakpoint, + * then suspend it again. This ensures the process space is initialized enough + * for us to inject code in older NT-based OSes (like Windows XP.) + */ +VOID JumpToEntrypoint(HANDLE hProcess, HANDLE hThread) { + CONTEXT context = {0}; + BYTE pbInfLoop[2] = {0xEB, 0xFE}; + BYTE pbOldEntry[3] = {0x00, 0x00}; + DWORD bEntry, i; + + // Patch the entrypoint. + bEntry = FindEntrypoint(hProcess); + RemotePatch(hProcess, bEntry, pbInfLoop, pbOldEntry, 2); + ResumeThread(hThread); + + // Poll until we see the process at the entrypoint. + for (i = 0; i < 100 && context.Eip != bEntry; ++i) { + Sleep(50); + context.ContextFlags = CONTEXT_CONTROL; + GetThreadContext(hThread, &context); + } + + // Suspend thread and unpatch. + SuspendThread(hThread); + RemotePatch(hProcess, bEntry, pbOldEntry, NULL, 2); +} diff --git a/src/inject.h b/src/inject.h new file mode 100644 index 0000000..74e9dfd --- /dev/null +++ b/src/inject.h @@ -0,0 +1,10 @@ +#ifndef INJECT_H +#define INJECT_H + +#include "common.h" + +VOID InjectProcess(HANDLE hProcess, LPCSTR pszDllName); + +VOID JumpToEntrypoint(HANDLE hProcess, HANDLE hThread); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..54f52d5 --- /dev/null +++ b/src/main.c @@ -0,0 +1,134 @@ +/** + * This is a shim for ijl15.dll that hooks various things. Its objectives are: + * + * - To fully disable GameGuard. + * - To make using unmodified PangYa with custom servers easier. + * + * As much as possible is accomplished by hooking Windows APIs, making many of + * the patches portable across Pangya versions. The only bits that aren't + * implemented this way are a few bits related to disabling GameGuard, due to + * the fact that the process will attempt to kill itself if GameGuard is not + * present. + */ + +#include "common.h" +#include "ijlfwd.h" +#include "hooks/hooks.h" + +/** + * InitEnvironment configures the PANGYA_ARG environment to avoid needing to + * run the updater first. + */ +VOID InitEnvironment() { + PANGYAVER pangyaVersion; + PSTR szPangyaArg; + + pangyaVersion = DetectPangyaVersion(); + szPangyaArg = GetPangyaArg(pangyaVersion); + + if (SetEnvironmentVariableA("PANGYA_ARG", szPangyaArg) == 0) { + FatalError("Couldn't set PANGYA_ARG (%08x)", GetLastError()); + } + + LocalFree(szPangyaArg); +} + +/** + * Patch is a small routine for patching arbitrary memory. + */ +VOID Patch(LPVOID dst, LPVOID src, DWORD size) { + DWORD OldProtection; + VirtualProtect(dst, size, PAGE_EXECUTE_READWRITE, &OldProtection); + memcpy(dst, src, size); + VirtualProtect(dst, size, OldProtection, &OldProtection); +} + +/** + * Implements the GameGuard patches for Pangya US 852.00. + */ +VOID PatchGG_US852(LPVOID param) { + while(1) { + // TODO(john): Remove hardcoded addresses. + if (*(DWORD*)0x00A495E0 == 0x8F143D83) { + Patch((LPVOID)0x00A495E0, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A49670, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A49690, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A496B0, "\x90\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A496E0, "\xC3", 1); + Patch((LPVOID)0x00A49840, "\xC3", 1); + Log("Patched GG check routines (Pangya US 852)\r\n"); + return; + } + Sleep(5); + } +} + +/** + * Implements the GameGuard patches for Pangya JP 972.00. + */ +VOID PatchGG_JP972(LPVOID param) { + while(1) { + // TODO(john): Remove hardcoded addresses. + if (*(DWORD*)0x00A5CD10 == 0x1BA43D83) { + Patch((LPVOID)0x00A5CD10, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A5CDA0, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A5CDC0, "\xC3\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A5CDE0, "\x90\x90\x90\x90\x90\x90\x90", 7); + Patch((LPVOID)0x00A5CE10, "\xC3", 1); + Patch((LPVOID)0x00A5CE40, "\xC3", 1); + Log("Patched GG check routines (Pangya JP 972)\r\n"); + return; + } + Sleep(5); + } +} + +/** + * Initializes the GameGuard patches based on game version. + */ +VOID InitGGPatch() { + PANGYAVER pangyaVersion; + LPTHREAD_START_ROUTINE patchThread = NULL; + + // TODO(john): Should support more versions of PangYa. + pangyaVersion = DetectPangyaVersion(); + switch (pangyaVersion) { + case PANGYA_US: + patchThread = (LPTHREAD_START_ROUTINE)PatchGG_US852; + break; + case PANGYA_JP: + patchThread = (LPTHREAD_START_ROUTINE)PatchGG_JP972; + break; + } + + if (!patchThread) { + MessageBoxA(NULL, "It looks like no patch exists for this version of PangYa.\nThe game will likely exit a couple minutes after detecting GameGuard is not present.", "rugburn", MB_OK); + return; + } + + CreateThread(0, 0, patchThread, 0, 0, 0); +} + +extern BOOL STDCALL DllMain(HANDLE hInstance, DWORD dwReason, LPVOID reserved) { + if (dwReason != DLL_PROCESS_ATTACH) { + return TRUE; + } + + LogInit(); + + if (StrCmpA(pszSelfName, "GameGuard.des") == 0) { + ExitProcess(0x755); + } + + // TODO(john): how do we reason about whether we're PangYa or not? + // Just looking at whether the filename is ProjectG or not is not very + // reliable, that would be annoying. For now we just treat everything + // that isn't GameGuard as ProjectG... + + InitGGPatch(); + InitIJL15(); + InitEnvironment(); + InitHooks(); + + return TRUE; +} diff --git a/src/ntdll.c b/src/ntdll.c new file mode 100644 index 0000000..9e70504 --- /dev/null +++ b/src/ntdll.c @@ -0,0 +1,28 @@ +#include "ntdll.h" + +HMODULE hNTDLLModule = NULL; + +PFNNTQUERYINFORMATIONPROCESSPROC NtQueryInformationProcess = NULL; + +BOOL LoadNTDLL() { + if (hNTDLLModule != NULL) { + return TRUE; + } + + hNTDLLModule = LoadLib("ntdll"); + if (hNTDLLModule == NULL) { + return FALSE; + } + + NtQueryInformationProcess = GetProc(hNTDLLModule, "NtQueryInformationProcess"); + if (NtQueryInformationProcess == NULL) { + goto errFree; + } + + return TRUE; + +errFree: + FreeLibrary(hNTDLLModule); + hNTDLLModule = NULL; + return FALSE; +} diff --git a/src/ntdll.h b/src/ntdll.h new file mode 100644 index 0000000..9fa70b1 --- /dev/null +++ b/src/ntdll.h @@ -0,0 +1,26 @@ +#ifndef NTDLL_H +#define NTDLL_H + +#include "common.h" + +typedef struct _PEB +{ + BYTE Reserved1[2]; + BYTE BeingDebugged; + BYTE Reserved2[1]; + PVOID Reserved3[2]; +} PEB, *PPEB; + +typedef struct _PROCESS_BASIC_INFORMATION { + PVOID Reserved1; + PPEB PebBaseAddress; + PVOID Reserved2[2]; + ULONG_PTR UniqueProcessId; + PVOID Reserved3; +} PROCESS_BASIC_INFORMATION; + +extern PFNNTQUERYINFORMATIONPROCESSPROC NtQueryInformationProcess; + +BOOL LoadNTDLL(); + +#endif diff --git a/src/patch.c b/src/patch.c new file mode 100644 index 0000000..e31171f --- /dev/null +++ b/src/patch.c @@ -0,0 +1,158 @@ +#include "patch.h" +#include "third_party/lend/ld32.h" + +/** + * Writes data into the remote process. + */ +VOID RemotePatch(HANDLE hProcess, DWORD dwAddr, PBYTE pbData, PBYTE pbBackup, DWORD cbData) { + DWORD dwOldProtect; + + // Unprotect function. + if (VirtualProtectEx(hProcess, (LPVOID)dwAddr, cbData, PAGE_EXECUTE_READWRITE, &dwOldProtect) == 0) { + FatalError("Failed to remote patch: VirtualProtect failed. (%08x)", GetLastError()); + } + + // Optional: Backup remote memory. + if (pbBackup) { + if (!ReadProcessMemory(hProcess, (LPVOID)dwAddr, pbBackup, cbData, NULL)) { + FatalError("Failed to remote patch: ReadProcessMemory failed. (%08x)", GetLastError()); + } + } + + // Patch remote memory. + if (!WriteProcessMemory(hProcess, (LPVOID)dwAddr, pbData, cbData, NULL)) { + FatalError("Failed to remote patch: WriteProcessMemory failed. (%08x)", GetLastError()); + } + + // Re-protect function. + if (VirtualProtectEx(hProcess, (LPVOID)dwAddr, cbData, dwOldProtect, &dwOldProtect) == 0) { + FatalError("Failed to remote patch: VirtualProtect failed. (%08x)", GetLastError()); + } + + // Flush the icache. Otherwise, it is theoretically possible that our + // patch will not work consistently. + if (FlushInstructionCache(hProcess, (LPVOID)dwAddr, cbData) == 0) { + FatalError("Failed to remote patch: FlushInstructionCache failed. (%08x)", GetLastError()); + } +} + +/** + * Installs a hook that redirects a function to a different function with a + * compatible signature. This will destroy the first 6 bytes of the function, + * so you will need to build a trampoline before installing the hook if you + * want to be able to call the original function again. + */ +VOID InstallHook(PVOID pfnProc, PVOID pfnTargetProc) { + DWORD dwOldProtect; + DWORD dwRelAddr; + CHAR pbHook[6] = {0xE9, 0x00, 0x00, 0x00, 0x00, 0xC3}; + + // Unprotect function. + if (VirtualProtect(pfnProc, 6, PAGE_EXECUTE_READWRITE, &dwOldProtect) == 0) { + FatalError("Failed to install hook: VirtualProtect failed. (%08x)", GetLastError()); + } + + // Create and install hook. + dwRelAddr = ((DWORD)pfnTargetProc - (DWORD)pfnProc - 5); + memcpy(&pbHook[1], &dwRelAddr, 4); + if (!WriteProcessMemory(GetCurrentProcess(), pfnProc, pbHook, 6, NULL)) { + FatalError("Failed to install hook: WriteProcessMemory failed. (%08x)", GetLastError()); + } + + // Re-protect function. + if (VirtualProtect(pfnProc, 6, dwOldProtect, &dwOldProtect) == 0) { + FatalError("Failed to install hook: VirtualProtect failed. (%08x)", GetLastError()); + } + + // Flush the icache. Otherwise, it is theoretically possible that our + // patch will not work consistently. + if (FlushInstructionCache(GetCurrentProcess(), pfnProc, 6) == 0) { + FatalError("Failed to install hook: FlushInstructionCache failed. (%08x)", GetLastError()); + } +} + +/** + * Counts at least minBytes bytes worth of instructions, ending at an + * instruction boundary. + */ +DWORD CountOpcodeBytes(FARPROC fn, DWORD minBytes) { + PBYTE fndata = (PBYTE)fn; + DWORD count = 0; + + while (count < minBytes) { + count += length_disasm(&fndata[count]); + } + + return count; +} + +/** + * Builds a trampoline to be able to call a function that has been hooked. + * Conceptually, it takes prefixLen bytes (at least 6 bytes) from the original + * function, then places them into a small block of code that jumps that many + * bytes into the original function call. prefixLen needs to be longer than 6, + * but must end on an instruction boundary. In addition, this approach is + * naive and won't always work well, though for most functions the prefix will + * be in the prologue and should be safe. + */ +PCHAR BuildTrampoline(DWORD fn, DWORD prefixLen) { + DWORD trampolineLen; + DWORD oldProtect; + DWORD relAddr; + PCHAR codeblock; + + // Allocate a block of memory. We need to fit the prefix + a jump. + // Extra byte is for a return so that the instruction after the jump will + // be valid. I'm not sure if this is strictly necessary. + trampolineLen = prefixLen + 6; + codeblock = LocalAlloc(0, trampolineLen); + + // Copy the prefix into our newly minted codeblock. + memcpy(codeblock, (void *)fn, prefixLen); + + // Calculate the jump address. We want to jump into the function at the same + // point we left off here, so we can just subtract the size of the jmp + // instruction and otherwise it's a flat subtraction. + relAddr = (DWORD)fn - (DWORD)codeblock - 5; + + // Create our jump instruction. + codeblock[prefixLen] = 0xE9; + memcpy(&codeblock[prefixLen + 1], &relAddr, 4); + + // ...and a return at the end, for good measure. + codeblock[prefixLen + 5] = 0xC3; + + // Mark the codeblock as executable. + VirtualProtect(codeblock, trampolineLen, PAGE_EXECUTE_READWRITE, &oldProtect); + + return codeblock; +} + +/** + * Creates a trampoline then hooks the provided function to call the target + * instead. + */ +PVOID HookFunc(PVOID pfnProc, PVOID pfnTargetProc) { + DWORD prefixLen, trampoline; + + prefixLen = CountOpcodeBytes(pfnProc, 6); + + trampoline = (DWORD)BuildTrampoline((DWORD)pfnProc, prefixLen); + + InstallHook((PCHAR)pfnProc, pfnTargetProc); + + return (PVOID)trampoline; +} + +/** + * Hooks a procedure in a module. + */ +PVOID HookProc(HMODULE hModule, LPCSTR szName, PVOID pfnTargetProc) { + PVOID pfnLibraryProc, pfnTrampolineProc; + + pfnLibraryProc = GetProc(hModule, szName); + + pfnTrampolineProc = HookFunc(pfnLibraryProc, pfnTargetProc); + + return pfnTrampolineProc; +} diff --git a/src/patch.h b/src/patch.h new file mode 100644 index 0000000..428be45 --- /dev/null +++ b/src/patch.h @@ -0,0 +1,13 @@ +#ifndef PATCH_H +#define PATCH_H + +#include "common.h" + +VOID RemotePatch(HANDLE hProcess, DWORD dwAddr, PBYTE pbData, PBYTE pbBackup, DWORD cbData); +VOID InstallHook(PVOID pfnProc, PVOID pfnTargetProc); +DWORD CountOpcodeBytes(FARPROC fn, DWORD minBytes); +PCHAR BuildTrampoline(DWORD fn, DWORD prefixLen); +PVOID HookFunc(PVOID pfnProc, PVOID pvTargetProc); +PVOID HookProc(HMODULE hModule, LPCSTR szName, PVOID pfnTargetProc); + +#endif diff --git a/src/third_party/lend/COPYING b/src/third_party/lend/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/src/third_party/lend/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/third_party/lend/ld32.c b/src/third_party/lend/ld32.c new file mode 100644 index 0000000..bd21689 --- /dev/null +++ b/src/third_party/lend/ld32.c @@ -0,0 +1,80 @@ +/* +x86 Length Disassembler. +Copyright (C) 2013 Byron Platt + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "ld32.h" + +/* length_disasm */ +unsigned int length_disasm(void * opcode0) { + + unsigned char* opcode = opcode0; + + unsigned int flag = 0; + unsigned int ddef = 4, mdef = 4; + unsigned int msize = 0, dsize = 0; + + unsigned char op, modrm, mod, rm; + +prefix: + op = *opcode++; + + /* prefix */ + if (CHECK_PREFIX(op)) { + if (CHECK_PREFIX_66(op)) ddef = 2; + else if (CHECK_PREFIX_67(op)) mdef = 2; + goto prefix; + } + + /* two byte opcode */ + if (CHECK_0F(op)) { + op = *opcode++; + if (CHECK_MODRM2(op)) flag++; + if (CHECK_DATA12(op)) dsize++; + if (CHECK_DATA662(op)) dsize += ddef; + } + + /* one byte opcode */ + else { + if (CHECK_MODRM(op)) flag++; + if (CHECK_TEST(op) && !(*opcode & 0x38)) dsize += (op & 1) ? ddef : 1; + if (CHECK_DATA1(op)) dsize++; + if (CHECK_DATA2(op)) dsize += 2; + if (CHECK_DATA66(op)) dsize += ddef; + if (CHECK_MEM67(op)) msize += mdef; + } + + /* modrm */ + if (flag) { + modrm = *opcode++; + mod = modrm & 0xc0; + rm = modrm & 0x07; + if (mod != 0xc0) { + if (mod == 0x40) msize++; + if (mod == 0x80) msize += mdef; + if (mdef == 2) { + if ((mod == 0x00) && (rm == 0x06)) msize += 2; + } else { + if (rm == 0x04) rm = *opcode++ & 0x07; + if (rm == 0x05 && mod == 0x00) msize += 4; + } + } + } + + opcode += msize + dsize; + + return opcode - (unsigned char *)opcode0; +} diff --git a/src/third_party/lend/ld32.h b/src/third_party/lend/ld32.h new file mode 100644 index 0000000..ac19a8b --- /dev/null +++ b/src/third_party/lend/ld32.h @@ -0,0 +1,254 @@ +/* +x86 Length Disassembler. +Copyright (C) 2013 Byron Platt + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#ifndef __LD32_H__ +#define __LD32_H__ + +/* implemented tables */ +#define PREFIX_T 1 +#define MODRM2_T 2 +#define MODRM_T 4 +#define DATA1_T 8 +#define DATA2_T 16 +#define DATA66_T 32 + +/* configure tables */ +#ifndef USE_T +#define USE_T (MODRM2_T|MODRM_T|DATA1_T|DATA66_T) +#endif + +/* length_disasm */ +unsigned int length_disasm(void* opcode0); + +/* table macros */ +#ifdef USE_T +#define BITMASK32( \ + b00,b01,b02,b03,b04,b05,b06,b07, \ + b08,b09,b0a,b0b,b0c,b0d,b0e,b0f, \ + b10,b11,b12,b13,b14,b15,b16,b17, \ + b18,b19,b1a,b1b,b1c,b1d,b1e,b1f \ +) ( \ + (b00<<0x00)|(b01<<0x01)|(b02<<0x02)|(b03<<0x03)| \ + (b04<<0x04)|(b05<<0x05)|(b06<<0x06)|(b07<<0x07)| \ + (b08<<0x08)|(b09<<0x09)|(b0a<<0x0a)|(b0b<<0x0b)| \ + (b0c<<0x0c)|(b0d<<0x0d)|(b0e<<0x0e)|(b0f<<0x0f)| \ + (b10<<0x10)|(b11<<0x11)|(b12<<0x12)|(b13<<0x13)| \ + (b14<<0x14)|(b15<<0x15)|(b16<<0x16)|(b17<<0x17)| \ + (b18<<0x18)|(b19<<0x19)|(b1a<<0x1a)|(b1b<<0x1b)| \ + (b1c<<0x1c)|(b1d<<0x1d)|(b1e<<0x1e)|(b1f<<0x1f) \ +) +#define CHECK_TABLE(t, v) ((t[(v)>>5]>>((v)&0x1f))&1) +#endif + +/* CHECK_PREFIX */ +#if defined(USE_T) && (USE_T & PREFIX_T) +const static unsigned int prefix_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 0 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 1 */ + BITMASK32(0,0,0,0,0,0,1,0, 0,0,0,0,0,0,1,0, /* 2 */ + 0,0,0,0,0,0,1,0, 0,0,0,0,0,0,1,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, /* 6 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 7 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 8 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 9 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* a */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* b */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* c */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* d */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* e */ + 1,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0) /* f */ +}; +#define CHECK_PREFIX(v) CHECK_TABLE(prefix_t, v) +#else +#define CHECK_PREFIX(v) \ + (((v)&0xe7)==0x26||((v)&0xfc)==0x64||(v)==0xf0||(v)==0xf2||(v)==0xf3) +#endif + +/* CHECK_PREFIX_66 */ +#define CHECK_PREFIX_66(v) ((v)==0x66) + +/* CHECK_PREFIX_67 */ +#define CHECK_PREFIX_67(v) ((v)==0x67) + +/* CHECK_0F */ +#define CHECK_0F(v) ((v)==0x0f) + +/* CHECK_MODRM2 */ +#if defined(USE_T) && (USE_T & MODRM2_T) +const static unsigned int modrm2_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(1,1,1,1,0,0,0,0, 0,0,0,0,0,0,0,0, /* 0 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 1 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 2 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 6 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 7 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 8 */ + 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1), /* 9 */ + BITMASK32(0,0,0,1,1,1,0,0, 0,0,0,1,1,1,0,1, /* a */ + 1,1,1,1,1,1,1,1, 0,0,1,1,1,1,1,1), /* b */ + BITMASK32(1,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* c */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* d */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* e */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) /* f */ +}; +#define CHECK_MODRM2(v) CHECK_TABLE(modrm2_t, v) +#else +#define CHECK_MODRM2(v) (__extension__ ({ \ + register BYTE __a=(v)&0xfc, __b=(v)&0xfe; \ + ((v)&0xf0)==0x90||((v)&0xf8)==0xb0||((v)&0xf6)==0xa4|| \ + __a==0x00||__a==0xbc||__b==0xba||__b==0xc0|| \ + (v)==0xa3||(v)==0xab||(v)==0xaf; \ +})) +#endif + +/* CHECK_DATA12 */ +#define CHECK_DATA12(v) ((v)==0xa4||(v)==0xac||(v)==0xba) + +/* CHECK_DATA662 */ +#define CHECK_DATA662(v) (((v)&0xf0)==0x80) + +/* CHECK_MODRM */ +#if defined(USE_T) && (USE_T & MODRM_T) +const static unsigned int modrm_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(1,1,1,1,0,0,0,0, 1,1,1,1,0,0,0,0, /* 0 */ + 1,1,1,1,0,0,0,0, 1,1,1,1,0,0,0,0), /* 1 */ + BITMASK32(1,1,1,1,0,0,0,0, 1,1,1,1,0,0,0,0, /* 2 */ + 1,1,1,1,0,0,0,0, 1,1,1,1,0,0,0,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,1,1,0,0,0,0, 0,1,0,1,0,0,0,0, /* 6 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 7 */ + BITMASK32(1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, /* 8 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 9 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* a */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* b */ + BITMASK32(1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, /* c */ + 1,1,1,1,0,0,0,0, 1,1,1,1,1,1,1,1), /* d */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* e */ + 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,1,1) /* f */ +}; +#define CHECK_MODRM(v) CHECK_TABLE(modrm_t, v) +#else +#define CHECK_MODRM(v) (__extension__ ({ \ + register BYTE __a=(v)&0xfc, __b=(v)&0xfe; \ + ((v)&0xc4)==0x00||((v)&0xf0)==0x80||((v)&0xf8)==0xd8||((v)&0xf6)==0xf6|| \ + __a==0xc4||__a==0xd0||__b==0x62||__b==0xc0|| \ + (v)==0x69||(v)==0x6b; \ +})) +#endif + +/* CHECK_TEST */ +#define CHECK_TEST(v) ((v)==0xf6||(v)==0xf7) + +/* CHECK_DATA1 */ +#if defined(USE_T) && (USE_T & DATA1_T) +const static unsigned int data1_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(0,0,0,0,1,0,0,0, 0,0,0,0,1,0,0,0, /* 0 */ + 0,0,0,0,1,0,0,0, 0,0,0,0,1,0,0,0), /* 1 */ + BITMASK32(0,0,0,0,1,0,0,0, 0,0,0,0,1,0,0,0, /* 2 */ + 0,0,0,0,1,0,0,0, 0,0,0,0,1,0,0,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,1,1,0,0,0,0, /* 6 */ + 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1), /* 7 */ + BITMASK32(1,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0, /* 8 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 9 */ + BITMASK32(0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0, /* a */ + 1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0), /* b */ + BITMASK32(1,1,0,0,0,0,1,0, 1,0,0,0,0,1,0,0, /* c */ + 0,0,0,0,1,1,0,0, 0,0,0,0,0,0,0,0), /* d */ + BITMASK32(1,1,1,1,1,1,1,1, 0,0,0,1,0,0,0,0, /* e */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) /* f */ +}; +#define CHECK_DATA1(v) CHECK_TABLE(data1_t, v) +#else +#define CHECK_DATA1(v) (__extension__ ({ \ + register BYTE __a=(v)&0xf8, __b=(v)&0xfe; \ + ((v)&0xf0)==0x70||((v)&0xc7)==0x04|| \ + __a==0xb0||__a==0xe0||__b==0x6a||__b==0x82||__b==0xc0||__b==0xd4|| \ + (v)==0x80||(v)==0xa8||(v)==0xc6||(v)==0xc8||(v)==0xcd||(v)==0xeb; \ +})) +#endif + +/* CHECK_DATA2 */ +#if defined(USE_T) && (USE_T & DATA2_T) +const static unsigned int data2_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 0 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 1 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 2 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 6 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 7 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 8 */ + 0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0), /* 9 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* a */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* b */ + BITMASK32(0,0,1,0,0,0,0,0, 1,0,1,0,0,0,0,0, /* c */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* d */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0, /* e */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) /* f */ +}; +#define CHECK_DATA2(v) CHECK_TABLE(data2_t, v) +#else +#define CHECK_DATA2(v) \ + ((v)==0x9a||(v)==0xc2||(v)==0xc8||(v)==0xca||(v)==0xea) +#endif + +/* CHECK_DATA66 */ +#if defined(USE_T) && (USE_T & DATA66_T) +const static unsigned int data66_t[] = { + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + BITMASK32(0,0,0,0,0,1,0,0, 0,0,0,0,0,1,0,0, /* 0 */ + 0,0,0,0,0,1,0,0, 0,0,0,0,0,1,0,0), /* 1 */ + BITMASK32(0,0,0,0,0,1,0,0, 0,0,0,0,0,1,0,0, /* 2 */ + 0,0,0,0,0,1,0,0, 0,0,0,0,0,1,0,0), /* 3 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 4 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 5 */ + BITMASK32(0,0,0,0,0,0,0,0, 1,1,0,0,0,0,0,0, /* 6 */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* 7 */ + BITMASK32(0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, /* 8 */ + 0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0), /* 9 */ + BITMASK32(0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0, /* a */ + 0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1), /* b */ + BITMASK32(0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, /* c */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0), /* d */ + BITMASK32(0,0,0,0,0,0,0,0, 1,1,1,0,0,0,0,0, /* e */ + 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0) /* f */ +}; +#define CHECK_DATA66(v) CHECK_TABLE(data66_t, v) +#else +#define CHECK_DATA66(v) \ + (((v)&0xc7)==0x05||((v)&0xf8)==0xb8||((v)&0x7e)==0x68|| \ + (v)==0x81||(v)==0x9a||(v)==0xa9||(v)==0xc7||(v)==0xea) +#endif + +/* CHECK_MEM67 */ +#define CHECK_MEM67(v) (((v)&0xfc)==0xa0) + +#endif