static PCImgDelayDescr PiddFromDllName(LPCSTR szDll) { PCImgDelayDescr piddRet = NULL; PIMAGE_NT_HEADERS pinh = PinhFromImageBase(HMODULE(&__ImageBase)); // Scan the Delay load IAT/INT for the dll in question // if (pinh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size != 0) { PCImgDelayDescr pidd = PFromRva<PCImgDelayDescr>( pinh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress ); // Check all of the dlls listed up to the NULL one. // while (pidd->rvaDLLName != 0) { // Check to see if it is the DLL we want // Intentionally case sensitive to avoid complication of using the CRT // for those that don't use the CRT...the user can replace this with // a variant of a case insenstive comparison routine. // LPCSTR szDllCur = PFromRva<LPCSTR>(pidd->rvaDLLName); size_t cchDllCur = __strlen(szDllCur); if (cchDllCur == __strlen(szDll) && __memcmp(szDll, szDllCur, cchDllCur) == 0) { piddRet = pidd; break; } pidd++; } } return piddRet; }
static ICompilerPtr NewCompiler() { ICompilerPtr piCompiler; HRESULT hr = piCompiler.CreateInstance(__uuidof(DolphinCompiler)); if (SUCCEEDED(hr)) return piCompiler; if (hr == REGDB_E_CLASSNOTREG) { // Try and register it HINSTANCE hLib = LoadCompiler(); if (hLib) { // It loaded, now try invoking the class factory entry point GETCLASSOBJPROC pfnFactory = (GETCLASSOBJPROC)::GetProcAddress(HMODULE(hLib), "DllGetClassObject"); if (pfnFactory) { // Found the entry point, try retrieving the factory IClassFactoryPtr piFactory; hr = (*pfnFactory)(__uuidof(DolphinCompiler), IID_IClassFactory, (void**)&piFactory); if (SUCCEEDED(hr)) { // Now try creating the VM object directly hr = piFactory->CreateInstance(NULL, __uuidof(ICompiler), (void**)&piCompiler); } } } } return piCompiler; }
st_run_impl() : pInit(NULL), pUnInit(NULL), hCBWnd(NULL), m_AT_HK_module(NULL) { // Support Autotype with Launch Browser and Run Command // Try to load DLL to call back when window active for Autotype #if defined( _DEBUG ) || defined( DEBUG ) TCHAR *dll_name = _T("pws_at_D.dll"); #else TCHAR *dll_name = _T("pws_at.dll"); #endif m_AT_HK_module = HMODULE(pws_os::LoadLibrary(dll_name, pws_os::LOAD_LIBRARY_APP)); if (m_AT_HK_module != NULL) { pws_os::Trace(_T("st_run_impl::st_run_impl - AutoType DLL Loaded: OK\n")); pInit = AT_PROC_BOOL(pws_os::GetFunction(m_AT_HK_module, "AT_HK_Initialise")); pws_os::Trace(_T("st_run_impl::st_run_impl - Found AT_HK_Initialise: %s\n"), pInit != NULL ? _T("OK") : _T("FAILED")); pUnInit = AT_PROC_BOOL(pws_os::GetFunction(m_AT_HK_module, "AT_HK_UnInitialise")); pws_os::Trace(_T("st_run_impl::st_run_impl - Found AT_HK_UnInitialise: %s\n"), pUnInit != NULL ? _T("OK") : _T("FAILED")); pGetVer = AT_PROC_INT(pws_os::GetFunction(m_AT_HK_module, "AT_HK_GetVersion")); pws_os::Trace(_T("st_run_impl::st_run_impl - Found AT_HK_GetVersion: %s\n"), pGetVer != NULL ? _T("OK") : _T("FAILED")); if (pGetVer == NULL || pGetVer() != AT_DLL_VERSION) { pws_os::Trace(_T("st_run_impl::st_run_impl - Unable to determine DLL version") _T(" or incorrect version\n")); BOOL brc = pws_os::FreeLibrary(m_AT_HK_module); pws_os::Trace(_T("st_run_impl::st_run_impl - Free Autotype DLL: %s\n"), brc == TRUE ? _T("OK") : _T("FAILED")); m_AT_HK_module = NULL; } } }
bool pws_os::FreeLibrary(void *handle) { if (handle != NULL) return ::FreeLibrary(HMODULE(handle)) == TRUE; else return false; }
int main(int argc, _TCHAR* argv[]) { struct ControllerStruct { unsigned long eventCount; //event counter, increases with every controller event, //but for some reason not by one. unsigned short up:1, down:1, left:1, right:1, start:1, back:1, l3:1, r3:1, lButton:1, rButton:1, guideButton:1, unknown:1, aButton:1, bButton:1, xButton:1, yButton:1; // button state bitfield unsigned char lTrigger; //Left Trigger unsigned char rTrigger; //Right Trigger short lJoyY; //Left Joystick Y short lJoyx; //Left Joystick X short rJoyY; //Right Joystick Y short rJoyX; //Right Joystick X }; //First create an HINSTANCE of the xinput1_3.dll. Probably should use system variables to find it //but whatever. HINSTANCE hGetProcIDDLL = LoadLibrary("C:/Windows/System32/xinput1_3.dll"); //In Visual Studio replace this //HINSTANCE hGetProcIDDLL = LoadLibrary(L"C:/Windows/System32/xinput1_3.dll"); //With this //Get the address of ordinal 100. FARPROC lpfnGetProcessID = GetProcAddress(HMODULE(hGetProcIDDLL), (LPCSTR)100); //typedef the function. It takes an int and a pointer to a ControllerStruct and returns an error code //as an int. it's 0 for no error and 1167 for "controller not present". presumably there are others //but I never saw them. It won't cause a crash on error, it just won't update the data. typedef int(__stdcall * pICFUNC)(int, ControllerStruct &); //Assign it to getControllerData for easier use pICFUNC getControllerData; getControllerData = pICFUNC(lpfnGetProcessID); //Create in an instance of the ControllerStruct ControllerStruct buttons; while(1) //Infinite polling loop { getControllerData(0, buttons); //call the function with the controller number(zero based) and //the pointer to the ControllerStruct. ClearScreen(); //clear the screen std::cout << buttons.guideButton; //simply access the variable like normal. Easy peasy. Sleep(50); //pause briefly so as not to spam the console } //in a real program you should release the dll by calling FreeLibrary(hGetProcIDDLL) to prevent memory //leaks, but since there's no way of cleanly exiting this program, I'm not sure where to put it return 0; }
int _tmain(int argc, _TCHAR* argv[]) { /* get handle to dll */ HINSTANCE hGetProcIDDLL = LoadLibrary("E:\\SteamLibrary\\SteamApps\\common\\Arma 3\\@MFD\\MFD_Extension.dll"); /* get pointer to the function in the dll*/ FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"_RVExtension@12"); if(lpfnGetProcessID == NULL) { DWORD lastError = GetLastError(); std::cout << "General failure. GetLastError returned " << std::hex << lastError << "."; } /* Define the Function in the DLL for reuse. This is just prototyping the dll's function. A mock of it. Use "stdcall" for maximum compatibility. */ typedef void (__stdcall * pICFUNC)(char *, int,char*); pICFUNC dllExtension; dllExtension = pICFUNC(lpfnGetProcessID); //-noPause -nosplash -mod=@CBA_A3;@JayArmA2Lib;@ACRE;@fhq_m4_a3;RH_pdw1.0;@fhq_accessories;@ac130x_a3;@MFD;@JS_JC_FA18 -showScriptErrors "C:\Users\bonilann\Documents\Arma 3 - Other Profiles\annerajb\missions\mfdtest.Stratis\mission.sqm" /* The actual call to the function contained in the dll */ char* output = new char[4096]; memset(output,0,4096); dllExtension(output, 4096,"version"); //output should be version# // dllExtension(output, 4096,"pack|81=0/80=0"); Sleep(5000); while(1) { dllExtension(output, 4096,"pack|81=1/81=0/302=12.5000"); } delete[] output; /* Release the Dll */ FreeLibrary(hGetProcIDDLL); return 0; }
void savingThread() { /* get handle to dll */ HINSTANCE hGetProcIDDLL = LoadLibrary("xsens_dll.dll"); /* get pointer to the function in the dll*/ FARPROC lpfnGetProcessID1 = GetProcAddress(HMODULE (hGetProcIDDLL),"XSENS_create"); FARPROC lpfnGetProcessID2 = GetProcAddress(HMODULE (hGetProcIDDLL),"XSENS_doTheMeasurements"); FARPROC lpfnGetProcessID3 = GetProcAddress(HMODULE (hGetProcIDDLL),"XSENS_getData"); /* Define the Function in the DLL for reuse. This is just prototyping the dll's function. A mock of it. Use "stdcall" for maximum compatibility. */ typedef void* (__cdecl * pICFUNC1)(int); typedef void (__cdecl * pICFUNC2)(void*); typedef void (__cdecl * pICFUNC3)(void*, double* , double* , double* , double* , double*); pICFUNC1 connectAtComport; pICFUNC2 doTheMeasurement; pICFUNC3 getTheMeasurement; connectAtComport = pICFUNC1(lpfnGetProcessID1); doTheMeasurement = pICFUNC2(lpfnGetProcessID2); getTheMeasurement = pICFUNC3(lpfnGetProcessID3); /* The actual call to the function contained in the dll */ void * xsens = connectAtComport(6); double temp; double acc[4]; double quat[4]; double gyr[4]; double mag[4]; std::ofstream zap; zap.open("Xsense.data"); printf("Ready to start the experiment\n"); while(true) { if ( j >= i ) { if ( experiment_end == 1) break; doTheMeasurement(xsens); } else { getTheMeasurement(xsens,&temp,acc,quat,gyr,mag); zap << temp << " | " << acc[0] << " " << acc[1] << " " << acc[2] << " | "; zap << quat[0] << " "<< quat[1]<< " "<< quat[2] << " "<< quat[3] << " | "; zap << gyr[0] << " "<<gyr[1]<< " "<<gyr[2]<< " | "; zap << mag[0] << " "<<mag[1]<< " "<<mag[2]<< std::endl; j++; } //printf("i, j : %d , %d\n", i, j); } /* Release the Dll */ FreeLibrary(hGetProcIDDLL); zap.close(); }
FARPROC WINAPI __delayLoadHelper2( PCImgDelayDescr pidd, FARPROC * ppfnIATEntry ) { // Set up some data we use for the hook procs but also useful for // our own use // InternalImgDelayDescr idd = { pidd->grAttrs, PFromRva<LPCSTR>(pidd->rvaDLLName), PFromRva<HMODULE*>(pidd->rvaHmod), PFromRva<PImgThunkData>(pidd->rvaIAT), PFromRva<PCImgThunkData>(pidd->rvaINT), PFromRva<PCImgThunkData>(pidd->rvaBoundIAT), PFromRva<PCImgThunkData>(pidd->rvaUnloadIAT), pidd->dwTimeStamp }; DelayLoadInfo dli = { sizeof DelayLoadInfo, pidd, ppfnIATEntry, idd.szName, { 0 }, 0, 0, 0 }; if (0 == (idd.grAttrs & dlattrRva)) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_INVALID_PARAMETER), 0, 1, PULONG_PTR(rgpdli) ); return 0; } HMODULE hmod = *idd.phmod; // Calculate the index for the IAT entry in the import address table // N.B. The INT entries are ordered the same as the IAT entries so // the calculation can be done on the IAT side. // const unsigned iIAT = IndexFromPImgThunkData(PCImgThunkData(ppfnIATEntry), idd.pIAT); const unsigned iINT = iIAT; PCImgThunkData pitd = &(idd.pINT[iINT]); dli.dlp.fImportByName = !IMAGE_SNAP_BY_ORDINAL(pitd->u1.Ordinal); if (dli.dlp.fImportByName) { dli.dlp.szProcName = LPCSTR(PFromRva<PIMAGE_IMPORT_BY_NAME>(RVA(UINT_PTR(pitd->u1.AddressOfData)))->Name); } else { dli.dlp.dwOrdinal = DWORD(IMAGE_ORDINAL(pitd->u1.Ordinal)); } // Call the initial hook. If it exists and returns a function pointer, // abort the rest of the processing and just return it for the call. // FARPROC pfnRet = NULL; if (__pfnDliNotifyHook2) { pfnRet = ((*__pfnDliNotifyHook2)(dliStartProcessing, &dli)); if (pfnRet != NULL) { goto HookBypass; } } // Check to see if we need to try to load the library. // if (hmod == 0) { if (__pfnDliNotifyHook2) { hmod = HMODULE(((*__pfnDliNotifyHook2)(dliNotePreLoadLibrary, &dli))); } if (hmod == 0) { hmod = ::LoadLibraryEx(dli.szDll, NULL, 0); } if (hmod == 0) { dli.dwLastError = ::GetLastError(); if (__pfnDliFailureHook2) { // when the hook is called on LoadLibrary failure, it will // return 0 for failure and an hmod for the lib if it fixed // the problem. // hmod = HMODULE((*__pfnDliFailureHook2)(dliFailLoadLib, &dli)); } if (hmod == 0) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND), 0, 1, PULONG_PTR(rgpdli) ); // If we get to here, we blindly assume that the handler of the exception // has magically fixed everything up and left the function pointer in // dli.pfnCur. // return dli.pfnCur; } } // Store the library handle. If it is already there, we infer // that another thread got there first, and we need to do a // FreeLibrary() to reduce the refcount // HMODULE hmodT = HMODULE(InterlockedExchangePointer((PVOID *) idd.phmod, PVOID(hmod))); if (hmodT == hmod) { ::FreeLibrary(hmod); } } // Go for the procedure now. // dli.hmodCur = hmod; if (__pfnDliNotifyHook2) { pfnRet = (*__pfnDliNotifyHook2)(dliNotePreGetProcAddress, &dli); } if (pfnRet == 0) { if (pidd->rvaBoundIAT && pidd->dwTimeStamp) { // bound imports exist...check the timestamp from the target image // PIMAGE_NT_HEADERS pinh(PinhFromImageBase(hmod)); if (pinh->Signature == IMAGE_NT_SIGNATURE && TimeStampOfImage(pinh) == idd.dwTimeStamp && FLoadedAtPreferredAddress(pinh, hmod)) { // Everything is good to go, if we have a decent address // in the bound IAT! // pfnRet = FARPROC(UINT_PTR(idd.pBoundIAT[iIAT].u1.Function)); if (pfnRet != 0) { goto SetEntryHookBypass; } } } pfnRet = ::GetProcAddress(hmod, dli.dlp.szProcName); } if (pfnRet == 0) { dli.dwLastError = ::GetLastError(); if (__pfnDliFailureHook2) { // when the hook is called on GetProcAddress failure, it will // return 0 on failure and a valid proc address on success // pfnRet = (*__pfnDliFailureHook2)(dliFailGetProc, &dli); } if (pfnRet == 0) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND), 0, 1, PULONG_PTR(rgpdli) ); // If we get to here, we blindly assume that the handler of the exception // has magically fixed everything up and left the function pointer in // dli.pfnCur. // pfnRet = dli.pfnCur; } } SetEntryHookBypass: *ppfnIATEntry = pfnRet; HookBypass: if (__pfnDliNotifyHook2) { dli.dwLastError = 0; dli.hmodCur = hmod; dli.pfnCur = pfnRet; (*__pfnDliNotifyHook2)(dliNoteEndProcessing, &dli); } return pfnRet; }
/* closes the shared library */ void closeLibrary(lib_t lib) { FreeLibrary(HMODULE(lib)); }
/* returns address of a symbol from the library */ void* getSymbol(lib_t lib, const std::string& sym) { return GetProcAddress(HMODULE(lib),sym.c_str()); }
void *pws_os::GetFunction(void *handle, const char *name) { ASSERT(handle != NULL && name != NULL); return ::GetProcAddress(HMODULE(handle), name); }
void Environment::loadModule(string lib) { // Type definition of the initialization function typedef const char* (*func)(); // Validate if (lib.empty()) throw DataException("Error: No library name specified for loading"); #ifdef WIN32 // Load the library - The windows way // Change the error mode: we handle errors now, not the operating system UINT em = SetErrorMode(SEM_FAILCRITICALERRORS); HINSTANCE handle = LoadLibraryEx(lib.c_str(),nullptr,LOAD_WITH_ALTERED_SEARCH_PATH); if (!handle) handle = LoadLibraryEx(lib.c_str(), nullptr, 0); if (!handle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), 0, error, 256, nullptr ); throw RuntimeException(error); } SetErrorMode(em); // Restore the previous error mode // Find the initialization routine func inithandle = reinterpret_cast<func>(GetProcAddress(HMODULE(handle), "initialize")); if (!inithandle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), 0, error, 256, nullptr ); throw RuntimeException(error); } #else // Load the library - The UNIX way // Search the frePPLe directories for the library string fullpath = Environment::searchFile(lib); if (fullpath.empty()) throw RuntimeException("Module '" + lib + "' not found"); dlerror(); // Clear the previous error void *handle = dlopen(fullpath.c_str(), RTLD_NOW | RTLD_GLOBAL); const char *err = dlerror(); // Pick up the error string if (err) { // Search the normal path for the library dlerror(); // Clear the previous error handle = dlopen(lib.c_str(), RTLD_NOW | RTLD_GLOBAL); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); } // Find the initialization routine func inithandle = (func)(dlsym(handle, "initialize")); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); #endif // Call the initialization routine with the parameter list string x = (inithandle)(); if (x.empty()) throw DataException("Invalid module"); // Insert the new module in the registry moduleRegistry.insert(x); }