Exemplo n.º 1
0
void main(int argc, char* argv[])
{
	OpenSharedMemory();
	printf("Type 1 to write to a position in the memory area.\n");
	printf("Type 2 to read from a position in the momery area.\n");
	printf("Type 3 or any other key to quit.\n");

	int todo=0;
	int pos=0,value=0;
	scanf_s("%i",&todo);
	while ((todo>0)&&(todo<3))
	{
		if (todo==1)
		{
			printf("Input position to write into the memory area\n");
			scanf_s("%i",&pos);
			while(pos<1)
			{
				printf("Position must be positive\n");
				scanf_s("%i",&pos);
			}
			printf("Input value to write into the memory area on position %i\n",pos);
			scanf_s("%i",&value);
			while(value<1)
			{
				printf("Value must be positive\n");
				scanf_s("%i",&value);
			}
  			WriteOnSharedMemory(value, pos); // performs the writing
			printf("Wrote %d to position %d.\n",value,pos);

			printf("Type 1 to write to a position in the memory area.\n");
			printf("Type 2 to read from a position in the momery area.\n");
			printf("Type 3 or any other key to quit.\n");
			scanf_s("%i",&todo);
		}
		if (todo==2)
		{
			printf("Input position to read from the memory area\n");
			scanf_s("%i",&pos);
			while(pos<1)
			{
				printf("Position must be positive\n");
				scanf_s("%i",&pos);
			}
			
			ReadFromSharedMemory(&value, pos); // performs the writing
			printf("Read %d from position %d.\n",value,pos);

			printf("Type 1 to write to a position in the memory area.\n");
			printf("Type 2 to read from a position in the momery area.\n");
			printf("Type 3 or any other key to quit.\n");
			scanf_s("%i",&todo);
		}
	}
}
Exemplo n.º 2
0
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
		break;

	case DLL_PROCESS_ATTACH:
		g_hDLL = hModule;
		if( IsRagnarokApp() )
		{
			TCHAR temppath[MAX_PATH];
			::DisableThreadLibraryCalls( hModule );
			CreateTinyConsole();
			OpenSharedMemory();
#ifndef JRO_CLIENT_STRUCTURE
			InstallProxyFunction(
				_T("ws2_32.dll"), "recv",
				ProxyWS2_32_recv, (LPVOID*)&OrigWS2_32_recv);
#endif
			InstallProxyFunction(
				_T("ddraw.dll"),  "DirectDrawCreateEx", 
				ProxyDirectDrawCreateEx, (LPVOID*)&OrigDirectDrawCreateEx);
			InstallProxyFunction(
				_T("dinput.dll"), "DirectInputCreateA",
				ProxyDirectInputCreateA, (LPVOID*)&OrigDirectInputCreateA);

			if( g_pSharedData ){
				::GetCurrentDirectory(MAX_PATH,temppath);
				strcat_s( temppath,"\\BGM\\");

				::MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,
					temppath,strlen(temppath)+1,
					g_pSharedData->musicfilename,MAX_PATH);
				g_FreeMouseSw = g_pSharedData->freemouse;
				if( g_pSharedData->_44khz_audiomode )
					RagexeSoundRateFixer();
			}

		}
		break;
	case DLL_PROCESS_DETACH:
		if( IsRagnarokApp() )
		{
			ReleaseTinyConsole();
			ReleaseSharedMemory();
		}
		break;
	}
	return TRUE;
}
Exemplo n.º 3
0
static bool GetLargestEntrySize (APRGlobalStorage *storage_p, unsigned int *size_p)
{
	bool success_flag = false;
	unsigned int *largest_size_p = (unsigned int *) OpenSharedMemory (storage_p -> ags_largest_entry_memory_id, 0);

	if (largest_size_p)
		{
			*size_p =	*largest_size_p;

			CloseSharedMemory (largest_size_p);
			success_flag = true;
		}
	else
		{
			PrintErrors (STM_LEVEL_SEVERE, __FILE__, __LINE__, "Failed to open shared memory %d for largest size entry", storage_p -> ags_largest_entry_memory_id);
		}

	return success_flag;
}
Exemplo n.º 4
0
EXTERN_C BOOL WINAPI
DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    const char *szNewDllName = NULL;
    const char *szNewDllBaseName;

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        g_hThisModule = hinstDLL;

        /*
         * Calling LoadLibrary inside DllMain is strongly discouraged.  But it
         * works quite well, provided that the loaded DLL does not require or do
         * anything special in its DllMain, which seems to be the general case.
         *
         * See also:
         * - http://stackoverflow.com/questions/4370812/calling-loadlibrary-from-dllmain
         * - http://msdn.microsoft.com/en-us/library/ms682583
         */

        if (!USE_SHARED_MEM) {
            szNewDllName = getenv("INJECT_DLL");
            if (!szNewDllName) {
                debugPrintf("inject: warning: INJECT_DLL not set\n");
                return FALSE;
            }
        } else {
            SharedMem *pSharedMem = OpenSharedMemory(NULL);
            if (!pSharedMem) {
                debugPrintf("inject: error: failed to open shared memory\n");
                return FALSE;
            }

            VERBOSITY = pSharedMem->cVerbosity;

            static char szSharedMemCopy[MAX_PATH];
            strncpy(szSharedMemCopy, pSharedMem->szDllName, _countof(szSharedMemCopy) - 1);
            szSharedMemCopy[_countof(szSharedMemCopy) - 1] = '\0';

            szNewDllName = szSharedMemCopy;
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_ATTACH\n");
        }

        if (VERBOSITY > 0) {
            char szProcess[MAX_PATH];
            GetModuleFileNameA(NULL, szProcess, sizeof szProcess);
            debugPrintf("inject: attached to process %s\n", szProcess);
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: loading %s\n", szNewDllName);
        }

        g_hHookModule = LoadLibraryA(szNewDllName);
        if (!g_hHookModule) {
            debugPrintf("inject: warning: failed to load %s\n", szNewDllName);
            return FALSE;
        }

        // Ensure we use kernel32.dll's CreateProcessAsUserW, and not advapi32.dll's.
        {
            HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
            assert(hKernel32);
            pfnCreateProcessAsUserW = (PFNCREATEPROCESSASUSERW)GetProcAddress(hKernel32, "CreateProcessAsUserW");
            assert(pfnCreateProcessAsUserW);
        }

        /*
         * Hook kernel32.dll functions, and its respective Windows API Set.
         *
         * http://msdn.microsoft.com/en-us/library/dn505783.aspx (Windows 8.1)
         * http://msdn.microsoft.com/en-us/library/hh802935.aspx (Windows 8)
         */

        registerLibraryLoaderHooks("kernel32.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-1.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-2-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-1.dll");

        registerProcessThreadsHooks("kernel32.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-0.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-1.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-2.dll");

        szNewDllBaseName = getBaseName(szNewDllName);
        if (stricmp(szNewDllBaseName, "dxgitrace.dll") == 0) {
            registerModuleHooks("dxgi.dll",    g_hHookModule);
            registerModuleHooks("d3d10.dll",   g_hHookModule);
            registerModuleHooks("d3d10_1.dll", g_hHookModule);
            registerModuleHooks("d3d11.dll",   g_hHookModule);
            registerModuleHooks("d3d9.dll",    g_hHookModule); // for D3DPERF_*
        } else if (stricmp(szNewDllBaseName, "d3d9.dll") == 0) {
            registerModuleHooks("d3d9.dll",    g_hHookModule);
            registerModuleHooks("dxva2.dll",   g_hHookModule);
        } else if (stricmp(szNewDllBaseName, "d2d1trace.dll") == 0) {
            registerModuleHooks("d2d1.dll",    g_hHookModule);
            registerModuleHooks("dwrite.dll",  g_hHookModule);
        } else {
            registerModuleHooks(szNewDllBaseName, g_hHookModule);
        }

        dumpRegisteredHooks();

        patchAllModules(ACTION_HOOK);
        break;

    case DLL_THREAD_ATTACH:
        break;

    case DLL_THREAD_DETACH:
        break;

    case DLL_PROCESS_DETACH:
        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_DETACH\n");
        }

        assert(!lpvReserved);

        patchAllModules(ACTION_UNHOOK);

        if (g_hHookModule) {
            FreeLibrary(g_hHookModule);
        }
        break;
    }
    return TRUE;
}
Exemplo n.º 5
0
int
main(int argc, char *argv[])
{
    BOOL bDebug = FALSE;
    BOOL bAttach = FALSE;
    DWORD dwProcessId = 0;
    DWORD dwThreadId = 0;
    char cVerbosity = 0;

    const char *szDll = NULL;

    int option_index = 0;
    while (true) {
        int opt = getopt_long_only(argc, argv, short_options, long_options, &option_index);
        if (opt == -1) {
            break;
        }
        switch (opt) {
            case 'h':
                help();
                return 0;
            case 'd':
                bDebug = TRUE;
                break;
            case 'D':
                szDll = optarg;
                break;
            case 'p':
                dwProcessId = strtoul(optarg, NULL, 0);
                bAttach = TRUE;
                break;
            case 't':
                dwThreadId = strtoul(optarg, NULL, 0);
                bAttach = TRUE;
                break;
            case 'v':
                ++cVerbosity;
                break;
            default:
                debugPrintf("inject: invalid option '%c'\n", optopt);
                help();
                return 1;
        }
    }

    if (!bAttach) {
        if (argc - optind < 1) {
            debugPrintf("inject: error: insufficient number of arguments\n");
            help();
            return 1;
        }

        if (isNumber(argv[optind])) {
            dwProcessId = atol(argv[optind]);
            bAttach = TRUE;
        } else if (argv[optind][0] == '!') {
            const char *szProcessName = &argv[optind][1];
            dwProcessId = getProcessIdByName(szProcessName);
            if (!dwProcessId) {
                debugPrintf("error: failed to find process %s\n", szProcessName);
                return 1;
            }
            bAttach = TRUE;
        }
    }

    if (!szDll) {
        debugPrintf("inject: error: DLL not specificed\n");
        help();
        return 1;
    }

    HANDLE hSemaphore = NULL;
    if (!USE_SHARED_MEM) {
        SetEnvironmentVariableA("INJECT_DLL", szDll);
    } else {
        hSemaphore = CreateSemaphore(NULL, 1, 1, "inject_semaphore");
        if (hSemaphore == NULL) {
            debugPrintf("error: failed to create semaphore\n");
            return 1;
        }

        DWORD dwWait = WaitForSingleObject(hSemaphore, 0);
        if (dwWait == WAIT_TIMEOUT) {
            debugPrintf("info: waiting for another inject instance to finish\n");
            dwWait = WaitForSingleObject(hSemaphore, INFINITE);
        }
        if (dwWait != WAIT_OBJECT_0) {
            debugPrintf("error: failed to enter semaphore gate\n");
            return 1;
        }

        SharedMem *pSharedMem = OpenSharedMemory();
        if (!pSharedMem) {
            debugPrintf("error: failed to open shared memory\n");
            return 1;
        }

        pSharedMem->cVerbosity = cVerbosity;

        strncpy(pSharedMem->szDllName, szDll, _countof(pSharedMem->szDllName) - 1);
        pSharedMem->szDllName[_countof(pSharedMem->szDllName) - 1] = '\0';
    }

    BOOL bAttachDwm = FALSE;
    PROCESS_INFORMATION processInfo;
    HANDLE hProcess;
    if (bAttach) {
        BOOL bRet;
        HANDLE hToken   = NULL;
        bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
        if (!bRet) {
            debugPrintf("error: OpenProcessToken returned %u\n", (unsigned)bRet);
            return 1;
        }

        LUID Luid;
        bRet = LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Luid);
        if (!bRet) {
            debugPrintf("error: LookupPrivilegeValue returned %u\n", (unsigned)bRet);
            return 1;
        }

        TOKEN_PRIVILEGES tp;
        tp.PrivilegeCount = 1;
        tp.Privileges[0].Luid = Luid;
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof tp, NULL, NULL);
        if (!bRet) {
            debugPrintf("error: AdjustTokenPrivileges returned %u\n", (unsigned)bRet);
            return 1;
        }

        DWORD dwDesiredAccess =
            PROCESS_CREATE_THREAD |
            PROCESS_QUERY_INFORMATION |
            PROCESS_QUERY_LIMITED_INFORMATION |
            PROCESS_VM_OPERATION |
            PROCESS_VM_WRITE |
            PROCESS_VM_READ |
            PROCESS_TERMINATE;
        hProcess = OpenProcess(
            dwDesiredAccess,
            FALSE /* bInheritHandle */,
            dwProcessId);
        if (!hProcess) {
            logLastError("failed to open process");
            return 1;
        }

        char szProcess[MAX_PATH];
        DWORD dwRet = GetModuleFileNameEx(hProcess, 0, szProcess, sizeof szProcess);
        assert(dwRet);
        if (dwRet &&
            stricmp(getBaseName(szProcess), "dwm.exe") == 0) {
            bAttachDwm = TRUE;
        }
    } else {
        std::string commandLine;
        char sep = 0;
        for (int i = optind; i < argc; ++i) {
            const char *arg = argv[i];

            if (sep) {
                commandLine.push_back(sep);
            }

            if (needsQuote(arg)) {
                quoteArg(commandLine, arg);
            } else {
                commandLine.append(arg);
            }

            sep = ' ';
        }

        STARTUPINFO startupInfo;
        memset(&startupInfo, 0, sizeof startupInfo);
        startupInfo.cb = sizeof startupInfo;

        // Create the process in suspended state
        if (!CreateProcessA(
               NULL,
               const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
               0, // process attributes
               0, // thread attributes
               TRUE, // inherit handles
               CREATE_SUSPENDED,
               NULL, // environment
               NULL, // current directory
               &startupInfo,
               &processInfo)) {
            DWORD dwLastError = GetLastError();
            fprintf(stderr, "inject: error: failed to execute %s (%lu)\n",
                    commandLine.c_str(), dwLastError);
            if (dwLastError == ERROR_ELEVATION_REQUIRED) {
                fprintf(stderr, "error: target program requires elevated priviledges and must be started from an Administrator Command Prompt, or UAC must be disabled\n");
            }
            return 1;
        }

        hProcess = processInfo.hProcess;
    }

    /*
     * XXX: Mixed architecture don't quite work.  See also
     * http://www.corsix.org/content/dll-injection-and-wow64
     */
    {
        typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
        PFNISWOW64PROCESS pfnIsWow64Process;
        pfnIsWow64Process = (PFNISWOW64PROCESS)
            GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
        if (pfnIsWow64Process) {
            BOOL isParentWow64 = FALSE;
            BOOL isChildWow64 = FALSE;
            if (pfnIsWow64Process(GetCurrentProcess(), &isParentWow64) &&
                pfnIsWow64Process(hProcess, &isChildWow64) &&
                isParentWow64 != isChildWow64) {
                debugPrintf("error: binaries mismatch: you need to use the "
#ifdef _WIN64
                        "32-bits"
#else
                        "64-bits"
#endif
                        " apitrace binaries to trace this application\n");
                TerminateProcess(hProcess, 1);
                return 1;
            }
        }
    }

    if (bAttachDwm && IsWindows8OrGreater()) {
        // Switch to Microsoft Basic Display Driver before injecting, so that
        // we don't trace with it.
        devconDisable(DEVCON_CLASS_DISPLAY);
        Sleep(1000);
    }

    const char *szDllName;
    szDllName = "injectee.dll";

    char szDllPath[MAX_PATH];
    GetModuleFileNameA(NULL, szDllPath, sizeof szDllPath);
    getDirName(szDllPath);
    strncat(szDllPath, szDllName, sizeof szDllPath - strlen(szDllPath) - 1);

    if (bDebug) {
        if (!attachDebugger(GetProcessId(hProcess))) {
            if (!bAttach) {
                TerminateProcess(hProcess, 1);
            }
            return 1;
        }
    }

#if 1
    if (!injectDll(hProcess, szDllPath)) {
        if (!bAttach) {
            TerminateProcess(hProcess, 1);
        }
        return 1;
    }
#endif

    DWORD exitCode;

    if (bAttach) {
        if (bAttachDwm) {
            restartDwmComposition(hProcess);
        } else {
            fprintf(stderr, "Press any key when finished tracing\n");
            getchar();

            ejectDll(hProcess, szDllPath);
        }

        if (dwThreadId) {
            HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, TRUE, dwThreadId);
            if (hThread) {
                ResumeThread(hThread);
                WaitForSingleObject(hThread, INFINITE);
                CloseHandle(hThread);
            } else {
                debugPrintf("inject: failed to open thread %lu\n", dwThreadId);
            }
            return 0;
        }

        exitCode = 0;
    } else {
        // Start main process thread
        ResumeThread(processInfo.hThread);

        // Wait for it to finish
        WaitForSingleObject(hProcess, INFINITE);

        if (pSharedMem && !pSharedMem->bReplaced) {
            debugPrintf("warning: %s was never used: application probably does not use this API\n", szDll);
        }

        exitCode = ~0;
        GetExitCodeProcess(hProcess, &exitCode);

        CloseHandle(processInfo.hThread);
    }

    CloseHandle(hProcess);

    if (hSemaphore) {
        ReleaseSemaphore(hSemaphore, 1, NULL);
        CloseHandle(hSemaphore);
    }

    return (int)exitCode;
}
Exemplo n.º 6
0
extern "C" bool __declspec(dllexport) DXISetupEx(HWND WindowHandle, unsigned int Width, unsigned int Height)
{
    DWORD PID = 0;
    GetWindowThreadProcessId(WindowHandle, &PID);
    return OpenSharedMemory(PID, Width, Height);
}
Exemplo n.º 7
0
static DWORD StoreConnectionInfo(
    IN LPCWSTR LocalName,
    IN LPCWSTR ConnectionName,
    IN USHORT ConnectionNameLength,
    IN LPNETRESOURCE lpNetResource)
{
    DWORD status;
    HANDLE hMutex, hMemory;
    PNFS41NP_SHARED_MEMORY pSharedMemory;
    PNFS41NP_NETRESOURCE pNfs41NetResource;
    INT Index;
    BOOLEAN FreeEntryFound = FALSE;

#ifdef __REACTOS__
    status = OpenSharedMemory(&hMutex, &hMemory, (PVOID *)&pSharedMemory);
#else
    status = OpenSharedMemory(&hMutex, &hMemory, &(PVOID)pSharedMemory);
#endif
    if (status)
        goto out;

    DbgP((TEXT("StoreConnectionInfo: NextIndex %d, NumResources %d\n"),
        pSharedMemory->NextAvailableIndex,
        pSharedMemory->NumberOfResourcesInUse));

    for (Index = 0; Index < pSharedMemory->NextAvailableIndex; Index++)
    {
        if (!pSharedMemory->NetResources[Index].InUse)
        {
            FreeEntryFound = TRUE;
            DbgP((TEXT("Reusing existing index %d\n"), Index));
            break;
        }
    }

    if (!FreeEntryFound)
    {
        if (pSharedMemory->NextAvailableIndex >= NFS41NP_MAX_DEVICES) {
            status = WN_NO_MORE_DEVICES;
            goto out_close;
        }
        Index = pSharedMemory->NextAvailableIndex++;
        DbgP((TEXT("Using new index %d\n"), Index));
    }

    pSharedMemory->NumberOfResourcesInUse += 1;

    pNfs41NetResource = &pSharedMemory->NetResources[Index];

    pNfs41NetResource->InUse                = TRUE;
    pNfs41NetResource->dwScope              = lpNetResource->dwScope;
    pNfs41NetResource->dwType               = lpNetResource->dwType;
    pNfs41NetResource->dwDisplayType        = lpNetResource->dwDisplayType;
    pNfs41NetResource->dwUsage              = RESOURCEUSAGE_CONNECTABLE;
    pNfs41NetResource->LocalNameLength      = (USHORT)(wcslen(LocalName) + 1) * sizeof(WCHAR);
    pNfs41NetResource->RemoteNameLength     = (USHORT)(wcslen(lpNetResource->lpRemoteName) + 1) * sizeof(WCHAR);
    pNfs41NetResource->ConnectionNameLength = ConnectionNameLength;

    StringCchCopy(pNfs41NetResource->LocalName,
        pNfs41NetResource->LocalNameLength,
        LocalName);
    StringCchCopy(pNfs41NetResource->RemoteName,
        pNfs41NetResource->RemoteNameLength,
        lpNetResource->lpRemoteName);
    StringCchCopy(pNfs41NetResource->ConnectionName,
        pNfs41NetResource->ConnectionNameLength,
        ConnectionName);

    // TODO: copy mount options -cbodley

out_close:
#ifdef __REACTOS__
    CloseSharedMemory(&hMutex, &hMemory, (PVOID *)&pSharedMemory);
#else
    CloseSharedMemory(&hMutex, &hMemory, &(PVOID)pSharedMemory);
#endif
out:
    return status;
}